xref: /aosp_15_r20/external/wayland/src/wayland-server.c (revision 84e872a0dc482bffdb63672969dd03a827d67c73)
1 /*
2  * Copyright © 2008 Kristian Høgsberg
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining
5  * a copy of this software and associated documentation files (the
6  * "Software"), to deal in the Software without restriction, including
7  * without limitation the rights to use, copy, modify, merge, publish,
8  * distribute, sublicense, and/or sell copies of the Software, and to
9  * permit persons to whom the Software is furnished to do so, subject to
10  * the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the
13  * next paragraph) shall be included in all copies or substantial
14  * portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
20  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
21  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  */
25 
26 #define _GNU_SOURCE
27 
28 #include <stdbool.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <stddef.h>
32 #include <stdio.h>
33 #include <stdarg.h>
34 #include <errno.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <sys/socket.h>
38 #include <sys/un.h>
39 #include <dlfcn.h>
40 #include <assert.h>
41 #include <sys/time.h>
42 #include <fcntl.h>
43 #include <sys/eventfd.h>
44 #include <sys/file.h>
45 #include <sys/stat.h>
46 
47 #include "wayland-util.h"
48 #include "wayland-private.h"
49 #include "wayland-server-private.h"
50 #include "wayland-server.h"
51 #include "wayland-os.h"
52 
53 /* This is the size of the char array in struct sock_addr_un.
54  * No Wayland socket can be created with a path longer than this,
55  * including the null terminator.
56  */
57 #ifndef UNIX_PATH_MAX
58 #define UNIX_PATH_MAX	108
59 #endif
60 
61 #define LOCK_SUFFIX	".lock"
62 #define LOCK_SUFFIXLEN	5
63 
64 struct wl_socket {
65 	int fd;
66 	int fd_lock;
67 	struct sockaddr_un addr;
68 	char lock_addr[UNIX_PATH_MAX + LOCK_SUFFIXLEN];
69 	struct wl_list link;
70 	struct wl_event_source *source;
71 	char *display_name;
72 };
73 
74 struct wl_client {
75 	struct wl_connection *connection;
76 	struct wl_event_source *source;
77 	struct wl_display *display;
78 	struct wl_resource *display_resource;
79 	struct wl_list link;
80 	struct wl_map objects;
81 	struct wl_priv_signal destroy_signal;
82 	struct wl_priv_signal destroy_late_signal;
83 	pid_t pid;
84 	uid_t uid;
85 	gid_t gid;
86 	int error;
87 	struct wl_priv_signal resource_created_signal;
88 };
89 
90 struct wl_display {
91 	struct wl_event_loop *loop;
92 	int run;
93 
94 	uint32_t next_global_name;
95 	uint32_t serial;
96 
97 	struct wl_list registry_resource_list;
98 	struct wl_list global_list;
99 	struct wl_list socket_list;
100 	struct wl_list client_list;
101 	struct wl_list protocol_loggers;
102 
103 	struct wl_priv_signal destroy_signal;
104 	struct wl_priv_signal create_client_signal;
105 
106 	struct wl_array additional_shm_formats;
107 
108 	wl_display_global_filter_func_t global_filter;
109 	void *global_filter_data;
110 
111 	int terminate_efd;
112 	struct wl_event_source *term_source;
113 };
114 
115 struct wl_global {
116 	struct wl_display *display;
117 	const struct wl_interface *interface;
118 	uint32_t name;
119 	uint32_t version;
120 	void *data;
121 	wl_global_bind_func_t bind;
122 	struct wl_list link;
123 	bool removed;
124 };
125 
126 struct wl_resource {
127 	struct wl_object object;
128 	wl_resource_destroy_func_t destroy;
129 	struct wl_list link;
130 	/* Unfortunately some users of libwayland (e.g. mesa) still use the
131 	 * deprecated wl_resource struct, even if creating it with the new
132 	 * wl_resource_create(). So we cannot change the layout of the struct
133 	 * unless after the data field. */
134 	struct wl_signal deprecated_destroy_signal;
135 	struct wl_client *client;
136 	void *data;
137 	int version;
138 	wl_dispatcher_func_t dispatcher;
139 	struct wl_priv_signal destroy_signal;
140 };
141 
142 struct wl_protocol_logger {
143 	struct wl_list link;
144 	wl_protocol_logger_func_t func;
145 	void *user_data;
146 };
147 
148 static int debug_server = 0;
149 
150 static void
log_closure(struct wl_resource * resource,struct wl_closure * closure,int send)151 log_closure(struct wl_resource *resource,
152 	    struct wl_closure *closure, int send)
153 {
154 	struct wl_object *object = &resource->object;
155 	struct wl_display *display = resource->client->display;
156 	struct wl_protocol_logger *protocol_logger;
157 	struct wl_protocol_logger_message message;
158 
159 	if (debug_server)
160 		wl_closure_print(closure, object, send, NULL);
161 
162 	if (!wl_list_empty(&display->protocol_loggers)) {
163 		message.resource = resource;
164 		message.message_opcode = closure->opcode;
165 		message.message = closure->message;
166 		message.arguments_count = closure->count;
167 		message.arguments = closure->args;
168 		wl_list_for_each(protocol_logger,
169 				 &display->protocol_loggers, link) {
170 			protocol_logger->func(protocol_logger->user_data,
171 					      send ? WL_PROTOCOL_LOGGER_EVENT :
172 						     WL_PROTOCOL_LOGGER_REQUEST,
173 					      &message);
174 		}
175 	}
176 }
177 
178 static bool
verify_objects(struct wl_resource * resource,uint32_t opcode,union wl_argument * args)179 verify_objects(struct wl_resource *resource, uint32_t opcode,
180 	       union wl_argument *args)
181 {
182 	struct wl_object *object = &resource->object;
183 	const char *signature = object->interface->events[opcode].signature;
184 	struct argument_details arg;
185 	struct wl_resource *res;
186 	int count, i;
187 
188 	count = arg_count_for_signature(signature);
189 	for (i = 0; i < count; i++) {
190 		signature = get_next_argument(signature, &arg);
191 		switch (arg.type) {
192 		case 'n':
193 		case 'o':
194 			res = (struct wl_resource *) (args[i].o);
195 			if (res && res->client != resource->client) {
196 				wl_log("compositor bug: The compositor "
197 				       "tried to use an object from one "
198 				       "client in a '%s.%s' for a different "
199 				       "client.\n", object->interface->name,
200 				       object->interface->events[opcode].name);
201 				return false;
202 			}
203 		}
204 	}
205 	return true;
206 }
207 
208 static void
handle_array(struct wl_resource * resource,uint32_t opcode,union wl_argument * args,int (* send_func)(struct wl_closure *,struct wl_connection *))209 handle_array(struct wl_resource *resource, uint32_t opcode,
210 	     union wl_argument *args,
211 	     int (*send_func)(struct wl_closure *, struct wl_connection *))
212 {
213 	struct wl_closure *closure;
214 	struct wl_object *object = &resource->object;
215 
216 	if (resource->client->error)
217 		return;
218 
219 	if (!verify_objects(resource, opcode, args)) {
220 		resource->client->error = 1;
221 		return;
222 	}
223 
224 	closure = wl_closure_marshal(object, opcode, args,
225 				     &object->interface->events[opcode]);
226 
227 	if (closure == NULL) {
228 		resource->client->error = 1;
229 		return;
230 	}
231 
232 	log_closure(resource, closure, true);
233 
234 	if (send_func(closure, resource->client->connection))
235 		resource->client->error = 1;
236 
237 	wl_closure_destroy(closure);
238 }
239 
240 WL_EXPORT void
wl_resource_post_event_array(struct wl_resource * resource,uint32_t opcode,union wl_argument * args)241 wl_resource_post_event_array(struct wl_resource *resource, uint32_t opcode,
242 			     union wl_argument *args)
243 {
244 	handle_array(resource, opcode, args, wl_closure_send);
245 }
246 
247 WL_EXPORT void
wl_resource_post_event(struct wl_resource * resource,uint32_t opcode,...)248 wl_resource_post_event(struct wl_resource *resource, uint32_t opcode, ...)
249 {
250 	union wl_argument args[WL_CLOSURE_MAX_ARGS];
251 	struct wl_object *object = &resource->object;
252 	va_list ap;
253 
254 	va_start(ap, opcode);
255 	wl_argument_from_va_list(object->interface->events[opcode].signature,
256 				 args, WL_CLOSURE_MAX_ARGS, ap);
257 	va_end(ap);
258 
259 	wl_resource_post_event_array(resource, opcode, args);
260 }
261 
262 
263 WL_EXPORT void
wl_resource_queue_event_array(struct wl_resource * resource,uint32_t opcode,union wl_argument * args)264 wl_resource_queue_event_array(struct wl_resource *resource, uint32_t opcode,
265 			      union wl_argument *args)
266 {
267 	handle_array(resource, opcode, args, wl_closure_queue);
268 }
269 
270 WL_EXPORT void
wl_resource_queue_event(struct wl_resource * resource,uint32_t opcode,...)271 wl_resource_queue_event(struct wl_resource *resource, uint32_t opcode, ...)
272 {
273 	union wl_argument args[WL_CLOSURE_MAX_ARGS];
274 	struct wl_object *object = &resource->object;
275 	va_list ap;
276 
277 	va_start(ap, opcode);
278 	wl_argument_from_va_list(object->interface->events[opcode].signature,
279 				 args, WL_CLOSURE_MAX_ARGS, ap);
280 	va_end(ap);
281 
282 	wl_resource_queue_event_array(resource, opcode, args);
283 }
284 
285 static void
wl_resource_post_error_vargs(struct wl_resource * resource,uint32_t code,const char * msg,va_list argp)286 wl_resource_post_error_vargs(struct wl_resource *resource,
287 			     uint32_t code, const char *msg, va_list argp)
288 {
289 	struct wl_client *client = resource->client;
290 	char buffer[128];
291 
292 	vsnprintf(buffer, sizeof buffer, msg, argp);
293 
294 	/*
295 	 * When a client aborts, its resources are destroyed in id order,
296 	 * which means the display resource is destroyed first. If destruction
297 	 * of any later resources results in a protocol error, we end up here
298 	 * with a NULL display_resource. Do not try to send errors to an
299 	 * already dead client.
300 	 */
301 	if (client->error || !client->display_resource)
302 		return;
303 
304 	wl_resource_post_event(client->display_resource,
305 			       WL_DISPLAY_ERROR, resource, code, buffer);
306 	client->error = 1;
307 
308 }
309 
310 WL_EXPORT void
wl_resource_post_error(struct wl_resource * resource,uint32_t code,const char * msg,...)311 wl_resource_post_error(struct wl_resource *resource,
312 		       uint32_t code, const char *msg, ...)
313 {
314 	va_list ap;
315 
316 	va_start(ap, msg);
317 	wl_resource_post_error_vargs(resource, code, msg, ap);
318 	va_end(ap);
319 }
320 
321 static void
destroy_client_with_error(struct wl_client * client,const char * reason)322 destroy_client_with_error(struct wl_client *client, const char *reason)
323 {
324 	wl_log("%s (pid %u)\n", reason, client->pid);
325 	wl_client_destroy(client);
326 }
327 
328 static int
wl_client_connection_data(int fd,uint32_t mask,void * data)329 wl_client_connection_data(int fd, uint32_t mask, void *data)
330 {
331 	struct wl_client *client = data;
332 	struct wl_connection *connection = client->connection;
333 	struct wl_resource *resource;
334 	struct wl_object *object;
335 	struct wl_closure *closure;
336 	const struct wl_message *message;
337 	uint32_t p[2];
338 	uint32_t resource_flags;
339 	int opcode, size, since;
340 	int len;
341 
342 	if (mask & WL_EVENT_HANGUP) {
343 		wl_client_destroy(client);
344 		return 1;
345 	}
346 
347 	if (mask & WL_EVENT_ERROR) {
348 		destroy_client_with_error(client, "socket error");
349 		return 1;
350 	}
351 
352 	if (mask & WL_EVENT_WRITABLE) {
353 		len = wl_connection_flush(connection);
354 		if (len < 0 && errno != EAGAIN) {
355 			destroy_client_with_error(
356 			    client, "failed to flush client connection");
357 			return 1;
358 		} else if (len >= 0) {
359 			wl_event_source_fd_update(client->source,
360 						  WL_EVENT_READABLE);
361 		}
362 	}
363 
364 	len = 0;
365 	if (mask & WL_EVENT_READABLE) {
366 		len = wl_connection_read(connection);
367 		if (len == 0 || (len < 0 && errno != EAGAIN)) {
368 			destroy_client_with_error(
369 			    client, "failed to read client connection");
370 			return 1;
371 		}
372 	}
373 
374 	while (len >= 0 && (size_t) len >= sizeof p) {
375 		wl_connection_copy(connection, p, sizeof p);
376 		opcode = p[1] & 0xffff;
377 		size = p[1] >> 16;
378 		if (len < size)
379 			break;
380 
381 		resource = wl_map_lookup(&client->objects, p[0]);
382 		resource_flags = wl_map_lookup_flags(&client->objects, p[0]);
383 		if (resource == NULL) {
384 			wl_resource_post_error(client->display_resource,
385 					       WL_DISPLAY_ERROR_INVALID_OBJECT,
386 					       "invalid object %u", p[0]);
387 			break;
388 		}
389 
390 		object = &resource->object;
391 		if (opcode >= object->interface->method_count) {
392 			wl_resource_post_error(client->display_resource,
393 					       WL_DISPLAY_ERROR_INVALID_METHOD,
394 					       "invalid method %d, object %s@%u",
395 					       opcode,
396 					       object->interface->name,
397 					       object->id);
398 			break;
399 		}
400 
401 		message = &object->interface->methods[opcode];
402 		since = wl_message_get_since(message);
403 		if (!(resource_flags & WL_MAP_ENTRY_LEGACY) &&
404 		    resource->version > 0 && resource->version < since) {
405 			wl_resource_post_error(client->display_resource,
406 					       WL_DISPLAY_ERROR_INVALID_METHOD,
407 					       "invalid method %d (since %d < %d)"
408 					       ", object %s@%u",
409 					       opcode, resource->version, since,
410 					       object->interface->name,
411 					       object->id);
412 			break;
413 		}
414 
415 
416 		closure = wl_connection_demarshal(client->connection, size,
417 						  &client->objects, message);
418 
419 		if (closure == NULL && errno == ENOMEM) {
420 			wl_resource_post_no_memory(resource);
421 			break;
422 		} else if (closure == NULL ||
423 			   wl_closure_lookup_objects(closure, &client->objects) < 0) {
424 			wl_resource_post_error(client->display_resource,
425 					       WL_DISPLAY_ERROR_INVALID_METHOD,
426 					       "invalid arguments for %s@%u.%s",
427 					       object->interface->name,
428 					       object->id,
429 					       message->name);
430 			wl_closure_destroy(closure);
431 			break;
432 		}
433 
434 		log_closure(resource, closure, false);
435 
436 		if ((resource_flags & WL_MAP_ENTRY_LEGACY) ||
437 		    resource->dispatcher == NULL) {
438 			wl_closure_invoke(closure, WL_CLOSURE_INVOKE_SERVER,
439 					  object, opcode, client);
440 		} else {
441 			wl_closure_dispatch(closure, resource->dispatcher,
442 					    object, opcode);
443 		}
444 
445 		wl_closure_destroy(closure);
446 
447 		if (client->error)
448 			break;
449 
450 		len = wl_connection_pending_input(connection);
451 	}
452 
453 	if (client->error) {
454 		destroy_client_with_error(client,
455 					  "error in client communication");
456 	}
457 
458 	return 1;
459 }
460 
461 /** Flush pending events to the client
462  *
463  * \param client The client object
464  *
465  * Events sent to clients are queued in a buffer and written to the
466  * socket later - typically when the compositor has handled all
467  * requests and goes back to block in the event loop.  This function
468  * flushes all queued up events for a client immediately.
469  *
470  * \memberof wl_client
471  */
472 WL_EXPORT void
wl_client_flush(struct wl_client * client)473 wl_client_flush(struct wl_client *client)
474 {
475 	wl_connection_flush(client->connection);
476 }
477 
478 /** Get the display object for the given client
479  *
480  * \param client The client object
481  * \return The display object the client is associated with.
482  *
483  * \memberof wl_client
484  */
485 WL_EXPORT struct wl_display *
wl_client_get_display(struct wl_client * client)486 wl_client_get_display(struct wl_client *client)
487 {
488 	return client->display;
489 }
490 
491 static int
492 bind_display(struct wl_client *client, struct wl_display *display);
493 
494 /** Create a client for the given file descriptor
495  *
496  * \param display The display object
497  * \param fd The file descriptor for the socket to the client
498  * \return The new client object or NULL on failure.
499  *
500  * Given a file descriptor corresponding to one end of a socket, this
501  * function will create a wl_client struct and add the new client to
502  * the compositors client list.  At that point, the client is
503  * initialized and ready to run, as if the client had connected to the
504  * servers listening socket.  When the client eventually sends
505  * requests to the compositor, the wl_client argument to the request
506  * handler will be the wl_client returned from this function.
507  *
508  * The other end of the socket can be passed to
509  * wl_display_connect_to_fd() on the client side or used with the
510  * WAYLAND_SOCKET environment variable on the client side.
511  *
512  * Listeners added with wl_display_add_client_created_listener() will
513  * be notified by this function after the client is fully constructed.
514  *
515  * On failure this function sets errno accordingly and returns NULL.
516  *
517  * \memberof wl_display
518  */
519 WL_EXPORT struct wl_client *
wl_client_create(struct wl_display * display,int fd)520 wl_client_create(struct wl_display *display, int fd)
521 {
522 	struct wl_client *client;
523 
524 	client = zalloc(sizeof *client);
525 	if (client == NULL)
526 		return NULL;
527 
528 	wl_priv_signal_init(&client->resource_created_signal);
529 	client->display = display;
530 	client->source = wl_event_loop_add_fd(display->loop, fd,
531 					      WL_EVENT_READABLE,
532 					      wl_client_connection_data, client);
533 
534 	if (!client->source)
535 		goto err_client;
536 
537 	if (wl_os_socket_peercred(fd, &client->uid, &client->gid,
538 				  &client->pid) != 0)
539 		goto err_source;
540 
541 	client->connection = wl_connection_create(fd);
542 	if (client->connection == NULL)
543 		goto err_source;
544 
545 	wl_map_init(&client->objects, WL_MAP_SERVER_SIDE);
546 
547 	if (wl_map_insert_at(&client->objects, 0, 0, NULL) < 0)
548 		goto err_map;
549 
550 	wl_priv_signal_init(&client->destroy_signal);
551 	wl_priv_signal_init(&client->destroy_late_signal);
552 	if (bind_display(client, display) < 0)
553 		goto err_map;
554 
555 	wl_list_insert(display->client_list.prev, &client->link);
556 
557 	wl_priv_signal_emit(&display->create_client_signal, client);
558 
559 	return client;
560 
561 err_map:
562 	wl_map_release(&client->objects);
563 	wl_connection_destroy(client->connection);
564 err_source:
565 	wl_event_source_remove(client->source);
566 err_client:
567 	free(client);
568 	return NULL;
569 }
570 
571 /** Return Unix credentials for the client
572  *
573  * \param client The display object
574  * \param pid Returns the process ID
575  * \param uid Returns the user ID
576  * \param gid Returns the group ID
577  *
578  * This function returns the process ID, the user ID and the group ID
579  * for the given client.  The credentials come from getsockopt() with
580  * SO_PEERCRED, on the client socket fd.  All the pointers can be
581  * NULL, if the caller is not interested in a particular ID.
582  *
583  * Note, process IDs are subject to race conditions and are not a reliable way
584  * to identify a client.
585  *
586  * Be aware that for clients that a compositor forks and execs and
587  * then connects using socketpair(), this function will return the
588  * credentials for the compositor.  The credentials for the socketpair
589  * are set at creation time in the compositor.
590  *
591  * \memberof wl_client
592  */
593 WL_EXPORT void
wl_client_get_credentials(struct wl_client * client,pid_t * pid,uid_t * uid,gid_t * gid)594 wl_client_get_credentials(struct wl_client *client,
595 			  pid_t *pid, uid_t *uid, gid_t *gid)
596 {
597 	if (pid)
598 		*pid = client->pid;
599 	if (uid)
600 		*uid = client->uid;
601 	if (gid)
602 		*gid = client->gid;
603 }
604 
605 /** Get the file descriptor for the client
606  *
607  * \param client The display object
608  * \return The file descriptor to use for the connection
609  *
610  * This function returns the file descriptor for the given client.
611  *
612  * Be sure to use the file descriptor from the client for inspection only.
613  * If the caller does anything to the file descriptor that changes its state,
614  * it will likely cause problems.
615  *
616  * See also wl_client_get_credentials().
617  * It is recommended that you evaluate whether wl_client_get_credentials()
618  * can be applied to your use case instead of this function.
619  *
620  * If you would like to distinguish just between the client and the compositor
621  * itself from the client's request, it can be done by getting the client
622  * credentials and by checking the PID of the client and the compositor's PID.
623  * Regarding the case in which the socketpair() is being used, you need to be
624  * careful. Please note the documentation for wl_client_get_credentials().
625  *
626  * This function can be used for a compositor to validate a request from
627  * a client if there are additional information provided from the client's
628  * file descriptor. For instance, suppose you can get the security contexts
629  * from the client's file descriptor. The compositor can validate the client's
630  * request with the contexts and make a decision whether it permits or deny it.
631  *
632  * \memberof wl_client
633  */
634 WL_EXPORT int
wl_client_get_fd(struct wl_client * client)635 wl_client_get_fd(struct wl_client *client)
636 {
637 	return wl_connection_get_fd(client->connection);
638 }
639 
640 /** Look up an object in the client name space
641  *
642  * \param client The client object
643  * \param id The object id
644  * \return The object or NULL if there is not object for the given ID
645  *
646  * This looks up an object in the client object name space by its
647  * object ID.
648  *
649  * \memberof wl_client
650  */
651 WL_EXPORT struct wl_resource *
wl_client_get_object(struct wl_client * client,uint32_t id)652 wl_client_get_object(struct wl_client *client, uint32_t id)
653 {
654 	return wl_map_lookup(&client->objects, id);
655 }
656 
657 WL_EXPORT void
wl_client_post_no_memory(struct wl_client * client)658 wl_client_post_no_memory(struct wl_client *client)
659 {
660 	wl_resource_post_error(client->display_resource,
661 			       WL_DISPLAY_ERROR_NO_MEMORY, "no memory");
662 }
663 
664 /** Report an internal server error
665  *
666  * \param client The client object
667  * \param msg A printf-style format string
668  * \param ... Format string arguments
669  *
670  * Report an unspecified internal implementation error and disconnect
671  * the client.
672  *
673  * \memberof wl_client
674  */
675 WL_EXPORT void
wl_client_post_implementation_error(struct wl_client * client,char const * msg,...)676 wl_client_post_implementation_error(struct wl_client *client,
677 				    char const *msg, ...)
678 {
679 	va_list ap;
680 
681 	va_start(ap, msg);
682 	wl_resource_post_error_vargs(client->display_resource,
683 				     WL_DISPLAY_ERROR_IMPLEMENTATION,
684 				     msg, ap);
685 	va_end(ap);
686 }
687 
688 WL_EXPORT void
wl_resource_post_no_memory(struct wl_resource * resource)689 wl_resource_post_no_memory(struct wl_resource *resource)
690 {
691 	wl_resource_post_error(resource->client->display_resource,
692 			       WL_DISPLAY_ERROR_NO_MEMORY, "no memory");
693 }
694 
695 /** Detect if a wl_resource uses the deprecated public definition.
696  *
697  * Before Wayland 1.2.0, the definition of struct wl_resource was public.
698  * It was made opaque just before 1.2.0, and later new fields were added.
699  * The new fields cannot be accessed if a program is using the deprecated
700  * definition, as there would not be memory allocated for them.
701  *
702  * The creation pattern for the deprecated definition was wl_resource_init()
703  * followed by wl_client_add_resource(). wl_resource_init() was an inline
704  * function and no longer exists, but binaries might still carry it.
705  * wl_client_add_resource() still exists for ABI compatibility.
706  */
707 static bool
resource_is_deprecated(struct wl_resource * resource)708 resource_is_deprecated(struct wl_resource *resource)
709 {
710 	struct wl_map *map = &resource->client->objects;
711 	int id = resource->object.id;
712 
713 	/* wl_client_add_resource() marks deprecated resources with the flag. */
714 	if (wl_map_lookup_flags(map, id) & WL_MAP_ENTRY_LEGACY)
715 		return true;
716 
717 	return false;
718 }
719 
720 static enum wl_iterator_result
destroy_resource(void * element,void * data,uint32_t flags)721 destroy_resource(void *element, void *data, uint32_t flags)
722 {
723 	struct wl_resource *resource = element;
724 
725 	wl_signal_emit(&resource->deprecated_destroy_signal, resource);
726 	/* Don't emit the new signal for deprecated resources, as that would
727 	 * access memory outside the bounds of the deprecated struct */
728 	if (!resource_is_deprecated(resource))
729 		wl_priv_signal_final_emit(&resource->destroy_signal, resource);
730 
731 	if (resource->destroy)
732 		resource->destroy(resource);
733 
734 	if (!(flags & WL_MAP_ENTRY_LEGACY))
735 		free(resource);
736 
737 	return WL_ITERATOR_CONTINUE;
738 }
739 
740 WL_EXPORT void
wl_resource_destroy(struct wl_resource * resource)741 wl_resource_destroy(struct wl_resource *resource)
742 {
743 	struct wl_client *client = resource->client;
744 	uint32_t id;
745 	uint32_t flags;
746 
747 	id = resource->object.id;
748 	flags = wl_map_lookup_flags(&client->objects, id);
749 	destroy_resource(resource, NULL, flags);
750 
751 	if (id < WL_SERVER_ID_START) {
752 		if (client->display_resource) {
753 			wl_resource_queue_event(client->display_resource,
754 						WL_DISPLAY_DELETE_ID, id);
755 		}
756 		wl_map_insert_at(&client->objects, 0, id, NULL);
757 	} else {
758 		wl_map_remove(&client->objects, id);
759 	}
760 }
761 
762 WL_EXPORT uint32_t
wl_resource_get_id(struct wl_resource * resource)763 wl_resource_get_id(struct wl_resource *resource)
764 {
765 	return resource->object.id;
766 }
767 
768 WL_EXPORT struct wl_list *
wl_resource_get_link(struct wl_resource * resource)769 wl_resource_get_link(struct wl_resource *resource)
770 {
771 	return &resource->link;
772 }
773 
774 WL_EXPORT struct wl_resource *
wl_resource_from_link(struct wl_list * link)775 wl_resource_from_link(struct wl_list *link)
776 {
777 	struct wl_resource *resource;
778 
779 	return wl_container_of(link, resource, link);
780 }
781 
782 WL_EXPORT struct wl_resource *
wl_resource_find_for_client(struct wl_list * list,struct wl_client * client)783 wl_resource_find_for_client(struct wl_list *list, struct wl_client *client)
784 {
785 	struct wl_resource *resource;
786 
787 	if (client == NULL)
788 		return NULL;
789 
790 	wl_list_for_each(resource, list, link) {
791 		if (resource->client == client)
792 			return resource;
793 	}
794 
795 	return NULL;
796 }
797 
798 WL_EXPORT struct wl_client *
wl_resource_get_client(struct wl_resource * resource)799 wl_resource_get_client(struct wl_resource *resource)
800 {
801 	return resource->client;
802 }
803 
804 WL_EXPORT void
wl_resource_set_user_data(struct wl_resource * resource,void * data)805 wl_resource_set_user_data(struct wl_resource *resource, void *data)
806 {
807 	resource->data = data;
808 }
809 
810 WL_EXPORT void *
wl_resource_get_user_data(struct wl_resource * resource)811 wl_resource_get_user_data(struct wl_resource *resource)
812 {
813 	return resource->data;
814 }
815 
816 WL_EXPORT int
wl_resource_get_version(struct wl_resource * resource)817 wl_resource_get_version(struct wl_resource *resource)
818 {
819 	return resource->version;
820 }
821 
822 WL_EXPORT void
wl_resource_set_destructor(struct wl_resource * resource,wl_resource_destroy_func_t destroy)823 wl_resource_set_destructor(struct wl_resource *resource,
824 			   wl_resource_destroy_func_t destroy)
825 {
826 	resource->destroy = destroy;
827 }
828 
829 WL_EXPORT int
wl_resource_instance_of(struct wl_resource * resource,const struct wl_interface * interface,const void * implementation)830 wl_resource_instance_of(struct wl_resource *resource,
831 			const struct wl_interface *interface,
832 			const void *implementation)
833 {
834 	return wl_interface_equal(resource->object.interface, interface) &&
835 		resource->object.implementation == implementation;
836 }
837 
838 WL_EXPORT void
wl_resource_add_destroy_listener(struct wl_resource * resource,struct wl_listener * listener)839 wl_resource_add_destroy_listener(struct wl_resource *resource,
840 				 struct wl_listener * listener)
841 {
842 	if (resource_is_deprecated(resource))
843 		wl_signal_add(&resource->deprecated_destroy_signal, listener);
844 	else
845 		wl_priv_signal_add(&resource->destroy_signal, listener);
846 }
847 
848 WL_EXPORT struct wl_listener *
wl_resource_get_destroy_listener(struct wl_resource * resource,wl_notify_func_t notify)849 wl_resource_get_destroy_listener(struct wl_resource *resource,
850 				 wl_notify_func_t notify)
851 {
852 	if (resource_is_deprecated(resource))
853 		return wl_signal_get(&resource->deprecated_destroy_signal, notify);
854 	return wl_priv_signal_get(&resource->destroy_signal, notify);
855 }
856 
857 /** Retrieve the interface name (class) of a resource object.
858  *
859  * \param resource The resource object
860  *
861  * \memberof wl_resource
862  */
863 WL_EXPORT const char *
wl_resource_get_class(struct wl_resource * resource)864 wl_resource_get_class(struct wl_resource *resource)
865 {
866 	return resource->object.interface->name;
867 }
868 
869 /** Safely converts an object into its corresponding resource
870  *
871  * \param object object to get the resource for
872  * \return A corresponding resource, or NULL on failure
873  *
874  * Safely converts an object into its corresponding resource.
875  *
876  * This is useful for implementing functions that are given a \c wl_argument
877  * array, and that need to do further introspection on the ".o" field, as it
878  * is otherwise an opaque type.
879  *
880  * \memberof wl_resource
881  */
882 WL_EXPORT struct wl_resource *
wl_resource_from_object(struct wl_object * object)883 wl_resource_from_object(struct wl_object *object)
884 {
885 	struct wl_resource *resource;
886 	if (object == NULL)
887 		return NULL;
888 	return wl_container_of(object, resource, object);
889 }
890 
891 /**
892  * Add a listener to be called at the beginning of wl_client destruction
893  *
894  * The listener provided will be called when wl_client destroy has begun,
895  * before any of that client's resources have been destroyed.
896  *
897  * There is no requirement to remove the link of the wl_listener when the
898  * signal is emitted.
899  *
900  * \memberof wl_client
901  */
902 WL_EXPORT void
wl_client_add_destroy_listener(struct wl_client * client,struct wl_listener * listener)903 wl_client_add_destroy_listener(struct wl_client *client,
904 			       struct wl_listener *listener)
905 {
906 	wl_priv_signal_add(&client->destroy_signal, listener);
907 }
908 
909 WL_EXPORT struct wl_listener *
wl_client_get_destroy_listener(struct wl_client * client,wl_notify_func_t notify)910 wl_client_get_destroy_listener(struct wl_client *client,
911 			       wl_notify_func_t notify)
912 {
913 	return wl_priv_signal_get(&client->destroy_signal, notify);
914 }
915 
916 /**
917  * Add a listener to be called at the end of wl_client destruction
918  *
919  * The listener provided will be called when wl_client destroy is nearly
920  * complete, after all of that client's resources have been destroyed.
921  *
922  * There is no requirement to remove the link of the wl_listener when the
923  * signal is emitted.
924  *
925  * \memberof wl_client
926  * \since 1.22.0
927  */
928 WL_EXPORT void
wl_client_add_destroy_late_listener(struct wl_client * client,struct wl_listener * listener)929 wl_client_add_destroy_late_listener(struct wl_client *client,
930 				    struct wl_listener *listener)
931 {
932 	wl_priv_signal_add(&client->destroy_late_signal, listener);
933 }
934 
935 WL_EXPORT struct wl_listener *
wl_client_get_destroy_late_listener(struct wl_client * client,wl_notify_func_t notify)936 wl_client_get_destroy_late_listener(struct wl_client *client,
937 				    wl_notify_func_t notify)
938 {
939 	return wl_priv_signal_get(&client->destroy_late_signal, notify);
940 }
941 
942 WL_EXPORT void
wl_client_destroy(struct wl_client * client)943 wl_client_destroy(struct wl_client *client)
944 {
945 	uint32_t serial = 0;
946 
947 	wl_priv_signal_final_emit(&client->destroy_signal, client);
948 
949 	wl_client_flush(client);
950 	wl_map_for_each(&client->objects, destroy_resource, &serial);
951 	wl_map_release(&client->objects);
952 	wl_event_source_remove(client->source);
953 	close(wl_connection_destroy(client->connection));
954 
955 	wl_priv_signal_final_emit(&client->destroy_late_signal, client);
956 
957 	wl_list_remove(&client->link);
958 	wl_list_remove(&client->resource_created_signal.listener_list);
959 	free(client);
960 }
961 
962 /* Check if a global filter is registered and use it if any.
963  *
964  * If no wl_global filter has been registered, this function will
965  * return true, allowing the wl_global to be visible to the wl_client
966  */
967 static bool
wl_global_is_visible(const struct wl_client * client,const struct wl_global * global)968 wl_global_is_visible(const struct wl_client *client,
969 	      const struct wl_global *global)
970 {
971 	struct wl_display *display = client->display;
972 
973 	return (display->global_filter == NULL ||
974 		display->global_filter(client, global, display->global_filter_data));
975 }
976 
977 static void
registry_bind(struct wl_client * client,struct wl_resource * resource,uint32_t name,const char * interface,uint32_t version,uint32_t id)978 registry_bind(struct wl_client *client,
979 	      struct wl_resource *resource, uint32_t name,
980 	      const char *interface, uint32_t version, uint32_t id)
981 {
982 	struct wl_global *global;
983 	struct wl_display *display = resource->data;
984 
985 	wl_list_for_each(global, &display->global_list, link)
986 		if (global->name == name)
987 			break;
988 
989 	if (&global->link == &display->global_list)
990 		wl_resource_post_error(resource,
991 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
992 				       "invalid global %s (%d)", interface, name);
993 	else if (strcmp(global->interface->name, interface) != 0)
994 		wl_resource_post_error(resource,
995 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
996 				       "invalid interface for global %u: "
997 				       "have %s, wanted %s",
998 				       name, interface, global->interface->name);
999 	else if (version == 0)
1000 		wl_resource_post_error(resource,
1001 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
1002 				       "invalid version for global %s (%d): 0 is not a valid version",
1003 				       interface, name);
1004 	else if (global->version < version)
1005 		wl_resource_post_error(resource,
1006 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
1007 				       "invalid version for global %s (%d): have %d, wanted %d",
1008 				       interface, name, global->version, version);
1009 	else if (!wl_global_is_visible(client, global))
1010 		wl_resource_post_error(resource,
1011 				       WL_DISPLAY_ERROR_INVALID_OBJECT,
1012 				       "invalid global %s (%d)", interface, name);
1013 	else
1014 		global->bind(client, global->data, version, id);
1015 }
1016 
1017 static const struct wl_registry_interface registry_interface = {
1018 	registry_bind
1019 };
1020 
1021 static void
display_sync(struct wl_client * client,struct wl_resource * resource,uint32_t id)1022 display_sync(struct wl_client *client,
1023 	     struct wl_resource *resource, uint32_t id)
1024 {
1025 	struct wl_resource *callback;
1026 	uint32_t serial;
1027 
1028 	callback = wl_resource_create(client, &wl_callback_interface, 1, id);
1029 	if (callback == NULL) {
1030 		wl_client_post_no_memory(client);
1031 		return;
1032 	}
1033 
1034 	serial = wl_display_get_serial(client->display);
1035 	wl_callback_send_done(callback, serial);
1036 	wl_resource_destroy(callback);
1037 }
1038 
1039 static void
unbind_resource(struct wl_resource * resource)1040 unbind_resource(struct wl_resource *resource)
1041 {
1042 	wl_list_remove(&resource->link);
1043 }
1044 
1045 static void
display_get_registry(struct wl_client * client,struct wl_resource * resource,uint32_t id)1046 display_get_registry(struct wl_client *client,
1047 		     struct wl_resource *resource, uint32_t id)
1048 {
1049 	struct wl_display *display = resource->data;
1050 	struct wl_resource *registry_resource;
1051 	struct wl_global *global;
1052 
1053 	registry_resource =
1054 		wl_resource_create(client, &wl_registry_interface, 1, id);
1055 	if (registry_resource == NULL) {
1056 		wl_client_post_no_memory(client);
1057 		return;
1058 	}
1059 
1060 	wl_resource_set_implementation(registry_resource,
1061 				       &registry_interface,
1062 				       display, unbind_resource);
1063 
1064 	wl_list_insert(&display->registry_resource_list,
1065 		       &registry_resource->link);
1066 
1067 	wl_list_for_each(global, &display->global_list, link)
1068 		if (wl_global_is_visible(client, global) && !global->removed)
1069 			wl_resource_post_event(registry_resource,
1070 					       WL_REGISTRY_GLOBAL,
1071 					       global->name,
1072 					       global->interface->name,
1073 					       global->version);
1074 }
1075 
1076 static const struct wl_display_interface display_interface = {
1077 	display_sync,
1078 	display_get_registry
1079 };
1080 
1081 static void
destroy_client_display_resource(struct wl_resource * resource)1082 destroy_client_display_resource(struct wl_resource *resource)
1083 {
1084 	resource->client->display_resource = NULL;
1085 }
1086 
1087 static int
bind_display(struct wl_client * client,struct wl_display * display)1088 bind_display(struct wl_client *client, struct wl_display *display)
1089 {
1090 	client->display_resource =
1091 		wl_resource_create(client, &wl_display_interface, 1, 1);
1092 	if (client->display_resource == NULL) {
1093 		/* DON'T send no-memory error to client - it has no
1094 		 * resource to which it could post the event */
1095 		return -1;
1096 	}
1097 
1098 	wl_resource_set_implementation(client->display_resource,
1099 				       &display_interface, display,
1100 				       destroy_client_display_resource);
1101 	return 0;
1102 }
1103 
1104 static int
handle_display_terminate(int fd,uint32_t mask,void * data)1105 handle_display_terminate(int fd, uint32_t mask, void *data) {
1106 	uint64_t term_event;
1107 
1108 	if (read(fd, &term_event, sizeof(term_event)) < 0 && errno != EAGAIN)
1109 		return -1;
1110 
1111 	return 0;
1112 }
1113 
1114 /** Create Wayland display object.
1115  *
1116  * \return The Wayland display object. Null if failed to create
1117  *
1118  * This creates the wl_display object.
1119  *
1120  * \memberof wl_display
1121  */
1122 WL_EXPORT struct wl_display *
wl_display_create(void)1123 wl_display_create(void)
1124 {
1125 	struct wl_display *display;
1126 	const char *debug;
1127 
1128 	debug = getenv("WAYLAND_DEBUG");
1129 	if (debug && (strstr(debug, "server") || strstr(debug, "1")))
1130 		debug_server = 1;
1131 
1132 	display = zalloc(sizeof *display);
1133 	if (display == NULL)
1134 		return NULL;
1135 
1136 	display->loop = wl_event_loop_create();
1137 	if (display->loop == NULL) {
1138 		free(display);
1139 		return NULL;
1140 	}
1141 
1142 	display->terminate_efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
1143 	if (display->terminate_efd < 0)
1144 		goto err_eventfd;
1145 
1146 	display->term_source = wl_event_loop_add_fd(display->loop,
1147 						    display->terminate_efd,
1148 						    WL_EVENT_READABLE,
1149 						    handle_display_terminate,
1150 						    NULL);
1151 
1152 	if (display->term_source == NULL)
1153 		goto err_term_source;
1154 
1155 	wl_list_init(&display->global_list);
1156 	wl_list_init(&display->socket_list);
1157 	wl_list_init(&display->client_list);
1158 	wl_list_init(&display->registry_resource_list);
1159 	wl_list_init(&display->protocol_loggers);
1160 
1161 	wl_priv_signal_init(&display->destroy_signal);
1162 	wl_priv_signal_init(&display->create_client_signal);
1163 
1164 	display->next_global_name = 1;
1165 	display->serial = 0;
1166 
1167 	display->global_filter = NULL;
1168 	display->global_filter_data = NULL;
1169 
1170 	wl_array_init(&display->additional_shm_formats);
1171 
1172 	return display;
1173 
1174 err_term_source:
1175 	close(display->terminate_efd);
1176 err_eventfd:
1177 	wl_event_loop_destroy(display->loop);
1178 	free(display);
1179 	return NULL;
1180 }
1181 
1182 static void
wl_socket_destroy(struct wl_socket * s)1183 wl_socket_destroy(struct wl_socket *s)
1184 {
1185 	if (s->source)
1186 		wl_event_source_remove(s->source);
1187 	if (s->addr.sun_path[0])
1188 		unlink(s->addr.sun_path);
1189 	if (s->fd >= 0)
1190 		close(s->fd);
1191 	if (s->lock_addr[0])
1192 		unlink(s->lock_addr);
1193 	if (s->fd_lock >= 0)
1194 		close(s->fd_lock);
1195 
1196 	free(s);
1197 }
1198 
1199 static struct wl_socket *
wl_socket_alloc(void)1200 wl_socket_alloc(void)
1201 {
1202 	struct wl_socket *s;
1203 
1204 	s = zalloc(sizeof *s);
1205 	if (!s)
1206 		return NULL;
1207 
1208 	s->fd = -1;
1209 	s->fd_lock = -1;
1210 
1211 	return s;
1212 }
1213 
1214 /** Destroy Wayland display object.
1215  *
1216  * \param display The Wayland display object which should be destroyed.
1217  *
1218  * This function emits the wl_display destroy signal, releases
1219  * all the sockets added to this display, free's all the globals associated
1220  * with this display, free's memory of additional shared memory formats and
1221  * destroy the display object.
1222  *
1223  * \sa wl_display_add_destroy_listener
1224  *
1225  * \memberof wl_display
1226  */
1227 WL_EXPORT void
wl_display_destroy(struct wl_display * display)1228 wl_display_destroy(struct wl_display *display)
1229 {
1230 	struct wl_socket *s, *next;
1231 	struct wl_global *global, *gnext;
1232 
1233 	wl_priv_signal_final_emit(&display->destroy_signal, display);
1234 
1235 	wl_list_for_each_safe(s, next, &display->socket_list, link) {
1236 		wl_socket_destroy(s);
1237 	}
1238 
1239 	close(display->terminate_efd);
1240 	wl_event_source_remove(display->term_source);
1241 
1242 	wl_event_loop_destroy(display->loop);
1243 
1244 	wl_list_for_each_safe(global, gnext, &display->global_list, link)
1245 		free(global);
1246 
1247 	wl_array_release(&display->additional_shm_formats);
1248 
1249 	wl_list_remove(&display->protocol_loggers);
1250 
1251 	free(display);
1252 }
1253 
1254 /** Set a filter function for global objects
1255  *
1256  * \param display The Wayland display object.
1257  * \param filter  The global filter function.
1258  * \param data User data to be associated with the global filter.
1259  *
1260  * Set a filter for the wl_display to advertise or hide global objects
1261  * to clients.
1262  * The set filter will be used during wl_global advertisement to
1263  * determine whether a global object should be advertised to a
1264  * given client, and during wl_global binding to determine whether
1265  * a given client should be allowed to bind to a global.
1266  *
1267  * Clients that try to bind to a global that was filtered out will
1268  * have an error raised.
1269  *
1270  * Setting the filter NULL will result in all globals being
1271  * advertised to all clients. The default is no filter.
1272  *
1273  * The filter should be installed before any client connects and should always
1274  * take the same decision given a client and a global. Not doing so will result
1275  * in inconsistent filtering and broken wl_registry event sequences.
1276  *
1277  * \memberof wl_display
1278  */
1279 WL_EXPORT void
wl_display_set_global_filter(struct wl_display * display,wl_display_global_filter_func_t filter,void * data)1280 wl_display_set_global_filter(struct wl_display *display,
1281 			     wl_display_global_filter_func_t filter,
1282 			     void *data)
1283 {
1284 	display->global_filter = filter;
1285 	display->global_filter_data = data;
1286 }
1287 
1288 WL_EXPORT struct wl_global *
wl_global_create(struct wl_display * display,const struct wl_interface * interface,int version,void * data,wl_global_bind_func_t bind)1289 wl_global_create(struct wl_display *display,
1290 		 const struct wl_interface *interface, int version,
1291 		 void *data, wl_global_bind_func_t bind)
1292 {
1293 	struct wl_global *global;
1294 	struct wl_resource *resource;
1295 
1296 	if (version < 1) {
1297 		wl_log("wl_global_create: failing to create interface "
1298 		       "'%s' with version %d because it is less than 1\n",
1299 			interface->name, version);
1300 		return NULL;
1301 	}
1302 
1303 	if (version > interface->version) {
1304 		wl_log("wl_global_create: implemented version for '%s' "
1305 		       "higher than interface version (%d > %d)\n",
1306 		       interface->name, version, interface->version);
1307 		return NULL;
1308 	}
1309 
1310 	if (display->next_global_name >= UINT32_MAX) {
1311 		wl_log("wl_global_create: ran out of global names\n");
1312 		return NULL;
1313 	}
1314 
1315 	global = zalloc(sizeof *global);
1316 	if (global == NULL)
1317 		return NULL;
1318 
1319 	global->display = display;
1320 	global->name = display->next_global_name++;
1321 	global->interface = interface;
1322 	global->version = version;
1323 	global->data = data;
1324 	global->bind = bind;
1325 	global->removed = false;
1326 	wl_list_insert(display->global_list.prev, &global->link);
1327 
1328 	wl_list_for_each(resource, &display->registry_resource_list, link)
1329 		if (wl_global_is_visible(resource->client, global))
1330 			wl_resource_post_event(resource,
1331 					       WL_REGISTRY_GLOBAL,
1332 					       global->name,
1333 					       global->interface->name,
1334 					       global->version);
1335 
1336 	return global;
1337 }
1338 
1339 /** Remove the global
1340  *
1341  * \param global The Wayland global.
1342  *
1343  * Broadcast a global remove event to all clients without destroying the
1344  * global. This function can only be called once per global.
1345  *
1346  * wl_global_destroy() removes the global and immediately destroys it. On
1347  * the other end, this function only removes the global, allowing clients
1348  * that have not yet received the global remove event to continue to bind to
1349  * it.
1350  *
1351  * This can be used by compositors to mitigate clients being disconnected
1352  * because a global has been added and removed too quickly. Compositors can call
1353  * wl_global_remove(), then wait an implementation-defined amount of time, then
1354  * call wl_global_destroy(). Note that the destruction of a global is still
1355  * racy, since clients have no way to acknowledge that they received the remove
1356  * event.
1357  *
1358  * \since 1.17.90
1359  */
1360 WL_EXPORT void
wl_global_remove(struct wl_global * global)1361 wl_global_remove(struct wl_global *global)
1362 {
1363 	struct wl_display *display = global->display;
1364 	struct wl_resource *resource;
1365 
1366 	if (global->removed)
1367 		wl_abort("wl_global_remove: called twice on the same "
1368 			 "global '%s@%"PRIu32"'", global->interface->name,
1369 			 global->name);
1370 
1371 	wl_list_for_each(resource, &display->registry_resource_list, link)
1372 		if (wl_global_is_visible(resource->client, global))
1373 			wl_resource_post_event(resource, WL_REGISTRY_GLOBAL_REMOVE,
1374 					       global->name);
1375 
1376 	global->removed = true;
1377 }
1378 
1379 WL_EXPORT void
wl_global_destroy(struct wl_global * global)1380 wl_global_destroy(struct wl_global *global)
1381 {
1382 	if (!global->removed)
1383 		wl_global_remove(global);
1384 	wl_list_remove(&global->link);
1385 	free(global);
1386 }
1387 
1388 WL_EXPORT const struct wl_interface *
wl_global_get_interface(const struct wl_global * global)1389 wl_global_get_interface(const struct wl_global *global)
1390 {
1391 	return global->interface;
1392 }
1393 
1394 /** Get the name of the global.
1395  *
1396  * \param global The global object.
1397  * \param client Client for which to look up the global.
1398  * \return The name of the global, or 0 if the global is not visible to the
1399  *         client.
1400  *
1401  * \memberof wl_global
1402  * \since 1.22
1403  */
1404 WL_EXPORT uint32_t
wl_global_get_name(const struct wl_global * global,const struct wl_client * client)1405 wl_global_get_name(const struct wl_global *global,
1406 		   const struct wl_client *client)
1407 {
1408 	return wl_global_is_visible(client, global) ? global->name : 0;
1409 }
1410 
1411 /** Get the version of the given global.
1412  *
1413  * \param global The global object.
1414  * \return The version advertised by the global.
1415  *
1416  * \memberof wl_global
1417  * \since 1.21
1418  */
1419 WL_EXPORT uint32_t
wl_global_get_version(const struct wl_global * global)1420 wl_global_get_version(const struct wl_global *global)
1421 {
1422 	return global->version;
1423 }
1424 
1425 /** Get the display object for the given global
1426  *
1427  * \param global The global object
1428  * \return The display object the global is associated with.
1429  *
1430  * \memberof wl_global
1431  * \since 1.20
1432  */
1433 WL_EXPORT struct wl_display *
wl_global_get_display(const struct wl_global * global)1434 wl_global_get_display(const struct wl_global *global)
1435 {
1436 	return global->display;
1437 }
1438 
1439 WL_EXPORT void *
wl_global_get_user_data(const struct wl_global * global)1440 wl_global_get_user_data(const struct wl_global *global)
1441 {
1442 	return global->data;
1443 }
1444 
1445 /** Set the global's user data
1446  *
1447  * \param global The global object
1448  * \param data The user data pointer
1449  *
1450  * \since 1.17.90
1451  */
1452 WL_EXPORT void
wl_global_set_user_data(struct wl_global * global,void * data)1453 wl_global_set_user_data(struct wl_global *global, void *data)
1454 {
1455 	global->data = data;
1456 }
1457 
1458 /** Get the current serial number
1459  *
1460  * \param display The display object
1461  *
1462  * This function returns the most recent serial number, but does not
1463  * increment it.
1464  *
1465  * \memberof wl_display
1466  */
1467 WL_EXPORT uint32_t
wl_display_get_serial(struct wl_display * display)1468 wl_display_get_serial(struct wl_display *display)
1469 {
1470 	return display->serial;
1471 }
1472 
1473 /** Get the next serial number
1474  *
1475  * \param display The display object
1476  *
1477  * This function increments the display serial number and returns the
1478  * new value.
1479  *
1480  * \memberof wl_display
1481  */
1482 WL_EXPORT uint32_t
wl_display_next_serial(struct wl_display * display)1483 wl_display_next_serial(struct wl_display *display)
1484 {
1485 	display->serial++;
1486 
1487 	return display->serial;
1488 }
1489 
1490 WL_EXPORT struct wl_event_loop *
wl_display_get_event_loop(struct wl_display * display)1491 wl_display_get_event_loop(struct wl_display *display)
1492 {
1493 	return display->loop;
1494 }
1495 
1496 WL_EXPORT void
wl_display_terminate(struct wl_display * display)1497 wl_display_terminate(struct wl_display *display)
1498 {
1499 	int ret;
1500 	uint64_t terminate = 1;
1501 
1502 	display->run = 0;
1503 
1504 	ret = write(display->terminate_efd, &terminate, sizeof(terminate));
1505 	assert (ret >= 0 || errno == EAGAIN);
1506 }
1507 
1508 WL_EXPORT void
wl_display_run(struct wl_display * display)1509 wl_display_run(struct wl_display *display)
1510 {
1511 	display->run = 1;
1512 
1513 	while (display->run) {
1514 		wl_display_flush_clients(display);
1515 		wl_event_loop_dispatch(display->loop, -1);
1516 	}
1517 }
1518 
1519 WL_EXPORT void
wl_display_flush_clients(struct wl_display * display)1520 wl_display_flush_clients(struct wl_display *display)
1521 {
1522 	struct wl_client *client, *next;
1523 	int ret;
1524 
1525 	wl_list_for_each_safe(client, next, &display->client_list, link) {
1526 		ret = wl_connection_flush(client->connection);
1527 		if (ret < 0 && errno == EAGAIN) {
1528 			wl_event_source_fd_update(client->source,
1529 						  WL_EVENT_WRITABLE |
1530 						  WL_EVENT_READABLE);
1531 		} else if (ret < 0) {
1532 			wl_client_destroy(client);
1533 		}
1534 	}
1535 }
1536 
1537 /** Destroy all clients connected to the display
1538  *
1539  * \param display The display object
1540  *
1541  * This function should be called right before wl_display_destroy() to ensure
1542  * all client resources are closed properly. Destroying a client from within
1543  * wl_display_destroy_clients() is safe, but creating one will leak resources
1544  * and raise a warning.
1545  *
1546  * \memberof wl_display
1547  */
1548 WL_EXPORT void
wl_display_destroy_clients(struct wl_display * display)1549 wl_display_destroy_clients(struct wl_display *display)
1550 {
1551 	struct wl_list tmp_client_list, *pos;
1552 	struct wl_client *client;
1553 
1554 	/* Move the whole client list to a temporary head because some new clients
1555 	 * might be added to the original head. */
1556 	wl_list_init(&tmp_client_list);
1557 	wl_list_insert_list(&tmp_client_list, &display->client_list);
1558 	wl_list_init(&display->client_list);
1559 
1560 	/* wl_list_for_each_safe isn't enough here: it fails if the next client is
1561 	 * destroyed by the destroy handler of the current one. */
1562 	while (!wl_list_empty(&tmp_client_list)) {
1563 		pos = tmp_client_list.next;
1564 		client = wl_container_of(pos, client, link);
1565 
1566 		wl_client_destroy(client);
1567 	}
1568 
1569 	if (!wl_list_empty(&display->client_list)) {
1570 		wl_log("wl_display_destroy_clients: cannot destroy all clients because "
1571 			   "new ones were created by destroy callbacks\n");
1572 	}
1573 }
1574 
1575 static int
socket_data(int fd,uint32_t mask,void * data)1576 socket_data(int fd, uint32_t mask, void *data)
1577 {
1578 	struct wl_display *display = data;
1579 	struct sockaddr_un name;
1580 	socklen_t length;
1581 	int client_fd;
1582 
1583 	length = sizeof name;
1584 	client_fd = wl_os_accept_cloexec(fd, (struct sockaddr *) &name,
1585 					 &length);
1586 	if (client_fd < 0)
1587 		wl_log("failed to accept: %s\n", strerror(errno));
1588 	else
1589 		if (!wl_client_create(display, client_fd))
1590 			close(client_fd);
1591 
1592 	return 1;
1593 }
1594 
1595 static int
wl_socket_lock(struct wl_socket * socket)1596 wl_socket_lock(struct wl_socket *socket)
1597 {
1598 	struct stat socket_stat;
1599 
1600 	snprintf(socket->lock_addr, sizeof socket->lock_addr,
1601 		 "%s%s", socket->addr.sun_path, LOCK_SUFFIX);
1602 
1603 	socket->fd_lock = open(socket->lock_addr, O_CREAT | O_CLOEXEC | O_RDWR,
1604 			       (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
1605 
1606 	if (socket->fd_lock < 0) {
1607 		wl_log("unable to open lockfile %s check permissions\n",
1608 			socket->lock_addr);
1609 		goto err;
1610 	}
1611 
1612 	if (flock(socket->fd_lock, LOCK_EX | LOCK_NB) < 0) {
1613 		wl_log("unable to lock lockfile %s, maybe another compositor is running\n",
1614 			socket->lock_addr);
1615 		goto err_fd;
1616 	}
1617 
1618 	if (lstat(socket->addr.sun_path, &socket_stat) < 0 ) {
1619 		if (errno != ENOENT) {
1620 			wl_log("did not manage to stat file %s\n",
1621 				socket->addr.sun_path);
1622 			goto err_fd;
1623 		}
1624 	} else if (socket_stat.st_mode & S_IWUSR ||
1625 		   socket_stat.st_mode & S_IWGRP) {
1626 		unlink(socket->addr.sun_path);
1627 	}
1628 
1629 	return 0;
1630 err_fd:
1631 	close(socket->fd_lock);
1632 	socket->fd_lock = -1;
1633 err:
1634 	*socket->lock_addr = 0;
1635 	/* we did not set this value here, but without lock the
1636 	 * socket won't be created anyway. This prevents the
1637 	 * wl_socket_destroy from unlinking already existing socket
1638 	 * created by other compositor */
1639 	*socket->addr.sun_path = 0;
1640 
1641 	return -1;
1642 }
1643 
1644 static int
wl_socket_init_for_display_name(struct wl_socket * s,const char * name)1645 wl_socket_init_for_display_name(struct wl_socket *s, const char *name)
1646 {
1647 	int name_size;
1648 	const char *runtime_dir = "";
1649 	const char *separator = "";
1650 
1651 	if (name[0] != '/') {
1652 		runtime_dir = getenv("XDG_RUNTIME_DIR");
1653 		if (!runtime_dir || runtime_dir[0] != '/') {
1654 			wl_log("error: XDG_RUNTIME_DIR is invalid or not set in"
1655 			       " the environment\n");
1656 
1657 			/* to prevent programs reporting
1658 			 * "failed to add socket: Success" */
1659 			errno = ENOENT;
1660 			return -1;
1661 		}
1662 		separator = "/";
1663 	}
1664 
1665 	s->addr.sun_family = AF_LOCAL;
1666 	name_size = snprintf(s->addr.sun_path, sizeof s->addr.sun_path,
1667 			     "%s%s%s", runtime_dir, separator, name) + 1;
1668 
1669 	assert(name_size > 0);
1670 	if (name_size > (int)sizeof s->addr.sun_path) {
1671 		wl_log("error: socket path \"%s%s%s\" plus null terminator"
1672 		       " exceeds 108 bytes\n", runtime_dir, separator, name);
1673 		*s->addr.sun_path = 0;
1674 		/* to prevent programs reporting
1675 		 * "failed to add socket: Success" */
1676 		errno = ENAMETOOLONG;
1677 		return -1;
1678 	}
1679 
1680 	s->display_name = (s->addr.sun_path + name_size - 1) - strlen(name);
1681 
1682 	return 0;
1683 }
1684 
1685 static int
_wl_display_add_socket(struct wl_display * display,struct wl_socket * s)1686 _wl_display_add_socket(struct wl_display *display, struct wl_socket *s)
1687 {
1688 	socklen_t size;
1689 
1690 	s->fd = wl_os_socket_cloexec(PF_LOCAL, SOCK_STREAM, 0);
1691 	if (s->fd < 0) {
1692 		return -1;
1693 	}
1694 
1695 	size = offsetof (struct sockaddr_un, sun_path) + strlen(s->addr.sun_path);
1696 	if (bind(s->fd, (struct sockaddr *) &s->addr, size) < 0) {
1697 		wl_log("bind() failed with error: %s\n", strerror(errno));
1698 		return -1;
1699 	}
1700 
1701 	if (listen(s->fd, 128) < 0) {
1702 		wl_log("listen() failed with error: %s\n", strerror(errno));
1703 		return -1;
1704 	}
1705 
1706 	s->source = wl_event_loop_add_fd(display->loop, s->fd,
1707 					 WL_EVENT_READABLE,
1708 					 socket_data, display);
1709 	if (s->source == NULL) {
1710 		return -1;
1711 	}
1712 
1713 	wl_list_insert(display->socket_list.prev, &s->link);
1714 	return 0;
1715 }
1716 
1717 WL_EXPORT const char *
wl_display_add_socket_auto(struct wl_display * display)1718 wl_display_add_socket_auto(struct wl_display *display)
1719 {
1720 	struct wl_socket *s;
1721 	int displayno = 0;
1722 	char display_name[20] = "";
1723 
1724 	/* A reasonable number of maximum default sockets. If
1725 	 * you need more than this, use the explicit add_socket API. */
1726 	const int MAX_DISPLAYNO = 32;
1727 
1728 	s = wl_socket_alloc();
1729 	if (s == NULL)
1730 		return NULL;
1731 
1732 	do {
1733 		snprintf(display_name, sizeof display_name, "wayland-%d", displayno);
1734 		if (wl_socket_init_for_display_name(s, display_name) < 0) {
1735 			wl_socket_destroy(s);
1736 			return NULL;
1737 		}
1738 
1739 		if (wl_socket_lock(s) < 0)
1740 			continue;
1741 
1742 		if (_wl_display_add_socket(display, s) < 0) {
1743 			wl_socket_destroy(s);
1744 			return NULL;
1745 		}
1746 
1747 		return s->display_name;
1748 	} while (displayno++ < MAX_DISPLAYNO);
1749 
1750 	/* Ran out of display names. */
1751 	wl_socket_destroy(s);
1752 	errno = EINVAL;
1753 	return NULL;
1754 }
1755 
1756 /**  Add a socket with an existing fd to Wayland display for the clients to connect.
1757  *
1758  * \param display Wayland display to which the socket should be added.
1759  * \param sock_fd The existing socket file descriptor to be used
1760  * \return 0 if success. -1 if failed.
1761  *
1762  * The existing socket fd must already be created, opened, and locked.
1763  * The fd must be properly set to CLOEXEC and bound to a socket file
1764  * with both bind() and listen() already called.
1765  *
1766  * \memberof wl_display
1767  */
1768 WL_EXPORT int
wl_display_add_socket_fd(struct wl_display * display,int sock_fd)1769 wl_display_add_socket_fd(struct wl_display *display, int sock_fd)
1770 {
1771 	struct wl_socket *s;
1772 	struct stat buf;
1773 
1774 	/* Require a valid fd or fail */
1775 	if (sock_fd < 0 || fstat(sock_fd, &buf) < 0 || !S_ISSOCK(buf.st_mode)) {
1776 		return -1;
1777 	}
1778 
1779 	s = wl_socket_alloc();
1780 	if (s == NULL)
1781 		return -1;
1782 
1783 	s->source = wl_event_loop_add_fd(display->loop, sock_fd,
1784 					 WL_EVENT_READABLE,
1785 					 socket_data, display);
1786 	if (s->source == NULL) {
1787 		wl_log("failed to establish event source\n");
1788 		wl_socket_destroy(s);
1789 		return -1;
1790 	}
1791 
1792 	/* Reuse the existing fd */
1793 	s->fd = sock_fd;
1794 
1795 	wl_list_insert(display->socket_list.prev, &s->link);
1796 
1797 	return 0;
1798 }
1799 
1800 /** Add a socket to Wayland display for the clients to connect.
1801  *
1802  * \param display Wayland display to which the socket should be added.
1803  * \param name Name of the Unix socket.
1804  * \return 0 if success. -1 if failed.
1805  *
1806  * This adds a Unix socket to Wayland display which can be used by clients to
1807  * connect to Wayland display.
1808  *
1809  * If NULL is passed as name, then it would look for WAYLAND_DISPLAY env
1810  * variable for the socket name. If WAYLAND_DISPLAY is not set, then default
1811  * wayland-0 is used.
1812  *
1813  * If the socket name is a relative path, the Unix socket will be created in
1814  * the directory pointed to by environment variable XDG_RUNTIME_DIR. If
1815  * XDG_RUNTIME_DIR is invalid or not set, then this function fails and returns -1.
1816  *
1817  * If the socket name is an absolute path, then it is used as-is for the
1818  * the Unix socket.
1819  *
1820  * The length of the computed socket path must not exceed the maximum length
1821  * of a Unix socket path.
1822  * The function also fails if the user does not have write permission in the
1823  * directory or if the path is already in use.
1824  *
1825  * \memberof wl_display
1826  */
1827 WL_EXPORT int
wl_display_add_socket(struct wl_display * display,const char * name)1828 wl_display_add_socket(struct wl_display *display, const char *name)
1829 {
1830 	struct wl_socket *s;
1831 
1832 	s = wl_socket_alloc();
1833 	if (s == NULL)
1834 		return -1;
1835 
1836 	if (name == NULL)
1837 		name = getenv("WAYLAND_DISPLAY");
1838 	if (name == NULL)
1839 		name = "wayland-0";
1840 
1841 	if (wl_socket_init_for_display_name(s, name) < 0) {
1842 		wl_socket_destroy(s);
1843 		return -1;
1844 	}
1845 
1846 	if (wl_socket_lock(s) < 0) {
1847 		wl_socket_destroy(s);
1848 		return -1;
1849 	}
1850 
1851 	if (_wl_display_add_socket(display, s) < 0) {
1852 		wl_socket_destroy(s);
1853 		return -1;
1854 	}
1855 
1856 	return 0;
1857 }
1858 
1859 WL_EXPORT void
wl_display_add_destroy_listener(struct wl_display * display,struct wl_listener * listener)1860 wl_display_add_destroy_listener(struct wl_display *display,
1861 				struct wl_listener *listener)
1862 {
1863 	wl_priv_signal_add(&display->destroy_signal, listener);
1864 }
1865 
1866 /** Registers a listener for the client connection signal.
1867  *  When a new client object is created, \a listener will be notified, carrying
1868  *  a pointer to the new wl_client object.
1869  *
1870  *  \ref wl_client_create
1871  *  \ref wl_display
1872  *  \ref wl_listener
1873  *
1874  * \param display The display object
1875  * \param listener Signal handler object
1876  */
1877 WL_EXPORT void
wl_display_add_client_created_listener(struct wl_display * display,struct wl_listener * listener)1878 wl_display_add_client_created_listener(struct wl_display *display,
1879 					struct wl_listener *listener)
1880 {
1881 	wl_priv_signal_add(&display->create_client_signal, listener);
1882 }
1883 
1884 WL_EXPORT struct wl_listener *
wl_display_get_destroy_listener(struct wl_display * display,wl_notify_func_t notify)1885 wl_display_get_destroy_listener(struct wl_display *display,
1886 				wl_notify_func_t notify)
1887 {
1888 	return wl_priv_signal_get(&display->destroy_signal, notify);
1889 }
1890 
1891 WL_EXPORT void
wl_resource_set_implementation(struct wl_resource * resource,const void * implementation,void * data,wl_resource_destroy_func_t destroy)1892 wl_resource_set_implementation(struct wl_resource *resource,
1893 			       const void *implementation,
1894 			       void *data, wl_resource_destroy_func_t destroy)
1895 {
1896 	resource->object.implementation = implementation;
1897 	resource->data = data;
1898 	resource->destroy = destroy;
1899 	resource->dispatcher = NULL;
1900 }
1901 
1902 WL_EXPORT void
wl_resource_set_dispatcher(struct wl_resource * resource,wl_dispatcher_func_t dispatcher,const void * implementation,void * data,wl_resource_destroy_func_t destroy)1903 wl_resource_set_dispatcher(struct wl_resource *resource,
1904 			   wl_dispatcher_func_t dispatcher,
1905 			   const void *implementation,
1906 			   void *data, wl_resource_destroy_func_t destroy)
1907 {
1908 	resource->dispatcher = dispatcher;
1909 	resource->object.implementation = implementation;
1910 	resource->data = data;
1911 	resource->destroy = destroy;
1912 }
1913 
1914 /** Create a new resource object
1915  *
1916  * \param client The client owner of the new resource.
1917  * \param interface The interface of the new resource.
1918  * \param version The version of the new resource.
1919  * \param id The id of the new resource. If 0, an available id will be used.
1920  *
1921  * Listeners added with \a wl_client_add_resource_created_listener will be
1922  * notified at the end of this function.
1923  *
1924  * \memberof wl_resource
1925  */
1926 WL_EXPORT struct wl_resource *
wl_resource_create(struct wl_client * client,const struct wl_interface * interface,int version,uint32_t id)1927 wl_resource_create(struct wl_client *client,
1928 		   const struct wl_interface *interface,
1929 		   int version, uint32_t id)
1930 {
1931 	struct wl_resource *resource;
1932 
1933 	resource = zalloc(sizeof *resource);
1934 	if (resource == NULL)
1935 		return NULL;
1936 
1937 	if (id == 0) {
1938 		id = wl_map_insert_new(&client->objects, 0, NULL);
1939 		if (id == 0) {
1940 			free(resource);
1941 			return NULL;
1942 		}
1943 	}
1944 
1945 	resource->object.id = id;
1946 	resource->object.interface = interface;
1947 	resource->object.implementation = NULL;
1948 
1949 	wl_signal_init(&resource->deprecated_destroy_signal);
1950 	wl_priv_signal_init(&resource->destroy_signal);
1951 
1952 	resource->destroy = NULL;
1953 	resource->client = client;
1954 	resource->data = NULL;
1955 	resource->version = version;
1956 	resource->dispatcher = NULL;
1957 
1958 	if (wl_map_insert_at(&client->objects, 0, id, resource) < 0) {
1959 		if (errno == EINVAL) {
1960 			wl_resource_post_error(client->display_resource,
1961 					       WL_DISPLAY_ERROR_INVALID_OBJECT,
1962 					       "invalid new id %d", id);
1963 		}
1964 		free(resource);
1965 		return NULL;
1966 	}
1967 
1968 	wl_priv_signal_emit(&client->resource_created_signal, resource);
1969 	return resource;
1970 }
1971 
1972 WL_EXPORT void
wl_log_set_handler_server(wl_log_func_t handler)1973 wl_log_set_handler_server(wl_log_func_t handler)
1974 {
1975 	wl_log_handler = handler;
1976 }
1977 
1978 /** Adds a new protocol logger.
1979  *
1980  * When a new protocol message arrives or is sent from the server
1981  * all the protocol logger functions will be called, carrying the
1982  * \a user_data pointer, the type of the message (request or
1983  * event) and the actual message.
1984  * The lifetime of the messages passed to the logger function ends
1985  * when they return so the messages cannot be stored and accessed
1986  * later.
1987  *
1988  * \a errno is set on error.
1989  *
1990  * \param display The display object
1991  * \param func The function to call to log a new protocol message
1992  * \param user_data The user data pointer to pass to \a func
1993  *
1994  * \return The protol logger object on success, NULL on failure.
1995  *
1996  * \sa wl_protocol_logger_destroy
1997  *
1998  * \memberof wl_display
1999  */
2000 WL_EXPORT struct wl_protocol_logger *
wl_display_add_protocol_logger(struct wl_display * display,wl_protocol_logger_func_t func,void * user_data)2001 wl_display_add_protocol_logger(struct wl_display *display,
2002 			       wl_protocol_logger_func_t func, void *user_data)
2003 {
2004 	struct wl_protocol_logger *logger;
2005 
2006 	logger = zalloc(sizeof *logger);
2007 	if (!logger)
2008 		return NULL;
2009 
2010 	logger->func = func;
2011 	logger->user_data = user_data;
2012 	wl_list_insert(&display->protocol_loggers, &logger->link);
2013 
2014 	return logger;
2015 }
2016 
2017 /** Destroys a protocol logger.
2018  *
2019  * This function destroys a protocol logger and removes it from the display
2020  * it was added to with \a wl_display_add_protocol_logger.
2021  * The \a logger object becomes invalid after calling this function.
2022  *
2023  * \sa wl_display_add_protocol_logger
2024  *
2025  * \memberof wl_protocol_logger
2026  */
2027 WL_EXPORT void
wl_protocol_logger_destroy(struct wl_protocol_logger * logger)2028 wl_protocol_logger_destroy(struct wl_protocol_logger *logger)
2029 {
2030 	wl_list_remove(&logger->link);
2031 	free(logger);
2032 }
2033 
2034 /** Add support for a wl_shm pixel format
2035  *
2036  * \param display The display object
2037  * \param format The wl_shm pixel format to advertise
2038  * \return A pointer to the wl_shm format that was added to the list
2039  * or NULL if adding it to the list failed.
2040  *
2041  * Add the specified wl_shm format to the list of formats the wl_shm
2042  * object advertises when a client binds to it.  Adding a format to
2043  * the list means that clients will know that the compositor supports
2044  * this format and may use it for creating wl_shm buffers.  The
2045  * compositor must be able to handle the pixel format when a client
2046  * requests it.
2047  *
2048  * The compositor by default supports WL_SHM_FORMAT_ARGB8888 and
2049  * WL_SHM_FORMAT_XRGB8888.
2050  *
2051  * \memberof wl_display
2052  */
2053 WL_EXPORT uint32_t *
wl_display_add_shm_format(struct wl_display * display,uint32_t format)2054 wl_display_add_shm_format(struct wl_display *display, uint32_t format)
2055 {
2056 	uint32_t *p = NULL;
2057 
2058 	p = wl_array_add(&display->additional_shm_formats, sizeof *p);
2059 
2060 	if (p != NULL)
2061 		*p = format;
2062 	return p;
2063 }
2064 
2065 /**
2066  * Get list of additional wl_shm pixel formats
2067  *
2068  * \param display The display object
2069  *
2070  * This function returns the list of addition wl_shm pixel formats
2071  * that the compositor supports.  WL_SHM_FORMAT_ARGB8888 and
2072  * WL_SHM_FORMAT_XRGB8888 are always supported and not included in the
2073  * array, but all formats added through wl_display_add_shm_format()
2074  * will be in the array.
2075  *
2076  * \sa wl_display_add_shm_format()
2077  *
2078  * \private
2079  *
2080  * \memberof wl_display
2081  */
2082 struct wl_array *
wl_display_get_additional_shm_formats(struct wl_display * display)2083 wl_display_get_additional_shm_formats(struct wl_display *display)
2084 {
2085 	return &display->additional_shm_formats;
2086 }
2087 
2088 /** Get the list of currently connected clients
2089  *
2090  * \param display The display object
2091  *
2092  * This function returns a pointer to the list of clients currently
2093  * connected to the display. You can iterate on the list by using
2094  * the \a wl_client_for_each macro.
2095  * The returned value is valid for the lifetime of the \a display.
2096  * You must not modify the returned list, but only access it.
2097  *
2098  * \sa wl_client_for_each()
2099  * \sa wl_client_get_link()
2100  * \sa wl_client_from_link()
2101  *
2102  * \memberof wl_display
2103  */
2104 WL_EXPORT struct wl_list *
wl_display_get_client_list(struct wl_display * display)2105 wl_display_get_client_list(struct wl_display *display)
2106 {
2107 	return &display->client_list;
2108 }
2109 
2110 /** Get the link by which a client is inserted in the client list
2111  *
2112  * \param client The client object
2113  *
2114  * \sa wl_client_for_each()
2115  * \sa wl_display_get_client_list()
2116  * \sa wl_client_from_link()
2117  *
2118  * \memberof wl_client
2119  */
2120 WL_EXPORT struct wl_list *
wl_client_get_link(struct wl_client * client)2121 wl_client_get_link(struct wl_client *client)
2122 {
2123 	return &client->link;
2124 }
2125 
2126 /** Get a wl_client by its link
2127  *
2128  * \param link The link of a wl_client
2129  *
2130  * \sa wl_client_for_each()
2131  * \sa wl_display_get_client_list()
2132  * \sa wl_client_get_link()
2133  *
2134  * \memberof wl_client
2135  */
2136 WL_EXPORT struct wl_client *
wl_client_from_link(struct wl_list * link)2137 wl_client_from_link(struct wl_list *link)
2138 {
2139 	struct wl_client *client;
2140 
2141 	return wl_container_of(link, client, link);
2142 }
2143 
2144 /** Add a listener for the client's resource creation signal
2145  *
2146  * \param client The client object
2147  * \param listener The listener to be added
2148  *
2149  * When a new resource is created for this client the listener
2150  * will be notified, carrying the new resource as the data argument.
2151  *
2152  * \memberof wl_client
2153  */
2154 WL_EXPORT void
wl_client_add_resource_created_listener(struct wl_client * client,struct wl_listener * listener)2155 wl_client_add_resource_created_listener(struct wl_client *client,
2156 					struct wl_listener *listener)
2157 {
2158 	wl_priv_signal_add(&client->resource_created_signal, listener);
2159 }
2160 
2161 struct wl_resource_iterator_context {
2162 	void *user_data;
2163 	wl_client_for_each_resource_iterator_func_t it;
2164 };
2165 
2166 static enum wl_iterator_result
resource_iterator_helper(void * res,void * user_data,uint32_t flags)2167 resource_iterator_helper(void *res, void *user_data, uint32_t flags)
2168 {
2169 	struct wl_resource_iterator_context *context = user_data;
2170 	struct wl_resource *resource = res;
2171 
2172 	return context->it(resource, context->user_data);
2173 }
2174 
2175 /** Iterate over all the resources of a client
2176  *
2177  * \param client The client object
2178  * \param iterator The iterator function
2179  * \param user_data The user data pointer
2180  *
2181  * The function pointed by \a iterator will be called for each
2182  * resource owned by the client. The \a user_data will be passed
2183  * as the second argument of the iterator function.
2184  * If the \a iterator function returns \a WL_ITERATOR_CONTINUE the iteration
2185  * will continue, if it returns \a WL_ITERATOR_STOP it will stop.
2186  *
2187  * Creating and destroying resources while iterating is safe, but new
2188  * resources may or may not be picked up by the iterator.
2189  *
2190  * \sa wl_iterator_result
2191  *
2192  * \memberof wl_client
2193  */
2194 WL_EXPORT void
wl_client_for_each_resource(struct wl_client * client,wl_client_for_each_resource_iterator_func_t iterator,void * user_data)2195 wl_client_for_each_resource(struct wl_client *client,
2196 			    wl_client_for_each_resource_iterator_func_t iterator,
2197 			    void *user_data)
2198 {
2199 	struct wl_resource_iterator_context context = {
2200 		.user_data = user_data,
2201 		.it = iterator,
2202 	};
2203 
2204 	wl_map_for_each(&client->objects, resource_iterator_helper, &context);
2205 }
2206 
2207 static void
handle_noop(struct wl_listener * listener,void * data)2208 handle_noop(struct wl_listener *listener, void *data)
2209 {
2210 	/* Do nothing */
2211 }
2212 
2213 /** Emits this signal, notifying all registered listeners.
2214  *
2215  * A safer version of wl_signal_emit() which can gracefully handle additions
2216  * and deletions of any signal listener from within listener notification
2217  * callbacks.
2218  *
2219  * Listeners deleted during a signal emission and which have not already been
2220  * notified at the time of deletion are not notified by that emission.
2221  *
2222  * Listeners added (or readded) during signal emission are ignored by that
2223  * emission.
2224  *
2225  * Note that repurposing a listener without explicitly removing it and readding
2226  * it is not supported and can lead to unexpected behavior.
2227  *
2228  * \param signal The signal object that will emit the signal
2229  * \param data The data that will be emitted with the signal
2230  *
2231  * \memberof wl_signal
2232  * \since 1.20.90
2233  */
2234 WL_EXPORT void
wl_signal_emit_mutable(struct wl_signal * signal,void * data)2235 wl_signal_emit_mutable(struct wl_signal *signal, void *data)
2236 {
2237 	struct wl_listener cursor;
2238 	struct wl_listener end;
2239 
2240 	/* Add two special markers: one cursor and one end marker. This way, we
2241 	 * know that we've already called listeners on the left of the cursor
2242 	 * and that we don't want to call listeners on the right of the end
2243 	 * marker. The 'it' function can remove any element it wants from the
2244 	 * list without troubles.
2245 	 *
2246 	 * There was a previous attempt that used to steal the whole list of
2247 	 * listeners but then that broke wl_signal_get().
2248 	 *
2249 	 * wl_list_for_each_safe tries to be safe but it fails: it works fine
2250 	 * if the current item is removed, but not if the next one is. */
2251 	wl_list_insert(&signal->listener_list, &cursor.link);
2252 	cursor.notify = handle_noop;
2253 	wl_list_insert(signal->listener_list.prev, &end.link);
2254 	end.notify = handle_noop;
2255 
2256 	while (cursor.link.next != &end.link) {
2257 		struct wl_list *pos = cursor.link.next;
2258 		struct wl_listener *l = wl_container_of(pos, l, link);
2259 
2260 		wl_list_remove(&cursor.link);
2261 		wl_list_insert(pos, &cursor.link);
2262 
2263 		l->notify(l, data);
2264 	}
2265 
2266 	wl_list_remove(&cursor.link);
2267 	wl_list_remove(&end.link);
2268 }
2269 
2270 /** \cond INTERNAL */
2271 
2272 /** Initialize a wl_priv_signal object
2273  *
2274  * wl_priv_signal is a safer implementation of a signal type, with the same API
2275  * as wl_signal, but kept as a private utility of libwayland-server.
2276  * It is safer because listeners can be removed from within wl_priv_signal_emit()
2277  * without corrupting the signal's list.
2278  *
2279  * Before passing a wl_priv_signal object to any other function it must be
2280  * initialized by using wl_priv_signal_init().
2281  *
2282  * \memberof wl_priv_signal
2283  */
2284 void
wl_priv_signal_init(struct wl_priv_signal * signal)2285 wl_priv_signal_init(struct wl_priv_signal *signal)
2286 {
2287 	wl_list_init(&signal->listener_list);
2288 	wl_list_init(&signal->emit_list);
2289 }
2290 
2291 /** Add a listener to a signal
2292  *
2293  * The new listener will be called when calling wl_signal_emit(). If a listener is
2294  * added to the signal while wl_signal_emit() is running it will be called from
2295  * the next time wl_priv_signal_emit() is called.
2296  * To remove a listener call wl_list_remove() on its link member.
2297  *
2298  * \memberof wl_priv_signal
2299  */
2300 void
wl_priv_signal_add(struct wl_priv_signal * signal,struct wl_listener * listener)2301 wl_priv_signal_add(struct wl_priv_signal *signal, struct wl_listener *listener)
2302 {
2303 	wl_list_insert(signal->listener_list.prev, &listener->link);
2304 }
2305 
2306 /** Get a listener added to a signal
2307  *
2308  * Returns the listener added to the given \a signal and with the given
2309  * \a notify function, or NULL if there isn't any.
2310  * Calling this function from within wl_priv_signal_emit() is safe and will
2311  * return the correct value.
2312  *
2313  * \memberof wl_priv_signal
2314  */
2315 struct wl_listener *
wl_priv_signal_get(struct wl_priv_signal * signal,wl_notify_func_t notify)2316 wl_priv_signal_get(struct wl_priv_signal *signal, wl_notify_func_t notify)
2317 {
2318 	struct wl_listener *l;
2319 
2320 	wl_list_for_each(l, &signal->listener_list, link)
2321 		if (l->notify == notify)
2322 			return l;
2323 	wl_list_for_each(l, &signal->emit_list, link)
2324 		if (l->notify == notify)
2325 			return l;
2326 
2327 	return NULL;
2328 }
2329 
2330 /** Emit the signal, calling all the installed listeners
2331  *
2332  * Iterate over all the listeners added to this \a signal and call
2333  * their \a notify function pointer, passing on the given \a data.
2334  * Removing or adding a listener from within wl_priv_signal_emit()
2335  * is safe.
2336  */
2337 void
wl_priv_signal_emit(struct wl_priv_signal * signal,void * data)2338 wl_priv_signal_emit(struct wl_priv_signal *signal, void *data)
2339 {
2340 	struct wl_listener *l;
2341 	struct wl_list *pos;
2342 
2343 	wl_list_insert_list(&signal->emit_list, &signal->listener_list);
2344 	wl_list_init(&signal->listener_list);
2345 
2346 	/* Take every element out of the list and put them in a temporary list.
2347 	 * This way, the 'it' func can remove any element it wants from the list
2348 	 * without troubles, because we always get the first element, not the
2349 	 * one after the current, which may be invalid.
2350 	 * wl_list_for_each_safe tries to be safe but it fails: it works fine
2351 	 * if the current item is removed, but not if the next one is. */
2352 	while (!wl_list_empty(&signal->emit_list)) {
2353 		pos = signal->emit_list.next;
2354 		l = wl_container_of(pos, l, link);
2355 
2356 		wl_list_remove(pos);
2357 		wl_list_insert(&signal->listener_list, pos);
2358 
2359 		l->notify(l, data);
2360 	}
2361 }
2362 
2363 /** Emit the signal for the last time, calling all the installed listeners
2364  *
2365  * Iterate over all the listeners added to this \a signal and call
2366  * their \a notify function pointer, passing on the given \a data.
2367  * Removing or adding a listener from within wl_priv_signal_emit()
2368  * is safe, as is freeing the structure containing the listener.
2369  *
2370  * A large body of external code assumes it's ok to free a destruction
2371  * listener without removing that listener from the list.  Mixing code
2372  * that acts like this and code that doesn't will result in list
2373  * corruption.
2374  *
2375  * We resolve this by removing each item from the list and isolating it
2376  * in another list.  We discard it completely after firing the notifier.
2377  * This should allow interoperability between code that unlinks its
2378  * destruction listeners and code that just frees structures they're in.
2379  *
2380  */
2381 void
wl_priv_signal_final_emit(struct wl_priv_signal * signal,void * data)2382 wl_priv_signal_final_emit(struct wl_priv_signal *signal, void *data)
2383 {
2384 	struct wl_listener *l;
2385 	struct wl_list *pos;
2386 
2387 	/* During a destructor notifier isolate every list item before
2388 	 * notifying.  This renders harmless the long standing misuse
2389 	 * of freeing listeners without removing them, but allows
2390 	 * callers that do choose to remove them to interoperate with
2391 	 * ones that don't. */
2392 	while (!wl_list_empty(&signal->listener_list)) {
2393 		pos = signal->listener_list.next;
2394 		l = wl_container_of(pos, l, link);
2395 
2396 		wl_list_remove(pos);
2397 		wl_list_init(pos);
2398 
2399 		l->notify(l, data);
2400 	}
2401 }
2402 
2403 /** \endcond INTERNAL */
2404 
2405 /** \cond */ /* Deprecated functions below. */
2406 
2407 uint32_t
2408 wl_client_add_resource(struct wl_client *client,
2409 		       struct wl_resource *resource) WL_DEPRECATED;
2410 
2411 WL_EXPORT uint32_t
wl_client_add_resource(struct wl_client * client,struct wl_resource * resource)2412 wl_client_add_resource(struct wl_client *client,
2413 		       struct wl_resource *resource)
2414 {
2415 	if (resource->object.id == 0) {
2416 		resource->object.id =
2417 			wl_map_insert_new(&client->objects,
2418 					  WL_MAP_ENTRY_LEGACY, resource);
2419 		if (resource->object.id == 0)
2420 			return 0;
2421 	} else if (wl_map_insert_at(&client->objects, WL_MAP_ENTRY_LEGACY,
2422 				  resource->object.id, resource) < 0) {
2423 		if (errno == EINVAL) {
2424 			wl_resource_post_error(client->display_resource,
2425 					       WL_DISPLAY_ERROR_INVALID_OBJECT,
2426 					       "invalid new id %d",
2427 					       resource->object.id);
2428 		}
2429 		return 0;
2430 	}
2431 
2432 	resource->client = client;
2433 	wl_signal_init(&resource->deprecated_destroy_signal);
2434 
2435 	return resource->object.id;
2436 }
2437 
2438 struct wl_resource *
2439 wl_client_add_object(struct wl_client *client,
2440 		     const struct wl_interface *interface,
2441 		     const void *implementation,
2442 		     uint32_t id, void *data) WL_DEPRECATED;
2443 
2444 WL_EXPORT struct wl_resource *
wl_client_add_object(struct wl_client * client,const struct wl_interface * interface,const void * implementation,uint32_t id,void * data)2445 wl_client_add_object(struct wl_client *client,
2446 		     const struct wl_interface *interface,
2447 		     const void *implementation, uint32_t id, void *data)
2448 {
2449 	struct wl_resource *resource;
2450 
2451 	resource = wl_resource_create(client, interface, -1, id);
2452 	if (resource == NULL)
2453 		wl_client_post_no_memory(client);
2454 	else
2455 		wl_resource_set_implementation(resource,
2456 					       implementation, data, NULL);
2457 
2458 	return resource;
2459 }
2460 
2461 struct wl_resource *
2462 wl_client_new_object(struct wl_client *client,
2463 		     const struct wl_interface *interface,
2464 		     const void *implementation, void *data) WL_DEPRECATED;
2465 
2466 WL_EXPORT struct wl_resource *
wl_client_new_object(struct wl_client * client,const struct wl_interface * interface,const void * implementation,void * data)2467 wl_client_new_object(struct wl_client *client,
2468 		     const struct wl_interface *interface,
2469 		     const void *implementation, void *data)
2470 {
2471 	struct wl_resource *resource;
2472 
2473 	resource = wl_resource_create(client, interface, -1, 0);
2474 	if (resource == NULL)
2475 		wl_client_post_no_memory(client);
2476 	else
2477 		wl_resource_set_implementation(resource,
2478 					       implementation, data, NULL);
2479 
2480 	return resource;
2481 }
2482 
2483 struct wl_global *
2484 wl_display_add_global(struct wl_display *display,
2485 		      const struct wl_interface *interface,
2486 		      void *data, wl_global_bind_func_t bind) WL_DEPRECATED;
2487 
2488 WL_EXPORT struct wl_global *
wl_display_add_global(struct wl_display * display,const struct wl_interface * interface,void * data,wl_global_bind_func_t bind)2489 wl_display_add_global(struct wl_display *display,
2490 		      const struct wl_interface *interface,
2491 		      void *data, wl_global_bind_func_t bind)
2492 {
2493 	return wl_global_create(display, interface, interface->version, data, bind);
2494 }
2495 
2496 void
2497 wl_display_remove_global(struct wl_display *display,
2498 			 struct wl_global *global) WL_DEPRECATED;
2499 
2500 WL_EXPORT void
wl_display_remove_global(struct wl_display * display,struct wl_global * global)2501 wl_display_remove_global(struct wl_display *display, struct wl_global *global)
2502 {
2503 	wl_global_destroy(global);
2504 }
2505 
2506 /** \endcond */
2507 
2508 /* Functions at the end of this file are deprecated.  Instead of adding new
2509  * code here, add it before the comment above that states:
2510  * Deprecated functions below.
2511  */
2512