<commit_before>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/config.hpp"

#if defined TORRENT_BSD || defined TORRENT_LINUX
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <net/route.h>
#elif defined TORRENT_WINDOWS
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <iphlpapi.h>
#endif

#include "libtorrent/enum_net.hpp"
#include "libtorrent/broadcast_socket.hpp"
#include <asio/ip/host_name.hpp>

namespace libtorrent
{
	namespace
	{
		address sockaddr_to_address(sockaddr const* sin)
		{
			if (sin->sa_family == AF_INET)
			{
				typedef asio::ip::address_v4::bytes_type bytes_t;
				bytes_t b;
				memcpy(&b[0], &((sockaddr_in const*)sin)->sin_addr, b.size());
				return address_v4(b);
			}
			else if (sin->sa_family == AF_INET6)
			{
				typedef asio::ip::address_v6::bytes_type bytes_t;
				bytes_t b;
				memcpy(&b[0], &((sockaddr_in6 const*)sin)->sin6_addr, b.size());
				return address_v6(b);
			}
			return address();
		}

#ifdef TORRENT_BSD
		bool verify_sockaddr(sockaddr_in* sin)
		{
			return (sin->sin_len == sizeof(sockaddr_in)
				&& sin->sin_family == AF_INET)
				|| (sin->sin_len == sizeof(sockaddr_in6)
				&& sin->sin_family == AF_INET6);
		}
#endif

	}

	bool in_subnet(address const& addr, ip_interface const& iface)
	{
		if (addr.is_v4() != iface.interface_address.is_v4()) return false;
		// since netmasks seems unreliable for IPv6 interfaces
		// (MacOS X returns AF_INET addresses as bitmasks) assume
		// that any IPv6 address belongs to the subnet of any
		// interface with an IPv6 address
		if (addr.is_v6()) return true;

		return (addr.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong())
			== (iface.interface_address.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong());
	}

	bool in_local_network(asio::io_service& ios, address const& addr, asio::error_code& ec)
	{
		std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec);
		if (ec) return false;
		for (std::vector<ip_interface>::const_iterator i = net.begin()
			, end(net.end()); i != end; ++i)
		{
			if (in_subnet(addr, *i)) return true;
		}
		return false;
	}

	std::vector<ip_interface> enum_net_interfaces(asio::io_service& ios, asio::error_code& ec)
	{
		std::vector<ip_interface> ret;
// covers linux, MacOS X and BSD distributions
#if defined TORRENT_LINUX || defined TORRENT_BSD
		int s = socket(AF_INET, SOCK_DGRAM, 0);
		if (s < 0)
		{
			ec = asio::error::fault;
			return ret;
		}
		ifconf ifc;
		char buf[1024];
		ifc.ifc_len = sizeof(buf);
		ifc.ifc_buf = buf;
		if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
		{
			ec = asio::error_code(errno, asio::error::system_category);
			close(s);
			return ret;
		}

		char *ifr = (char*)ifc.ifc_req;
		int remaining = ifc.ifc_len;

		while (remaining)
		{
			ifreq const& item = *reinterpret_cast<ifreq*>(ifr);

			if (item.ifr_addr.sa_family == AF_INET
				|| item.ifr_addr.sa_family == AF_INET6)
			{
				ip_interface iface;
				iface.interface_address = sockaddr_to_address(&item.ifr_addr);

				ifreq netmask = item;
				if (ioctl(s, SIOCGIFNETMASK, &netmask) < 0)
				{
					if (iface.interface_address.is_v6())
					{
						// this is expected to fail (at least on MacOS X)
						iface.netmask = address_v6::any();
					}
					else
					{
						ec = asio::error_code(errno, asio::error::system_category);
						close(s);
						return ret;
					}
				}
				else
				{
					iface.netmask = sockaddr_to_address(&netmask.ifr_addr);
				}
				ret.push_back(iface);
			}

#if defined TORRENT_BSD
			int current_size = item.ifr_addr.sa_len + IFNAMSIZ;
#elif defined TORRENT_LINUX
			int current_size = sizeof(ifreq);
#endif
			ifr += current_size;
			remaining -= current_size;
		}
		close(s);

#elif defined TORRENT_WINDOWS

		SOCKET s = socket(AF_INET, SOCK_DGRAM, 0);
		if (s == SOCKET_ERROR)
		{
			ec = asio::error_code(WSAGetLastError(), asio::error::system_category);
			return ret;
		}

		INTERFACE_INFO buffer[30];
		DWORD size;

		if (WSAIoctl(s, SIO_GET_INTERFACE_LIST, 0, 0, buffer,
			sizeof(buffer), &size, 0, 0) != 0)
		{
			ec = asio::error_code(WSAGetLastError(), asio::error::system_category);
			closesocket(s);
			return ret;
		}
		closesocket(s);

		int n = size / sizeof(INTERFACE_INFO);

		ip_interface iface;
		for (int i = 0; i < n; ++i)
		{
			iface.interface_address = sockaddr_to_address(&buffer[i].iiAddress.Address);
			iface.netmask = sockaddr_to_address(&buffer[i].iiNetmask.Address);
			if (iface.interface_address == address_v4::any()) continue;
			ret.push_back(iface);
		}

#else
#warning THIS OS IS NOT RECOGNIZED, enum_net_interfaces WILL PROBABLY NOT WORK
		// make a best guess of the interface we're using and its IP
		udp::resolver r(ios);
		udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(ec), "0"), ec);
		if (ec) return ret;
		ip_interface iface;
		for (;i != udp::resolver_iterator(); ++i)
		{
			iface.interface_address = i->endpoint().address();
			if (iface.interface_address.is_v4())
				iface.netmask = address_v4::netmask(iface.interface_address.to_v4());
			ret.push_back(iface);
		}
#endif
		return ret;
	}

	address get_default_gateway(asio::io_service& ios, address const& interface, asio::error_code& ec)
	{

#if defined TORRENT_BSD

		struct rt_msg
		{
			rt_msghdr m_rtm;
			char buf[512];
		};

		rt_msg m;
		int len = sizeof(rt_msg);
		bzero(&m, len);
		m.m_rtm.rtm_type = RTM_GET;
		m.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY;
		m.m_rtm.rtm_version = RTM_VERSION;
		m.m_rtm.rtm_addrs = RTA_DST | RTA_GATEWAY;
		m.m_rtm.rtm_seq = 0;
		m.m_rtm.rtm_msglen = len;

		int s = socket(PF_ROUTE, SOCK_RAW, AF_INET);
		if (s == -1)
		{
			ec = asio::error_code(errno, asio::error::system_category);
			return address_v4::any();
		}

		int n = write(s, &m, len);
		if (n == -1)
		{
			ec = asio::error_code(errno, asio::error::system_category);
			close(s);
			return address_v4::any();
		}
		else if (n != len)
		{
			ec = asio::error::operation_not_supported;
			close(s);
			return address_v4::any();
		}
		bzero(&m, len);

		n = read(s, &m, len);
		if (n == -1)
		{
			ec = asio::error_code(errno, asio::error::system_category);
			close(s);
			return address_v4::any();
		}
		close(s);

		TORRENT_ASSERT(m.m_rtm.rtm_seq == 0);
		TORRENT_ASSERT(m.m_rtm.rtm_pid == getpid());
		if (m.m_rtm.rtm_errno)
		{
			ec = asio::error_code(m.m_rtm.rtm_errno, asio::error::system_category);
			return address_v4::any();
		}
		if (m.m_rtm.rtm_flags & RTF_UP == 0
			|| m.m_rtm.rtm_flags & RTF_GATEWAY == 0)
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}
		if (m.m_rtm.rtm_addrs & RTA_DST == 0
			|| m.m_rtm.rtm_addrs & RTA_GATEWAY == 0)
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}
		if (m.m_rtm.rtm_msglen > len)
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}
		int min_len = sizeof(rt_msghdr) + 2 * sizeof(struct sockaddr_in);
		if (m.m_rtm.rtm_msglen < min_len)
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		// default route
		char* p = m.buf;
		sockaddr_in* sin = (sockaddr_in*)p;
		if (!verify_sockaddr(sin))
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		// default gateway
		p += sin->sin_len;
		sin = (sockaddr_in*)p;
		if (!verify_sockaddr(sin))
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		return sockaddr_to_address((sockaddr*)sin);

#elif defined TORRENT_WINDOWS

		// Load Iphlpapi library
		HMODULE iphlp = LoadLibraryA("Iphlpapi.dll");
		if (!iphlp)
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		// Get GetAdaptersInfo() pointer
		typedef DWORD (WINAPI *GetAdaptersInfo_t)(PIP_ADAPTER_INFO, PULONG);
		GetAdaptersInfo_t GetAdaptersInfo = (GetAdaptersInfo_t)GetProcAddress(iphlp, "GetAdaptersInfo");
		if (!GetAdaptersInfo)
		{
			FreeLibrary(iphlp);
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		PIP_ADAPTER_INFO adapter_info = 0;
		ULONG out_buf_size = 0;
		if (GetAdaptersInfo(adapter_info, &out_buf_size) != ERROR_BUFFER_OVERFLOW)
		{
			FreeLibrary(iphlp);
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		adapter_info = (IP_ADAPTER_INFO*)malloc(out_buf_size);
		if (!adapter_info)
		{
			FreeLibrary(iphlp);
			ec = asio::error::no_memory;
			return address_v4::any();
		}

		address ret;
		if (GetAdaptersInfo(adapter_info, &out_buf_size) == NO_ERROR)
		{
			for (PIP_ADAPTER_INFO adapter = adapter_info;
				adapter != 0; adapter = adapter->Next)
			{
				address iface = address::from_string(adapter->IpAddressList.IpAddress.String, ec);
				if (ec)
				{
					ec = asio::error_code();
					continue;
				}
				if (is_loopback(iface) || is_any(iface)) continue;
				if (interface == address() || interface == iface)
				{
					ret = address::from_string(adapter->GatewayList.IpAddress.String, ec);
					break;
				}
			}
		}

		// Free memory
		free(adapter_info);
		FreeLibrary(iphlp);

		return ret;

//#elif defined TORRENT_LINUX
// No linux implementation yet
#else
		if (!interface.is_v4())
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}
		return address_v4((interface.to_v4().to_ulong() & 0xffffff00) | 1);
#endif
	}

}

<commit_msg>fixed FreeBSD build. #284<commit_after>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/config.hpp"

#if defined TORRENT_BSD || defined TORRENT_LINUX
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <net/route.h>
#elif defined TORRENT_WINDOWS
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <iphlpapi.h>
#endif

#include "libtorrent/enum_net.hpp"
#include "libtorrent/broadcast_socket.hpp"
#include <asio/ip/host_name.hpp>

namespace libtorrent
{
	namespace
	{
		address sockaddr_to_address(sockaddr const* sin)
		{
			if (sin->sa_family == AF_INET)
			{
				typedef asio::ip::address_v4::bytes_type bytes_t;
				bytes_t b;
				memcpy(&b[0], &((sockaddr_in const*)sin)->sin_addr, b.size());
				return address_v4(b);
			}
			else if (sin->sa_family == AF_INET6)
			{
				typedef asio::ip::address_v6::bytes_type bytes_t;
				bytes_t b;
				memcpy(&b[0], &((sockaddr_in6 const*)sin)->sin6_addr, b.size());
				return address_v6(b);
			}
			return address();
		}

#ifdef TORRENT_BSD
		bool verify_sockaddr(sockaddr_in* sin)
		{
			return (sin->sin_len == sizeof(sockaddr_in)
				&& sin->sin_family == AF_INET)
				|| (sin->sin_len == sizeof(sockaddr_in6)
				&& sin->sin_family == AF_INET6);
		}
#endif

	}

	bool in_subnet(address const& addr, ip_interface const& iface)
	{
		if (addr.is_v4() != iface.interface_address.is_v4()) return false;
		// since netmasks seems unreliable for IPv6 interfaces
		// (MacOS X returns AF_INET addresses as bitmasks) assume
		// that any IPv6 address belongs to the subnet of any
		// interface with an IPv6 address
		if (addr.is_v6()) return true;

		return (addr.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong())
			== (iface.interface_address.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong());
	}

	bool in_local_network(asio::io_service& ios, address const& addr, asio::error_code& ec)
	{
		std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec);
		if (ec) return false;
		for (std::vector<ip_interface>::const_iterator i = net.begin()
			, end(net.end()); i != end; ++i)
		{
			if (in_subnet(addr, *i)) return true;
		}
		return false;
	}

	std::vector<ip_interface> enum_net_interfaces(asio::io_service& ios, asio::error_code& ec)
	{
		std::vector<ip_interface> ret;
// covers linux, MacOS X and BSD distributions
#if defined TORRENT_LINUX || defined TORRENT_BSD
		int s = socket(AF_INET, SOCK_DGRAM, 0);
		if (s < 0)
		{
			ec = asio::error::fault;
			return ret;
		}
		ifconf ifc;
		char buf[1024];
		ifc.ifc_len = sizeof(buf);
		ifc.ifc_buf = buf;
		if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
		{
			ec = asio::error_code(errno, asio::error::system_category);
			close(s);
			return ret;
		}

		char *ifr = (char*)ifc.ifc_req;
		int remaining = ifc.ifc_len;

		while (remaining)
		{
			ifreq const& item = *reinterpret_cast<ifreq*>(ifr);

			if (item.ifr_addr.sa_family == AF_INET
				|| item.ifr_addr.sa_family == AF_INET6)
			{
				ip_interface iface;
				iface.interface_address = sockaddr_to_address(&item.ifr_addr);

				ifreq netmask = item;
				if (ioctl(s, SIOCGIFNETMASK, &netmask) < 0)
				{
					if (iface.interface_address.is_v6())
					{
						// this is expected to fail (at least on MacOS X)
						iface.netmask = address_v6::any();
					}
					else
					{
						ec = asio::error_code(errno, asio::error::system_category);
						close(s);
						return ret;
					}
				}
				else
				{
					iface.netmask = sockaddr_to_address(&netmask.ifr_addr);
				}
				ret.push_back(iface);
			}

#if defined TORRENT_BSD
			int current_size = item.ifr_addr.sa_len + IFNAMSIZ;
#elif defined TORRENT_LINUX
			int current_size = sizeof(ifreq);
#endif
			ifr += current_size;
			remaining -= current_size;
		}
		close(s);

#elif defined TORRENT_WINDOWS

		SOCKET s = socket(AF_INET, SOCK_DGRAM, 0);
		if (s == SOCKET_ERROR)
		{
			ec = asio::error_code(WSAGetLastError(), asio::error::system_category);
			return ret;
		}

		INTERFACE_INFO buffer[30];
		DWORD size;

		if (WSAIoctl(s, SIO_GET_INTERFACE_LIST, 0, 0, buffer,
			sizeof(buffer), &size, 0, 0) != 0)
		{
			ec = asio::error_code(WSAGetLastError(), asio::error::system_category);
			closesocket(s);
			return ret;
		}
		closesocket(s);

		int n = size / sizeof(INTERFACE_INFO);

		ip_interface iface;
		for (int i = 0; i < n; ++i)
		{
			iface.interface_address = sockaddr_to_address(&buffer[i].iiAddress.Address);
			iface.netmask = sockaddr_to_address(&buffer[i].iiNetmask.Address);
			if (iface.interface_address == address_v4::any()) continue;
			ret.push_back(iface);
		}

#else
#warning THIS OS IS NOT RECOGNIZED, enum_net_interfaces WILL PROBABLY NOT WORK
		// make a best guess of the interface we're using and its IP
		udp::resolver r(ios);
		udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(ec), "0"), ec);
		if (ec) return ret;
		ip_interface iface;
		for (;i != udp::resolver_iterator(); ++i)
		{
			iface.interface_address = i->endpoint().address();
			if (iface.interface_address.is_v4())
				iface.netmask = address_v4::netmask(iface.interface_address.to_v4());
			ret.push_back(iface);
		}
#endif
		return ret;
	}

	address get_default_gateway(asio::io_service& ios, address const& interface, asio::error_code& ec)
	{

#if defined TORRENT_BSD

		struct rt_msg
		{
			rt_msghdr m_rtm;
			char buf[512];
		};

		rt_msg m;
		int len = sizeof(rt_msg);
		bzero(&m, len);
		m.m_rtm.rtm_type = RTM_GET;
		m.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY;
		m.m_rtm.rtm_version = RTM_VERSION;
		m.m_rtm.rtm_addrs = RTA_DST | RTA_GATEWAY;
		m.m_rtm.rtm_seq = 0;
		m.m_rtm.rtm_msglen = len;

		int s = socket(PF_ROUTE, SOCK_RAW, AF_INET);
		if (s == -1)
		{
			ec = asio::error_code(errno, asio::error::system_category);
			return address_v4::any();
		}

		int n = write(s, &m, len);
		if (n == -1)
		{
			ec = asio::error_code(errno, asio::error::system_category);
			close(s);
			return address_v4::any();
		}
		else if (n != len)
		{
			ec = asio::error::operation_not_supported;
			close(s);
			return address_v4::any();
		}
		bzero(&m, len);

		n = read(s, &m, len);
		if (n == -1)
		{
			ec = asio::error_code(errno, asio::error::system_category);
			close(s);
			return address_v4::any();
		}
		close(s);

		TORRENT_ASSERT(m.m_rtm.rtm_seq == 0);
		TORRENT_ASSERT(m.m_rtm.rtm_pid == getpid());
		if (m.m_rtm.rtm_errno)
		{
			ec = asio::error_code(m.m_rtm.rtm_errno, asio::error::system_category);
			return address_v4::any();
		}
		if (m.m_rtm.rtm_flags & RTF_UP == 0
			|| m.m_rtm.rtm_flags & RTF_GATEWAY == 0)
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}
		if (m.m_rtm.rtm_addrs & RTA_DST == 0
			|| m.m_rtm.rtm_addrs & RTA_GATEWAY == 0)
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}
		if (m.m_rtm.rtm_msglen > len)
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}
		int min_len = sizeof(rt_msghdr) + 2 * sizeof(struct sockaddr_in);
		if (m.m_rtm.rtm_msglen < min_len)
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		// default route
		char* p = m.buf;
		sockaddr_in* sin = (sockaddr_in*)p;
		if (!verify_sockaddr(sin))
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		// default gateway
		p += sin->sin_len;
		sin = (sockaddr_in*)p;
		if (!verify_sockaddr(sin))
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		return sockaddr_to_address((sockaddr*)sin);

#elif defined TORRENT_WINDOWS

		// Load Iphlpapi library
		HMODULE iphlp = LoadLibraryA("Iphlpapi.dll");
		if (!iphlp)
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		// Get GetAdaptersInfo() pointer
		typedef DWORD (WINAPI *GetAdaptersInfo_t)(PIP_ADAPTER_INFO, PULONG);
		GetAdaptersInfo_t GetAdaptersInfo = (GetAdaptersInfo_t)GetProcAddress(iphlp, "GetAdaptersInfo");
		if (!GetAdaptersInfo)
		{
			FreeLibrary(iphlp);
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		PIP_ADAPTER_INFO adapter_info = 0;
		ULONG out_buf_size = 0;
		if (GetAdaptersInfo(adapter_info, &out_buf_size) != ERROR_BUFFER_OVERFLOW)
		{
			FreeLibrary(iphlp);
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}

		adapter_info = (IP_ADAPTER_INFO*)malloc(out_buf_size);
		if (!adapter_info)
		{
			FreeLibrary(iphlp);
			ec = asio::error::no_memory;
			return address_v4::any();
		}

		address ret;
		if (GetAdaptersInfo(adapter_info, &out_buf_size) == NO_ERROR)
		{
			for (PIP_ADAPTER_INFO adapter = adapter_info;
				adapter != 0; adapter = adapter->Next)
			{
				address iface = address::from_string(adapter->IpAddressList.IpAddress.String, ec);
				if (ec)
				{
					ec = asio::error_code();
					continue;
				}
				if (is_loopback(iface) || is_any(iface)) continue;
				if (interface == address() || interface == iface)
				{
					ret = address::from_string(adapter->GatewayList.IpAddress.String, ec);
					break;
				}
			}
		}

		// Free memory
		free(adapter_info);
		FreeLibrary(iphlp);

		return ret;

//#elif defined TORRENT_LINUX
// No linux implementation yet
#else
		if (!interface.is_v4())
		{
			ec = asio::error::operation_not_supported;
			return address_v4::any();
		}
		return address_v4((interface.to_v4().to_ulong() & 0xffffff00) | 1);
#endif
	}

}

<|endoftext|>


<commit_before>//===------------- IncrementalRanges.cpp - Generates swiftdeps files
//---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

// These are the definitions for managing serializable source locations so that
// the frontend and the driver can implement incremental compilation based on
// source ranges.

#include "swift/AST/IncrementalRanges.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsCommon.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/FileSystem.h"
#include "swift/AST/SourceFile.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/PersistentParserState.h"
#include "llvm/Support/YAMLParser.h"

using namespace swift;
using namespace incremental_ranges;

//==============================================================================
// MARK: SerializableSourceLocation
//==============================================================================

SerializableSourceLocation::SerializableSourceLocation(
    const SourceLoc loc, const SourceManager &SM) {
  auto lc = SM.getLineAndColumn(loc);
  line = lc.first;
  column = lc.second;
}

const SerializableSourceLocation SerializableSourceLocation::endOfAnyFile = {
    ~decltype(line)(0), 0};

void SerializableSourceLocation::print(raw_ostream &out) const {
  out << line << ":" << column;
}
void SerializableSourceLocation::dump() const { print(llvm::errs()); }

//==============================================================================
// MARK: SerializableSourceRange
//==============================================================================

SerializableSourceRange::SerializableSourceRange(
    SerializableSourceLocation start, SerializableSourceLocation end)
    : start(start), end(end) {
#ifndef NDEBUG
  if (!(start <= end)) {
    llvm::errs() << "*** Error: creating backwards SerializableSourceRange: [";
    start.print(llvm::errs());
    llvm::errs() << " -- ";
    end.print(llvm::errs());
    llvm::errs() << ")\n";
    assert(false && "Detected backwards SerializableSourceRange");
  }
#endif
}

SerializableSourceRange::SerializableSourceRange(const CharSourceRange r,
                                                 const SourceManager &SM)
    : start(SerializableSourceLocation(r.getStart(), SM)),
      end(SerializableSourceLocation(r.getEnd(), SM)) {}

const SerializableSourceRange SerializableSourceRange::wholeFile = {
    {0, 0}, SerializableSourceLocation::endOfAnyFile};

Ranges SerializableSourceRange::RangesForWholeFile() {
  assert(wholeFile.end.line && "Ensure initialization happens");
  return {wholeFile};
}

bool SerializableSourceRange::properlyPreceeds(
    const SerializableSourceRange &other) const {
  return end <= other.start;
}

bool SerializableSourceRange::isProperlySorted(
    ArrayRef<SerializableSourceRange> ranges) {
  Optional<SerializableSourceRange> lastRange;
  for (const auto &thisRange : ranges) {
    if (!lastRange)
      lastRange = thisRange;
    else if (!lastRange->properlyPreceeds(thisRange))
      return false;
  }
  return true;
}

bool SerializableSourceRange::isImproperSubsetOf(
    const SerializableSourceRange &superset) const {
  return superset.start <= start && end <= superset.end;
}

Optional<SerializableSourceRange> SerializableSourceRange::findOutlierIfAny(
    ArrayRef<SerializableSourceRange> subset,
    ArrayRef<SerializableSourceRange> superset) {
  // TODO: could optimize this by exploiting sortedness of the arrays:
  // i.e. could skip searching the start of the superset
  for (const auto &subsetRange : subset) {
    const bool isSubsetRangeContained = subsetRange.isImproperSubsetOfAny(superset);
    if (!isSubsetRangeContained)
      return subsetRange;
  }
  return None;
}

Ranges SerializableSourceRange::findAllOutliers(
    ArrayRef<SerializableSourceRange> subset,
    ArrayRef<SerializableSourceRange> superset) {
  // TODO:  optimize with slice of superset
  Ranges outliers;
  std::copy_if(subset.begin(), subset.end(), std::back_inserter(outliers),
               [&](const SerializableSourceRange &r) {
                 return !r.isImproperSubsetOfAny(superset);
               });
  return outliers;
}

bool SerializableSourceRange::isImproperSubsetOfAny(
    ArrayRef<SerializableSourceRange> supersetRanges) const {
  assert(isProperlySorted(supersetRanges) && "required for binary search");
  const auto firstRangeInSupersetNotBeforeSub =
      std::lower_bound(supersetRanges.begin(), supersetRanges.end(), *this,
                       [](const SerializableSourceRange &superRange,
                          const SerializableSourceRange &subsetRange) {
                         return superRange.properlyPreceeds(subsetRange);
                       });
  const bool result =
      firstRangeInSupersetNotBeforeSub != supersetRanges.end() &&
      isImproperSubsetOf(*firstRangeInSupersetNotBeforeSub);

  // slow if input is too big
  assert((supersetRanges.size() >= 5 ||
          result == isImproperSubsetOfAnySlowlyAndSimply(supersetRanges)) &&
         "Check against reference");

  return result;
}

bool SerializableSourceRange::isImproperSubsetOfAnySlowlyAndSimply(
    ArrayRef<SerializableSourceRange> supersetRanges) const {
  return llvm::any_of(supersetRanges,
                      [&](const SerializableSourceRange &superset) {
                        return isImproperSubsetOf(superset);
                      });
}

std::string SerializableSourceRange::printString() const {
  std::string result;
  llvm::raw_string_ostream out(result);
  print(out);
  return out.str();
}

void SerializableSourceRange::print(raw_ostream &out) const {
  out << "[";
  start.print(out);
  out << "--";
  end.print(out);
  out << ")";
}
void SerializableSourceRange::dump() const { print(llvm::errs()); }

//==============================================================================
// MARK: SwiftRangesEmitter
//==============================================================================

bool SwiftRangesEmitter::emit() const {
  const bool hadError =
      withOutputFile(diags, outputPath, [&](llvm::raw_pwrite_stream &out) {
        out << SwiftRangesFileContents::header;
        emitRanges(out);
        return false;
      });
  if (!hadError)
    return false;
  diags.diagnose(SourceLoc(), diag::error_unable_to_write_swift_ranges_file,
                 outputPath, "Output error");
  return true;
}

void SwiftRangesEmitter::emitRanges(llvm::raw_ostream &out) const {
  SwiftRangesFileContents wholeFileContents(
      collectSerializedUnparsedRangesByNonPrimary(),
      collectSortedSerializedNoninlinableFunctionBodies());
  llvm::yaml::Output yamlWriter(out);
  yamlWriter << wholeFileContents;
}

RangesByFilename
SwiftRangesEmitter::collectSerializedUnparsedRangesByNonPrimary() const {
  auto rangesByNonprimary = collectUnparsedRanges();
  std::map<std::string, std::vector<SerializableSourceRange>>
      serializedRangesByNonprimary;
  // The driver counts on getting coalescedSortedRanges because it
  // does binary chop searches
  for (auto &nonPriAndRanges : rangesByNonprimary)
    serializedRangesByNonprimary.insert(
        {nonPriAndRanges.first, serializeRanges(coalesceSortedRanges(sortRanges(
                                    std::move(nonPriAndRanges.second))))});
  return serializedRangesByNonprimary;
}

Ranges
SwiftRangesEmitter::collectSortedSerializedNoninlinableFunctionBodies() const {
  return serializeRanges(sortRanges(collectNoninlinableFunctionBodies()));
}

std::vector<CharSourceRange>
SwiftRangesEmitter::collectNoninlinableFunctionBodies() const {
  struct FnBodyCollector : ASTWalker {
    const SourceManager &SM;
    FnBodyCollector(const SourceManager &SM) : SM(SM) {}

    std::vector<CharSourceRange> ranges;
    bool walkToDeclPre(Decl *D) override {
      if (const auto *AFD = dyn_cast<AbstractFunctionDecl>(D)) {
        if (!AFD->getAttrs().hasAttribute<InlinableAttr>()) {
          auto sr = AFD->getBodySourceRange();
          if (sr.isValid())
            ranges.push_back(Lexer::getCharSourceRangeFromSourceRange(SM, sr));
        }
        return false;
      }
      return true;
    }
  };
  FnBodyCollector collector(sourceMgr);
  primaryFile->walk(collector);
  return collector.ranges;
}

std::map<std::string, std::vector<CharSourceRange>>
SwiftRangesEmitter::collectUnparsedRanges() const {
  std::map<std::string, std::vector<CharSourceRange>> rangesByNonprimaryFile;
  persistentState.forEachDelayedSourceRange(
      primaryFile, [&](const SourceRange sr) {
        const auto filename = sourceMgr.getIdentifierForBuffer(
            sourceMgr.findBufferContainingLoc(sr.Start));
        const auto csr =
            Lexer::getCharSourceRangeFromSourceRange(sourceMgr, sr);
        rangesByNonprimaryFile[filename].push_back(csr);
      });
  return rangesByNonprimaryFile;
}

std::vector<CharSourceRange>
SwiftRangesEmitter::sortRanges(std::vector<CharSourceRange> ranges) const {
  std::sort(ranges.begin(), ranges.end(),
            [&](const CharSourceRange &lhs, const CharSourceRange &rhs) {
              return sourceMgr.isBeforeInBuffer(lhs.getStart(), rhs.getStart());
            });
  return ranges;
}

std::vector<CharSourceRange> SwiftRangesEmitter::coalesceSortedRanges(
    std::vector<CharSourceRange> ranges) const {
  auto toBeWidened = ranges.begin();
  auto candidate = toBeWidened + 1;
  while (candidate < ranges.end()) {
    if (isImmediatelyBeforeOrOverlapping(*toBeWidened, *candidate))
      toBeWidened->widen(*candidate++);
    else if (++toBeWidened == candidate)
      ++candidate;
  }
  ranges.erase(candidate, ranges.end());
  return ranges;
}

std::vector<SerializableSourceRange>
SwiftRangesEmitter::serializeRanges(std::vector<CharSourceRange> ranges) const {
  std::vector<SerializableSourceRange> result;
  for (const auto r : ranges)
    result.push_back(SerializableSourceRange(r, sourceMgr));
  return result;
}

bool SwiftRangesEmitter::isImmediatelyBeforeOrOverlapping(
    CharSourceRange prev, CharSourceRange next) const {
  // TODO: investigate returning true if only white space intervenes.
  // Would be more work here, but less work downstream.
  return !sourceMgr.isBeforeInBuffer(prev.getEnd(), next.getStart());
}

//==============================================================================
// MARK: CompiledSource
//==============================================================================

bool CompiledSourceEmitter::emit() {
  auto const bufID = primaryFile->getBufferID();
  if (!bufID.hasValue()) {
    diags.diagnose(SourceLoc(),
                   diag::error_unable_to_write_compiled_source_file, outputPath,
                   "No buffer");
    return true;
  }
  const bool hadError =
      withOutputFile(diags, outputPath, [&](llvm::raw_pwrite_stream &out) {
        out << sourceMgr.getEntireTextForBuffer(bufID.getValue());
        return false;
      });
  if (!hadError)
    return false;
  diags.diagnose(SourceLoc(), diag::error_unable_to_write_compiled_source_file,
                 outputPath, "Output error");
  return true;
}

//==============================================================================
// MARK: SwiftRangesFileContents
//==============================================================================

void SwiftRangesFileContents::dump(const StringRef primary) const {
  llvm::errs() << "\n*** Swift range file contents for '" << primary
               << "': ***\n";
  llvm::yaml::Output dumper(llvm::errs());
  dumper << *const_cast<SwiftRangesFileContents *>(this);
}
<commit_msg>Range fixes<commit_after>//===------------- IncrementalRanges.cpp - Generates swiftdeps files
//---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

// These are the definitions for managing serializable source locations so that
// the frontend and the driver can implement incremental compilation based on
// source ranges.

#include "swift/AST/IncrementalRanges.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsCommon.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/FileSystem.h"
#include "swift/AST/SourceFile.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/PersistentParserState.h"
#include "llvm/Support/YAMLParser.h"

using namespace swift;
using namespace incremental_ranges;

//==============================================================================
// MARK: SerializableSourceLocation
//==============================================================================

SerializableSourceLocation::SerializableSourceLocation(
    const SourceLoc loc, const SourceManager &SM) {
  auto lc = SM.getLineAndColumn(loc);
  line = lc.first;
  column = lc.second;
}

const SerializableSourceLocation SerializableSourceLocation::endOfAnyFile = {
    ~decltype(line)(0), 0};

void SerializableSourceLocation::print(raw_ostream &out) const {
  out << line << ":" << column;
}
void SerializableSourceLocation::dump() const { print(llvm::errs()); }

//==============================================================================
// MARK: SerializableSourceRange
//==============================================================================

SerializableSourceRange::SerializableSourceRange(
    SerializableSourceLocation start, SerializableSourceLocation end)
    : start(start), end(end) {
#ifndef NDEBUG
  if (!(start <= end)) {
    llvm::errs() << "*** Error: creating backwards SerializableSourceRange: [";
    start.print(llvm::errs());
    llvm::errs() << " -- ";
    end.print(llvm::errs());
    llvm::errs() << ")\n";
    assert(false && "Detected backwards SerializableSourceRange");
  }
#endif
}

SerializableSourceRange::SerializableSourceRange(const CharSourceRange r,
                                                 const SourceManager &SM)
    : start(SerializableSourceLocation(r.getStart(), SM)),
      end(SerializableSourceLocation(r.getEnd(), SM)) {}

const SerializableSourceRange SerializableSourceRange::wholeFile = {
    {0, 0}, SerializableSourceLocation::endOfAnyFile};

Ranges SerializableSourceRange::RangesForWholeFile() {
  assert(wholeFile.end.line && "Ensure initialization happens");
  return {wholeFile};
}

bool SerializableSourceRange::properlyPreceeds(
    const SerializableSourceRange &other) const {
  return end <= other.start;
}

bool SerializableSourceRange::isProperlySorted(
    ArrayRef<SerializableSourceRange> ranges) {
  Optional<SerializableSourceRange> lastRange;
  for (const auto &thisRange : ranges) {
    if (!lastRange)
      lastRange = thisRange;
    else if (!lastRange->properlyPreceeds(thisRange))
      return false;
  }
  return true;
}

bool SerializableSourceRange::isImproperSubsetOf(
    const SerializableSourceRange &superset) const {
  return superset.start <= start && end <= superset.end;
}

Optional<SerializableSourceRange> SerializableSourceRange::findOutlierIfAny(
    ArrayRef<SerializableSourceRange> subset,
    ArrayRef<SerializableSourceRange> superset) {
  // TODO: could optimize this by exploiting sortedness of the arrays:
  // i.e. could skip searching the start of the superset
  for (const auto &subsetRange : subset) {
    const bool isSubsetRangeContained = subsetRange.isImproperSubsetOfAny(superset);
    if (!isSubsetRangeContained)
      return subsetRange;
  }
  return None;
}

Ranges SerializableSourceRange::findAllOutliers(
    ArrayRef<SerializableSourceRange> subset,
    ArrayRef<SerializableSourceRange> superset) {
  // TODO:  optimize with slice of superset
  Ranges outliers;
  std::copy_if(subset.begin(), subset.end(), std::back_inserter(outliers),
               [&](const SerializableSourceRange &r) {
                 return !r.isImproperSubsetOfAny(superset);
               });
  return outliers;
}

bool SerializableSourceRange::isImproperSubsetOfAny(
    ArrayRef<SerializableSourceRange> supersetRanges) const {
  assert(isProperlySorted(supersetRanges) && "required for binary search");
  const auto firstRangeInSupersetNotBeforeSub =
      std::lower_bound(supersetRanges.begin(), supersetRanges.end(), *this,
                       [](const SerializableSourceRange &superRange,
                          const SerializableSourceRange &subsetRange) {
                         return superRange.properlyPreceeds(subsetRange);
                       });
  const bool result =
      firstRangeInSupersetNotBeforeSub != supersetRanges.end() &&
      isImproperSubsetOf(*firstRangeInSupersetNotBeforeSub);

  // slow if input is too big
  assert((supersetRanges.size() >= 5 ||
          result == isImproperSubsetOfAnySlowlyAndSimply(supersetRanges)) &&
         "Check against reference");

  return result;
}

bool SerializableSourceRange::isImproperSubsetOfAnySlowlyAndSimply(
    ArrayRef<SerializableSourceRange> supersetRanges) const {
  return llvm::any_of(supersetRanges,
                      [&](const SerializableSourceRange &superset) {
                        return isImproperSubsetOf(superset);
                      });
}

std::string SerializableSourceRange::printString() const {
  std::string result;
  llvm::raw_string_ostream out(result);
  print(out);
  return out.str();
}

void SerializableSourceRange::print(raw_ostream &out) const {
  out << "[";
  start.print(out);
  out << "--";
  end.print(out);
  out << ")";
}
void SerializableSourceRange::dump() const { print(llvm::errs()); }

//==============================================================================
// MARK: SwiftRangesEmitter
//==============================================================================

bool SwiftRangesEmitter::emit() const {
  const bool hadError =
      withOutputFile(diags, outputPath, [&](llvm::raw_pwrite_stream &out) {
        out << SwiftRangesFileContents::header;
        emitRanges(out);
        return false;
      });
  if (!hadError)
    return false;
  diags.diagnose(SourceLoc(), diag::error_unable_to_write_swift_ranges_file,
                 outputPath, "Output error");
  return true;
}

void SwiftRangesEmitter::emitRanges(llvm::raw_ostream &out) const {
  SwiftRangesFileContents wholeFileContents(
      collectSerializedUnparsedRangesByNonPrimary(),
      collectSortedSerializedNoninlinableFunctionBodies());
  llvm::yaml::Output yamlWriter(out);
  yamlWriter << wholeFileContents;
}

RangesByFilename
SwiftRangesEmitter::collectSerializedUnparsedRangesByNonPrimary() const {
  auto rangesByNonprimary = collectUnparsedRanges();
  std::map<std::string, std::vector<SerializableSourceRange>>
      serializedRangesByNonprimary;
  // The driver counts on getting coalescedSortedRanges because it
  // does binary chop searches
  for (auto &nonPriAndRanges : rangesByNonprimary)
    serializedRangesByNonprimary.insert(
        {nonPriAndRanges.first, serializeRanges(coalesceSortedRanges(sortRanges(
                                    std::move(nonPriAndRanges.second))))});
  return serializedRangesByNonprimary;
}

Ranges
SwiftRangesEmitter::collectSortedSerializedNoninlinableFunctionBodies() const {
  return serializeRanges(
      coalesceSortedRanges(sortRanges(collectNoninlinableFunctionBodies())));
}

std::vector<CharSourceRange>
SwiftRangesEmitter::collectNoninlinableFunctionBodies() const {
  struct FnBodyCollector : ASTWalker {
    const SourceManager &SM;
    FnBodyCollector(const SourceManager &SM) : SM(SM) {}

    std::vector<CharSourceRange> ranges;
    bool walkToDeclPre(Decl *D) override {
      if (const auto *AFD = dyn_cast<AbstractFunctionDecl>(D)) {
        // If you change an accessor body you might change the inferred
        // type, and the change might propagate, so exclude them from local
        // change ranges.
        // Also rule out implicit constructors a fortiori.
        if (!isa<AccessorDecl>(AFD) && !AFD->isImplicit() &&
            !AFD->getAttrs().hasAttribute<InlinableAttr>()) {
          auto sr = AFD->getBodySourceRange();
          if (sr.isValid())
            ranges.push_back(Lexer::getCharSourceRangeFromSourceRange(SM, sr));
        }
        return false;
      }
      return true;
    }
  };
  FnBodyCollector collector(sourceMgr);
  primaryFile->walk(collector);
  return collector.ranges;
}

std::map<std::string, std::vector<CharSourceRange>>
SwiftRangesEmitter::collectUnparsedRanges() const {
  std::map<std::string, std::vector<CharSourceRange>> rangesByNonprimaryFile;
  persistentState.forEachDelayedSourceRange(
      primaryFile, [&](const SourceRange sr) {
        const auto filename = sourceMgr.getIdentifierForBuffer(
            sourceMgr.findBufferContainingLoc(sr.Start));
        const auto csr =
            Lexer::getCharSourceRangeFromSourceRange(sourceMgr, sr);
        rangesByNonprimaryFile[filename].push_back(csr);
      });
  return rangesByNonprimaryFile;
}

std::vector<CharSourceRange>
SwiftRangesEmitter::sortRanges(std::vector<CharSourceRange> ranges) const {
  std::sort(ranges.begin(), ranges.end(),
            [&](const CharSourceRange &lhs, const CharSourceRange &rhs) {
              return sourceMgr.isBeforeInBuffer(lhs.getStart(), rhs.getStart());
            });
  return ranges;
}

std::vector<CharSourceRange> SwiftRangesEmitter::coalesceSortedRanges(
    std::vector<CharSourceRange> ranges) const {
  if (ranges.empty())
    return ranges;
  auto toBeWidened = ranges.begin();
  auto candidate = toBeWidened + 1;
  while (candidate < ranges.end()) {
    if (isImmediatelyBeforeOrOverlapping(*toBeWidened, *candidate))
      toBeWidened->widen(*candidate++);
    else
      *++toBeWidened = *candidate++;
  }
  ranges.erase(toBeWidened + 1, ranges.end());
  return ranges;
}

std::vector<SerializableSourceRange>
SwiftRangesEmitter::serializeRanges(std::vector<CharSourceRange> ranges) const {
  std::vector<SerializableSourceRange> result;
  for (const auto r : ranges)
    result.push_back(SerializableSourceRange(r, sourceMgr));
  return result;
}

bool SwiftRangesEmitter::isImmediatelyBeforeOrOverlapping(
    CharSourceRange prev, CharSourceRange next) const {
  // TODO: investigate returning true if only white space intervenes.
  // Would be more work here, but less work downstream.
  return !sourceMgr.isBeforeInBuffer(prev.getEnd(), next.getStart());
}

//==============================================================================
// MARK: CompiledSource
//==============================================================================

bool CompiledSourceEmitter::emit() {
  auto const bufID = primaryFile->getBufferID();
  if (!bufID.hasValue()) {
    diags.diagnose(SourceLoc(),
                   diag::error_unable_to_write_compiled_source_file, outputPath,
                   "No buffer");
    return true;
  }
  const bool hadError =
      withOutputFile(diags, outputPath, [&](llvm::raw_pwrite_stream &out) {
        out << sourceMgr.getEntireTextForBuffer(bufID.getValue());
        return false;
      });
  if (!hadError)
    return false;
  diags.diagnose(SourceLoc(), diag::error_unable_to_write_compiled_source_file,
                 outputPath, "Output error");
  return true;
}

//==============================================================================
// MARK: SwiftRangesFileContents
//==============================================================================

void SwiftRangesFileContents::dump(const StringRef primary) const {
  llvm::errs() << "\n*** Swift range file contents for '" << primary
               << "': ***\n";
  llvm::yaml::Output dumper(llvm::errs());
  dumper << *const_cast<SwiftRangesFileContents *>(this);
}
<|endoftext|>


<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2018 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#pragma once

#include "caf/detail/type_list.hpp"
#include "caf/detail/type_traits.hpp"
#include "caf/sum_type_access.hpp"

namespace caf {

/// Concept for checking whether `T` supports the sum type API by specializing
/// `sum_type_access`.
template <class T>
constexpr bool SumType() {
  return has_sum_type_access<typename std::decay<T>::type>::value;
}

/// Concept for checking whether all `Ts` support the sum type API by
/// specializing `sum_type_access`.
template <class... Ts>
constexpr bool SumTypes() {
  using namespace detail;
  using types = type_list<decay_t<Ts>...>;
  return tl_forall<types, has_sum_type_access>::value;
}

/// Returns a reference to the value of a sum type.
/// @pre `holds_alternative<T>(x)`
/// @relates SumType
template <class T, class U>
detail::enable_if_t<SumType<U>(), T&> get(U& x) {
  using namespace detail;
  using trait = sum_type_access<U>;
  int_token<tl_index_where<typename trait::types,
                           tbind<is_same_ish, T>::template type>::value> token;
  // Silence compiler error about "binding to unrelated types" such as
  // 'signed char' to 'char' (which is obvious bullshit).
  return reinterpret_cast<T&>(trait::get(x, token));
}

/// Returns a reference to the value of a sum type.
/// @pre `holds_alternative<T>(x)`
/// @relates SumType
template <class T, class U>
detail::enable_if_t<SumType<U>(), const T&> get(const U& x) {
  using namespace detail;
  using trait = sum_type_access<U>;
  int_token<tl_index_where<typename trait::types,
                           tbind<is_same_ish, T>::template type>::value> token;
  // Silence compiler error about "binding to unrelated types" such as
  // 'signed char' to 'char' (which is obvious bullshit).
  return reinterpret_cast<const T&>(trait::get(x, token));
}

/// Returns a pointer to the value of a sum type if it is of type `T`,
/// `nullptr` otherwise.
/// @relates SumType
template <class T, class U>
detail::enable_if_t<SumType<U>(), T*> get_if(U* x) {
  using namespace detail;
  using trait = sum_type_access<U>;
  int_token<tl_index_where<typename trait::types,
                           tbind<is_same_ish, T>::template type>::value> token;
  return trait::is(*x, token) ? &trait::get(*x, token) : nullptr;
}

/// Returns a pointer to the value of a sum type if it is of type `T`,
/// `nullptr` otherwise.
/// @relates SumType
template <class T, class U>
detail::enable_if_t<SumType<U>(), const T*> get_if(const U* x) {
  using namespace detail;
  using trait = sum_type_access<U>;
  using token_type =
    int_token<tl_index_where<typename trait::types,
                             tbind<is_same_ish, T>::template type>::value>;
  token_type token;
  static_assert(token_type::value != -1, "T is not part of the sum type");
  return trait::is(*x, token) ? &trait::get(*x, token) : nullptr;
}

/// Returns whether a sum type has a value of type `T`.
/// @relates SumType
template <class T, class U>
bool holds_alternative(const U& x) {
  using namespace detail;
  using trait = sum_type_access<U>;
  int_token<tl_index_where<typename trait::types,
                           tbind<is_same_ish, T>::template type>::value> token;
  return trait::is(x, token);
}

template <bool Valid, class F, class... Ts>
struct sum_type_visit_result_impl {
  using type = decltype((std::declval<F&>())(
    std::declval<typename sum_type_access<Ts>::type0&>()...));
};

template <class F, class... Ts>
struct sum_type_visit_result_impl<false, F, Ts...> {};

template <class F, class... Ts>
struct sum_type_visit_result
    : sum_type_visit_result_impl<
        detail::conjunction<SumType<Ts>()...>::value, F, Ts...> {};

template <class F, class... Ts>
using sum_type_visit_result_t =
  typename sum_type_visit_result<detail::decay_t<F>,
                                 detail::decay_t<Ts>...>::type;

template <class Result, int I, class Visitor>
struct visit_impl_continuation;

template <class Result, int I>
struct visit_impl {
  template <class Visitor, class T, class... Ts>
  static Result apply(Visitor&& f, T&& x, Ts&&... xs) {
    visit_impl_continuation<Result, I - 1, Visitor> continuation{f};
    using trait = sum_type_access<detail::decay_t<T>>;
    return trait::template apply<Result>(x, continuation,
                                         std::forward<Ts>(xs)...);
  }
};

template <class Result>
struct visit_impl<Result, 0> {
  template <class Visitor, class... Ts>
  static Result apply(Visitor&& f, Ts&&... xs) {
    return f(std::forward<Ts>(xs)...);
  }
};

template <class Result, int I, class Visitor>
struct visit_impl_continuation {
  Visitor& f;
  template <class... Ts>
  Result operator()(Ts&&... xs) {
    return visit_impl<Result, I>::apply(f, std::forward<Ts>(xs)...);
  }
};

/// Applies the values of any number of sum types to the visitor.
/// @relates SumType
template <class Visitor, class T, class... Ts,
          class Result = sum_type_visit_result_t<Visitor, T, Ts...>>
detail::enable_if_t<SumTypes<T, Ts...>(), Result>
visit(Visitor&& f, T&& x, Ts&&... xs) {
  return visit_impl<Result, sizeof...(Ts) + 1>::apply(std::forward<Visitor>(f),
                                                      std::forward<T>(x),
                                                      std::forward<Ts>(xs)...);
}

} // namespace caf
<commit_msg>Remove redundant newline<commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2018 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#pragma once

#include "caf/detail/type_list.hpp"
#include "caf/detail/type_traits.hpp"
#include "caf/sum_type_access.hpp"

namespace caf {

/// Concept for checking whether `T` supports the sum type API by specializing
/// `sum_type_access`.
template <class T>
constexpr bool SumType() {
  return has_sum_type_access<typename std::decay<T>::type>::value;
}

/// Concept for checking whether all `Ts` support the sum type API by
/// specializing `sum_type_access`.
template <class... Ts>
constexpr bool SumTypes() {
  using namespace detail;
  using types = type_list<decay_t<Ts>...>;
  return tl_forall<types, has_sum_type_access>::value;
}

/// Returns a reference to the value of a sum type.
/// @pre `holds_alternative<T>(x)`
/// @relates SumType
template <class T, class U>
detail::enable_if_t<SumType<U>(), T&> get(U& x) {
  using namespace detail;
  using trait = sum_type_access<U>;
  int_token<tl_index_where<typename trait::types,
                           tbind<is_same_ish, T>::template type>::value> token;
  // Silence compiler error about "binding to unrelated types" such as
  // 'signed char' to 'char' (which is obvious bullshit).
  return reinterpret_cast<T&>(trait::get(x, token));
}

/// Returns a reference to the value of a sum type.
/// @pre `holds_alternative<T>(x)`
/// @relates SumType
template <class T, class U>
detail::enable_if_t<SumType<U>(), const T&> get(const U& x) {
  using namespace detail;
  using trait = sum_type_access<U>;
  int_token<tl_index_where<typename trait::types,
                           tbind<is_same_ish, T>::template type>::value> token;
  // Silence compiler error about "binding to unrelated types" such as
  // 'signed char' to 'char' (which is obvious bullshit).
  return reinterpret_cast<const T&>(trait::get(x, token));
}

/// Returns a pointer to the value of a sum type if it is of type `T`,
/// `nullptr` otherwise.
/// @relates SumType
template <class T, class U>
detail::enable_if_t<SumType<U>(), T*> get_if(U* x) {
  using namespace detail;
  using trait = sum_type_access<U>;
  int_token<tl_index_where<typename trait::types,
                           tbind<is_same_ish, T>::template type>::value> token;
  return trait::is(*x, token) ? &trait::get(*x, token) : nullptr;
}

/// Returns a pointer to the value of a sum type if it is of type `T`,
/// `nullptr` otherwise.
/// @relates SumType
template <class T, class U>
detail::enable_if_t<SumType<U>(), const T*> get_if(const U* x) {
  using namespace detail;
  using trait = sum_type_access<U>;
  using token_type =
    int_token<tl_index_where<typename trait::types,
                             tbind<is_same_ish, T>::template type>::value>;
  token_type token;
  static_assert(token_type::value != -1, "T is not part of the sum type");
  return trait::is(*x, token) ? &trait::get(*x, token) : nullptr;
}

/// Returns whether a sum type has a value of type `T`.
/// @relates SumType
template <class T, class U>
bool holds_alternative(const U& x) {
  using namespace detail;
  using trait = sum_type_access<U>;
  int_token<tl_index_where<typename trait::types,
                           tbind<is_same_ish, T>::template type>::value> token;
  return trait::is(x, token);
}

template <bool Valid, class F, class... Ts>
struct sum_type_visit_result_impl {
  using type = decltype((std::declval<F&>())(
    std::declval<typename sum_type_access<Ts>::type0&>()...));
};

template <class F, class... Ts>
struct sum_type_visit_result_impl<false, F, Ts...> {};

template <class F, class... Ts>
struct sum_type_visit_result
    : sum_type_visit_result_impl<
        detail::conjunction<SumType<Ts>()...>::value, F, Ts...> {};

template <class F, class... Ts>
using sum_type_visit_result_t =
  typename sum_type_visit_result<detail::decay_t<F>,
                                 detail::decay_t<Ts>...>::type;

template <class Result, int I, class Visitor>
struct visit_impl_continuation;

template <class Result, int I>
struct visit_impl {
  template <class Visitor, class T, class... Ts>
  static Result apply(Visitor&& f, T&& x, Ts&&... xs) {
    visit_impl_continuation<Result, I - 1, Visitor> continuation{f};
    using trait = sum_type_access<detail::decay_t<T>>;
    return trait::template apply<Result>(x, continuation,
                                         std::forward<Ts>(xs)...);
  }
};

template <class Result>
struct visit_impl<Result, 0> {
  template <class Visitor, class... Ts>
  static Result apply(Visitor&& f, Ts&&... xs) {
    return f(std::forward<Ts>(xs)...);
  }
};

template <class Result, int I, class Visitor>
struct visit_impl_continuation {
  Visitor& f;
  template <class... Ts>
  Result operator()(Ts&&... xs) {
    return visit_impl<Result, I>::apply(f, std::forward<Ts>(xs)...);
  }
};

/// Applies the values of any number of sum types to the visitor.
/// @relates SumType
template <class Visitor, class T, class... Ts,
          class Result = sum_type_visit_result_t<Visitor, T, Ts...>>
detail::enable_if_t<SumTypes<T, Ts...>(), Result>
visit(Visitor&& f, T&& x, Ts&&... xs) {
  return visit_impl<Result, sizeof...(Ts) + 1>::apply(std::forward<Visitor>(f),
                                                      std::forward<T>(x),
                                                      std::forward<Ts>(xs)...);
}

} // namespace caf
<|endoftext|>


<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2014                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#ifndef CAF_IO_PUBLISH_HPP
#define CAF_IO_PUBLISH_HPP

#include <cstdint>

#include "caf/actor.hpp"
#include "caf/actor_cast.hpp"
#include "caf/typed_actor.hpp"

namespace caf {
namespace io {

void publish_impl(abstract_actor_ptr whom, uint16_t port, const char* in);

/**
 * Publishes `whom` at `port`. The connection is managed by the middleman.
 * @param whom Actor that should be published at `port`.
 * @param port Unused TCP port.
 * @param addr The IP address to listen to or `INADDR_ANY` if `in == nullptr`.
 * @throws bind_failure
 */
inline void publish(caf::actor whom, uint16_t port, const char* in = nullptr) {
  if (!whom) {
    return;
  }
  publish_impl(actor_cast<abstract_actor_ptr>(whom), port, in);
}

/**
 * @copydoc publish(actor,uint16_t,const char*)
 */
template <class... Rs>
void typed_publish(typed_actor<Rs...> whom, uint16_t port,
                   const char* in = nullptr) {
  if (!whom) {
    return;
  }
  publish_impl(actor_cast<abstract_actor_ptr>(whom), port, in);
}

} // namespace io
} // namespace caf

#endif // CAF_IO_PUBLISH_HPP
<commit_msg>Fix parameter name in Doxygen comment<commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2014                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#ifndef CAF_IO_PUBLISH_HPP
#define CAF_IO_PUBLISH_HPP

#include <cstdint>

#include "caf/actor.hpp"
#include "caf/actor_cast.hpp"
#include "caf/typed_actor.hpp"

namespace caf {
namespace io {

void publish_impl(abstract_actor_ptr whom, uint16_t port, const char* in);

/**
 * Publishes `whom` at `port`. The connection is managed by the middleman.
 * @param whom Actor that should be published at `port`.
 * @param port Unused TCP port.
 * @param in The IP address to listen to or `INADDR_ANY` if `in == nullptr`.
 * @throws bind_failure
 */
inline void publish(caf::actor whom, uint16_t port, const char* in = nullptr) {
  if (!whom) {
    return;
  }
  publish_impl(actor_cast<abstract_actor_ptr>(whom), port, in);
}

/**
 * @copydoc publish(actor,uint16_t,const char*)
 */
template <class... Rs>
void typed_publish(typed_actor<Rs...> whom, uint16_t port,
                   const char* in = nullptr) {
  if (!whom) {
    return;
  }
  publish_impl(actor_cast<abstract_actor_ptr>(whom), port, in);
}

} // namespace io
} // namespace caf

#endif // CAF_IO_PUBLISH_HPP
<|endoftext|>


<commit_before>#include "topic.h"
#include "consumer.h"

using namespace std;

Consumer::Consumer(const std::string& root, const std::string& topic, const std::string& name, TopicOpt* opt) : _topic(EnvManager::getEnv(root)->getTopic(topic)), _name(name), _current(0), _lastOffset(0), _env(nullptr), _db(0), _rtxn(nullptr), _cursor(nullptr) {
    if (opt) {
        _opt = *opt;
    } else {
        /* Default opt */
        _opt.chunkSize = 1024 * 1024 * 1024;
        _opt.chunksToKeep = 8;
    }

    Txn txn(_topic->getEnv(), NULL);
    openHead(&txn);
    txn.commit();
}

Consumer::~Consumer() {
    closeCurrent();
}

void Consumer::pull(BatchType& result, size_t cnt) {
    result.reserve(cnt);
    bool shouldRotate = false;

    {
        Txn txn(_topic->getEnv(), NULL);
        mdb_txn_renew(_rtxn);

        uint64_t head = _topic->getConsumerHead(txn, _name);
        int rc = _cursor->seek(head);

        if (rc == 0) {
            uint64_t offset = 0;
            for (; rc == 0 && cnt > 0; --cnt) {
                offset = _cursor->key<uint64_t>();
                const char* data = (const char*)_cursor->val().mv_data;
                size_t len = _cursor->val().mv_size;
                result.push_back(ItemType(offset, data, len));
                rc = _cursor->next();
            }

            if (offset > 0) {
                _topic->setConsumerHead(txn, _name, offset + 1);
                txn.commit();
            }
        } else {
            if (rc != MDB_NOTFOUND) cout << "Consumer seek error: " << mdb_strerror(rc) << endl;

            if (head < _topic->getProducerHead(txn)) {
                shouldRotate = true;
            }
        }
    }

    if (shouldRotate) {
        rotate();
        pull(result, cnt);
    }
}

void Consumer::openHead(Txn* txn) {
    _current = _topic->getConsumerHeadFile(*txn, _name, _current);

    char path[4096];
    _topic->getChunkFilePath(path, _current);

    mdb_env_create(&_env);
    mdb_env_set_mapsize(_env, _opt.chunkSize);
    int rc = mdb_env_open(_env, path, MDB_RDONLY | MDB_NOSYNC | MDB_NOSUBDIR, 0664);

    int cleared = 0;
    mdb_reader_check(_env, &cleared);

    if (rc != 0) {
        mdb_env_close(_env);
        _env = nullptr;
        printf("Producer open error.\n%s\n", mdb_strerror(rc));
        return;
    }

    MDB_txn *otxn;
    mdb_txn_begin(_env, NULL, MDB_RDONLY, &otxn);
    mdb_dbi_open(otxn, NULL, MDB_CREATE, &_db);
    mdb_set_compare(otxn, _db, mdbIntCmp<uint64_t>);
    mdb_txn_commit(otxn);

    mdb_txn_begin(_env, NULL, MDB_RDONLY, &_rtxn);
    _cursor = new MDBCursor(_db, _rtxn);
    mdb_txn_reset(_rtxn);
}

void Consumer::closeCurrent() {
    delete _cursor;
    mdb_txn_abort(_rtxn);
    mdb_dbi_close(_env, _db);
    mdb_env_close(_env);
}

void Consumer::rotate() {
    Txn txn(_topic->getEnv(), NULL);
    closeCurrent();
    openHead(&txn);
    txn.commit();
}<commit_msg>fix msg error.<commit_after>#include "topic.h"
#include "consumer.h"

using namespace std;

Consumer::Consumer(const std::string& root, const std::string& topic, const std::string& name, TopicOpt* opt) : _topic(EnvManager::getEnv(root)->getTopic(topic)), _name(name), _current(0), _lastOffset(0), _env(nullptr), _db(0), _rtxn(nullptr), _cursor(nullptr) {
    if (opt) {
        _opt = *opt;
    } else {
        /* Default opt */
        _opt.chunkSize = 1024 * 1024 * 1024;
        _opt.chunksToKeep = 8;
    }

    Txn txn(_topic->getEnv(), NULL);
    openHead(&txn);
    txn.commit();
}

Consumer::~Consumer() {
    closeCurrent();
}

void Consumer::pull(BatchType& result, size_t cnt) {
    result.reserve(cnt);
    bool shouldRotate = false;

    {
        Txn txn(_topic->getEnv(), NULL);
        mdb_txn_renew(_rtxn);

        uint64_t head = _topic->getConsumerHead(txn, _name);
        int rc = _cursor->seek(head);

        if (rc == 0) {
            uint64_t offset = 0;
            for (; rc == 0 && cnt > 0; --cnt) {
                offset = _cursor->key<uint64_t>();
                const char* data = (const char*)_cursor->val().mv_data;
                size_t len = _cursor->val().mv_size;
                result.push_back(ItemType(offset, data, len));
                rc = _cursor->next();
            }

            if (offset > 0) {
                _topic->setConsumerHead(txn, _name, offset + 1);
                txn.commit();
            }
        } else {
            if (rc != MDB_NOTFOUND) cout << "Consumer seek error: " << mdb_strerror(rc) << endl;

            if (head < _topic->getProducerHead(txn)) {
                shouldRotate = true;
            }
        }
    }

    if (shouldRotate) {
        rotate();
        pull(result, cnt);
    }
}

void Consumer::openHead(Txn* txn) {
    _current = _topic->getConsumerHeadFile(*txn, _name, _current);

    char path[4096];
    _topic->getChunkFilePath(path, _current);

    mdb_env_create(&_env);
    mdb_env_set_mapsize(_env, _opt.chunkSize);
    int rc = mdb_env_open(_env, path, MDB_RDONLY | MDB_NOSYNC | MDB_NOSUBDIR, 0664);

    int cleared = 0;
    mdb_reader_check(_env, &cleared);

    if (rc != 0) {
        mdb_env_close(_env);
        _env = nullptr;
        printf("Consumer open error.\n%s\n", mdb_strerror(rc));
        return;
    }

    MDB_txn *otxn;
    mdb_txn_begin(_env, NULL, MDB_RDONLY, &otxn);
    mdb_dbi_open(otxn, NULL, MDB_CREATE, &_db);
    mdb_set_compare(otxn, _db, mdbIntCmp<uint64_t>);
    mdb_txn_commit(otxn);

    mdb_txn_begin(_env, NULL, MDB_RDONLY, &_rtxn);
    _cursor = new MDBCursor(_db, _rtxn);
    mdb_txn_reset(_rtxn);
}

void Consumer::closeCurrent() {
    delete _cursor;
    mdb_txn_abort(_rtxn);
    mdb_dbi_close(_env, _db);
    mdb_env_close(_env);
}

void Consumer::rotate() {
    Txn txn(_topic->getEnv(), NULL);
    closeCurrent();
    openHead(&txn);
    txn.commit();
}<|endoftext|>


<commit_before>/*******************************************************************************
*     ALMA - Atacama Large Millimiter Array
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration)
*    and Cosylab 2002, All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: acsdaemonImpl.cpp,v 1.2 2006/06/23 12:23:05 msekoran Exp $"
*
* who       when        what
* --------  ---------   ----------------------------------------------
* msekoran  2006-06-21  created
*/

#include "acsdaemonImpl.h"
#include <tao/IORTable/IORTable.h>
#include <acserr.h>
#include <acsdaemonErrType.h>
#include <ACSErrTypeCommon.h>

/*****************************************************************/

ACSDaemonImpl::ACSDaemonImpl (LoggingProxy &logProxy) :
    m_isInitialized(false),
    m_logProxy(logProxy)
{
    // noop here

    m_isInitialized = true;
}

ACSDaemonImpl::~ACSDaemonImpl (void)
{
}

int
ACSDaemonImpl::init_ORB  (int& argc, char *argv [])
{
    m_orb = CORBA::ORB_init(argc, argv, "TAO");

    try
	{
	// get a reference to the RootPOA
	CORBA::Object_var obj = m_orb->resolve_initial_references("RootPOA");
	PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());
	PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();

	// create policies
	CORBA::PolicyList policy_list;
	policy_list.length(5);
	policy_list[0] = root_poa->create_request_processing_policy(PortableServer::USE_DEFAULT_SERVANT);
	policy_list[1] =  root_poa->create_id_uniqueness_policy(PortableServer::MULTIPLE_ID);
	policy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID);
	policy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN);
	policy_list[4] =  root_poa->create_lifespan_policy(PortableServer::PERSISTENT);

	// create a ACSDaemon POA with policies
	PortableServer::POA_var poa = root_poa->create_POA("ACSDaemon", poa_manager.in(), policy_list);

	// destroy policies
	for (CORBA::ULong i = 0; i < policy_list.length(); ++i)
	    {
	    CORBA::Policy_ptr policy = policy_list[i];
	    policy->destroy();
	    }

	// set as default servant
	poa->set_servant(this);

	// create reference
	PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId("ACSDeamon");
	obj = poa->create_reference_with_id (oid.in(), _interface_repository_id());
	m_ior = m_orb->object_to_string(obj.in());

	// bind to IOR table
      	CORBA::Object_var table_object = m_orb->resolve_initial_references("IORTable");
	IORTable::Table_var adapter = IORTable::Table::_narrow(table_object.in());

	if (CORBA::is_nil(adapter.in()))
	    {
	    ACS_SHORT_LOG ((LM_ERROR, "Nil IORTable"));
	    return -1;
	    }
	else
	    {
	    adapter->bind("ACSDaemon", m_ior.in());
	    }

	// activate POA
	poa_manager->activate();

	ACS_SHORT_LOG((LM_INFO, "ACS Daemon is waiting for incoming requests."));

	}
    catch( CORBA::Exception &ex )
	{
	ACE_PRINT_EXCEPTION (ex, "EXCEPTION CAUGHT");
	return -1;
	}

    return 0;
}

int
ACSDaemonImpl::startup (int argc, char *argv[])
{
    ACS_SHORT_LOG ((LM_INFO, "Starting up the ACS Daemon..."));

    // Initalize the ORB.
    if (init_ORB (argc, argv) != 0)
	{
	return -1;
	}

    // Initialize AES.
    if (!ACSError::init(m_orb.in()))
	{
	ACS_SHORT_LOG ((LM_ERROR, "Failed to initalize the ACS Error System."));
	return -1;
	}

    ACS_SHORT_LOG ((LM_INFO, "ACS Daemon is initialized."));

    return 0;
}

int
ACSDaemonImpl::run (void)
{
    ACS_SHORT_LOG ((LM_INFO, "ACS Daemon is up and running..."));

    try
	{
	this->m_orb->run ();
	}
    catch(...)
	{
	return -1;
	}

    return 0;
}

void
ACSDaemonImpl::shutdown ()
{

    // shutdown the ORB.
    if (!CORBA::is_nil (m_orb.in ()))
	{
	this->m_orb->shutdown (true);

	}

    // shutdown AES
    ACSError::done();
}

/************************** CORBA interface ****************************/

void
ACSDaemonImpl::start_container (
    const char * container_type,
    const char * container_name,
    ::CORBA::Short instance_number,
    const char * additional_command_line
    )
    ACE_THROW_SPEC ((
			CORBA::SystemException,
			::acsdaemonErrType::FailedToStartContainerEx,
			::ACSErrTypeCommon::BadParameterEx
			))
{
    if (container_type == 0 ||
	*container_type == 0)
	{
	::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
						  "::ACSDaemonImpl::start_container");
	ex.setParameter("container_type");
	throw ex.getBadParameterEx();
	}

    if (container_name == 0 ||
	*container_name == 0)
	{
	::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
						  "::ACSDaemonImpl::start_container");
	ex.setParameter("container_name");
	throw ex.getBadParameterEx();
	}

    const char * cmdln = (additional_command_line ? additional_command_line : "");

    // execute: "acsStartContainer -<type> -b <instance> <name> <args>"
    // TODO checks for ';', '&', '|' chars, they can run any other command!
    char command[200];
    snprintf(command, 200, "acsStartContainer -%s -b %d %s %s &", container_type, instance_number, container_name, cmdln);

    ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));

    int result = ACE_OS::system(command);

    if (result < 0)
	{
	throw ::acsdaemonErrType::FailedToStartContainerExImpl(
	    __FILE__, __LINE__,
	    "::ACSDaemonImpl::start_container").getFailedToStartContainerEx();
	}

}

<commit_msg>larger commandling length needed for IOR<commit_after>/*******************************************************************************
*     ALMA - Atacama Large Millimiter Array
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration)
*    and Cosylab 2002, All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: acsdaemonImpl.cpp,v 1.3 2006/10/27 09:19:20 msekoran Exp $"
*
* who       when        what
* --------  ---------   ----------------------------------------------
* msekoran  2006-06-21  created
*/

#include "acsdaemonImpl.h"
#include <tao/IORTable/IORTable.h>
#include <acserr.h>
#include <acsdaemonErrType.h>
#include <ACSErrTypeCommon.h>

/*****************************************************************/

ACSDaemonImpl::ACSDaemonImpl (LoggingProxy &logProxy) :
    m_isInitialized(false),
    m_logProxy(logProxy)
{
    // noop here

    m_isInitialized = true;
}

ACSDaemonImpl::~ACSDaemonImpl (void)
{
}

int
ACSDaemonImpl::init_ORB  (int& argc, char *argv [])
{
    m_orb = CORBA::ORB_init(argc, argv, "TAO");

    try
	{
	// get a reference to the RootPOA
	CORBA::Object_var obj = m_orb->resolve_initial_references("RootPOA");
	PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());
	PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();

	// create policies
	CORBA::PolicyList policy_list;
	policy_list.length(5);
	policy_list[0] = root_poa->create_request_processing_policy(PortableServer::USE_DEFAULT_SERVANT);
	policy_list[1] =  root_poa->create_id_uniqueness_policy(PortableServer::MULTIPLE_ID);
	policy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID);
	policy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN);
	policy_list[4] =  root_poa->create_lifespan_policy(PortableServer::PERSISTENT);

	// create a ACSDaemon POA with policies
	PortableServer::POA_var poa = root_poa->create_POA("ACSDaemon", poa_manager.in(), policy_list);

	// destroy policies
	for (CORBA::ULong i = 0; i < policy_list.length(); ++i)
	    {
	    CORBA::Policy_ptr policy = policy_list[i];
	    policy->destroy();
	    }

	// set as default servant
	poa->set_servant(this);

	// create reference
	PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId("ACSDeamon");
	obj = poa->create_reference_with_id (oid.in(), _interface_repository_id());
	m_ior = m_orb->object_to_string(obj.in());

	// bind to IOR table
      	CORBA::Object_var table_object = m_orb->resolve_initial_references("IORTable");
	IORTable::Table_var adapter = IORTable::Table::_narrow(table_object.in());

	if (CORBA::is_nil(adapter.in()))
	    {
	    ACS_SHORT_LOG ((LM_ERROR, "Nil IORTable"));
	    return -1;
	    }
	else
	    {
	    adapter->bind("ACSDaemon", m_ior.in());
	    }

	// activate POA
	poa_manager->activate();

	ACS_SHORT_LOG((LM_INFO, "ACS Daemon is waiting for incoming requests."));

	}
    catch( CORBA::Exception &ex )
	{
	ACE_PRINT_EXCEPTION (ex, "EXCEPTION CAUGHT");
	return -1;
	}

    return 0;
}

int
ACSDaemonImpl::startup (int argc, char *argv[])
{
    ACS_SHORT_LOG ((LM_INFO, "Starting up the ACS Daemon..."));

    // Initalize the ORB.
    if (init_ORB (argc, argv) != 0)
	{
	return -1;
	}

    // Initialize AES.
    if (!ACSError::init(m_orb.in()))
	{
	ACS_SHORT_LOG ((LM_ERROR, "Failed to initalize the ACS Error System."));
	return -1;
	}

    ACS_SHORT_LOG ((LM_INFO, "ACS Daemon is initialized."));

    return 0;
}

int
ACSDaemonImpl::run (void)
{
    ACS_SHORT_LOG ((LM_INFO, "ACS Daemon is up and running..."));

    try
	{
	this->m_orb->run ();
	}
    catch(...)
	{
	return -1;
	}

    return 0;
}

void
ACSDaemonImpl::shutdown ()
{

    // shutdown the ORB.
    if (!CORBA::is_nil (m_orb.in ()))
	{
	this->m_orb->shutdown (true);

	}

    // shutdown AES
    ACSError::done();
}

/************************** CORBA interface ****************************/

void
ACSDaemonImpl::start_container (
    const char * container_type,
    const char * container_name,
    ::CORBA::Short instance_number,
    const char * additional_command_line
    )
    ACE_THROW_SPEC ((
			CORBA::SystemException,
			::acsdaemonErrType::FailedToStartContainerEx,
			::ACSErrTypeCommon::BadParameterEx
			))
{
    if (container_type == 0 ||
	*container_type == 0)
	{
	::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
						  "::ACSDaemonImpl::start_container");
	ex.setParameter("container_type");
	throw ex.getBadParameterEx();
	}

    if (container_name == 0 ||
	*container_name == 0)
	{
	::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
						  "::ACSDaemonImpl::start_container");
	ex.setParameter("container_name");
	throw ex.getBadParameterEx();
	}

    const char * cmdln = (additional_command_line ? additional_command_line : "");

    // execute: "acsStartContainer -<type> -b <instance> <name> <args>"
    // TODO checks for ';', '&', '|' chars, they can run any other command!
    char command[1000];
    snprintf(command, 1000, "acsStartContainer -%s -b %d %s %s &", container_type, instance_number, container_name, cmdln);

    ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));

    int result = ACE_OS::system(command);

    if (result < 0)
	{
	throw ::acsdaemonErrType::FailedToStartContainerExImpl(
	    __FILE__, __LINE__,
	    "::ACSDaemonImpl::start_container").getFailedToStartContainerEx();
	}

}

<|endoftext|>


<commit_before>#include "stdafx.h"

DWORD WINAPI Init(LPVOID bDelay)
{
    auto pattern = hook::pattern("B9 ? ? ? ? E8 ? ? ? ? 8B 7C 24 10 6A 65 8B F0 57 89 74 24 28");

    if (pattern.count_hint(1).empty() && !bDelay)
    {
        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Init, (LPVOID)true, 0, NULL);
        return 0;
    }

    if (bDelay)
        while (pattern.clear().count_hint(1).empty()) { Sleep(0); };

    static auto dword_7242B0 = *pattern.get_first<uint32_t>(1);
    //injector::WriteMemory<float>(dword_7242B0 + 0x904, static_cast<float>(nWidth), true);
    //injector::WriteMemory<float>(dword_7242B0 + 0x908, static_cast<float>(nHeight), true);

    pattern = hook::pattern("D9 44 24 04 D9 99 04 09 00 00 D9 44"); // 0x608970
    struct SetAR
    {
        void operator()(injector::reg_pack& regs)
        {
            float temp = 0.0f;
            _asm fstp dword ptr[temp]
            _asm fstp dword ptr[temp]

            auto nWidth = *(uint32_t*)(dword_7242B0 + 0x8);
            auto nHeight = *(uint32_t*)(dword_7242B0 + 0xC);
            *(float*)(regs.ecx + 0x904) = static_cast<float>(nWidth);
            *(float*)(regs.ecx + 0x908) = static_cast<float>(nHeight);
        }
    }; injector::MakeInline<SetAR>(pattern.get_first(0), pattern.get_first(20));

    //pattern = hook::pattern(""); //
    //struct Hook
    //{
    //    void operator()(injector::reg_pack& regs)
    //    {
    //        float temp = 0.0f;
    //        _asm fstp    dword ptr[temp]
    //
    //        *(float*)(regs.edx + 0x54) = temp / 2.0f;
    //        regs.edx = *(uint32_t*)(regs.ecx + 0x2C);
    //    }
    //}; injector::MakeInline<Hook>(0x46FF14, 0x46FF14+6);
    return 0;
}

BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/)
{
    if (reason == DLL_PROCESS_ATTACH)
    {
        Init(NULL);
    }
    return TRUE;
}
<commit_msg>fouc update<commit_after>#include "stdafx.h"

DWORD WINAPI Init(LPVOID bDelay)
{
    auto pattern = hook::pattern("B9 ? ? ? ? E8 ? ? ? ? 8B 7C 24 10 6A 65 8B F0 57 89 74 24 28");

    if (pattern.count_hint(1).empty() && !bDelay)
    {
        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Init, (LPVOID)true, 0, NULL);
        return 0;
    }

    if (bDelay)
        while (pattern.clear().count_hint(1).empty()) { Sleep(0); };

    static auto dword_7242B0 = *pattern.get_first<uint32_t>(1);
    auto nWidth = *(uint32_t*)(dword_7242B0 + 0x8);
    auto nHeight = *(uint32_t*)(dword_7242B0 + 0xC);
    injector::WriteMemory<float>(dword_7242B0 + 0x904, static_cast<float>(nWidth), true);
    injector::WriteMemory<float>(dword_7242B0 + 0x908, static_cast<float>(nHeight), true);

    pattern = hook::pattern("D9 44 24 04 D9 99 04 09 00 00 D9 44"); // 0x608970
    struct SetAR
    {
        void operator()(injector::reg_pack& regs)
        {
            float temp = 0.0f;
            _asm fstp dword ptr[temp]
            _asm fstp dword ptr[temp]

            auto nWidth = *(uint32_t*)(dword_7242B0 + 0x8);
            auto nHeight = *(uint32_t*)(dword_7242B0 + 0xC);
            *(float*)(regs.ecx + 0x904) = static_cast<float>(nWidth);
            *(float*)(regs.ecx + 0x908) = static_cast<float>(nHeight);
        }
    }; injector::MakeInline<SetAR>(pattern.get_first(0), pattern.get_first(20));

    //pattern = hook::pattern(""); //
    //struct Hook
    //{
    //    void operator()(injector::reg_pack& regs)
    //    {
    //        float temp = 0.0f;
    //        _asm fstp    dword ptr[temp]
    //
    //        *(float*)(regs.edx + 0x54) = temp / 2.0f;
    //        regs.edx = *(uint32_t*)(regs.ecx + 0x2C);
    //    }
    //}; injector::MakeInline<Hook>(0x46FF14, 0x46FF14+6);
    return 0;
}

BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/)
{
    if (reason == DLL_PROCESS_ATTACH)
    {
        Init(NULL);
    }
    return TRUE;
}
<|endoftext|>