[interp] Decruft PowerPC. (#18981)
[mono-project.git] / mono / profiler / helper.c
blobd906561ae72810a0636754fb7d11f57e331adfce
1 /*
2 * helper.c: Helper code shared between various profilers
5 * Copyright 2019 Microsoft Corporation
6 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
7 */
9 #include <config.h>
11 #include <mono/utils/mono-logger-internals.h>
13 #ifdef HAVE_UNISTD_H
14 #include <unistd.h>
15 #endif
16 #include <errno.h>
17 #include <glib.h>
19 #ifndef HOST_WIN32
20 #include <netinet/in.h>
21 #endif
22 #ifndef HOST_WIN32
23 #include <sys/socket.h>
24 #endif
25 #ifdef HOST_WIN32
26 #include <winsock2.h>
27 #include <ws2tcpip.h>
28 #endif
30 #include "helper.h"
32 void
33 mono_profhelper_close_socket_fd (int fd)
35 #ifdef HOST_WIN32
36 closesocket (fd);
37 #else
38 close (fd);
39 #endif
42 void
43 mono_profhelper_setup_command_server (int *server_socket, int *command_port, const char* profiler_name)
45 *server_socket = socket (PF_INET, SOCK_STREAM, 0);
47 if (*server_socket == -1) {
48 mono_profiler_printf_err ("Could not create log profiler server socket: %s", g_strerror (errno));
49 exit (1);
52 struct sockaddr_in server_address;
54 memset (&server_address, 0, sizeof (server_address));
55 server_address.sin_family = AF_INET;
56 server_address.sin_addr.s_addr = INADDR_ANY;
57 server_address.sin_port = htons (*command_port);
59 if (bind (*server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) == -1) {
60 mono_profiler_printf_err ("Could not bind %s profiler server socket on port %d: %s", profiler_name, *command_port, g_strerror (errno));
61 mono_profhelper_close_socket_fd (*server_socket);
62 exit (1);
65 if (listen (*server_socket, 1) == -1) {
66 mono_profiler_printf_err ("Could not listen on %s profiler server socket: %s", profiler_name, g_strerror (errno));
67 mono_profhelper_close_socket_fd (*server_socket);
68 exit (1);
71 socklen_t slen = sizeof (server_address);
73 if (getsockname (*server_socket, (struct sockaddr *) &server_address, &slen)) {
74 mono_profiler_printf_err ("Could not retrieve assigned port for %s profiler server socket: %s", profiler_name, g_strerror (errno));
75 mono_profhelper_close_socket_fd (*server_socket);
76 exit (1);
79 *command_port = ntohs (server_address.sin_port);
82 void
83 mono_profhelper_add_to_fd_set (fd_set *set, int fd, int *max_fd)
86 * This should only trigger for the basic FDs (server socket, pipes) at
87 * startup if for some mysterious reason they're too large. In this case,
88 * the profiler really can't function, and we're better off printing an
89 * error and exiting.
91 if (fd >= FD_SETSIZE) {
92 mono_profiler_printf_err ("File descriptor is out of bounds for fd_set: %d", fd);
93 exit (1);
96 FD_SET (fd, set);
98 if (*max_fd < fd)
99 *max_fd = fd;