wayland-client: fix to check if thread_data is valid before accessing it
[platform/upstream/wayland.git] / src / wayland-client.c
1 /*
2  * Copyright © 2008-2012 Kristian Høgsberg
3  * Copyright © 2010-2012 Intel Corporation
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining
6  * a copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sublicense, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the
14  * next paragraph) shall be included in all copies or substantial
15  * portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24  * SOFTWARE.
25  */
26
27 #define _GNU_SOURCE
28
29 #include "../config.h"
30
31 #include <stdlib.h>
32 #include <stdint.h>
33 #include <stddef.h>
34 #include <stdio.h>
35 #include <stdbool.h>
36 #include <errno.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <sys/socket.h>
40 #include <sys/un.h>
41 #include <ctype.h>
42 #include <assert.h>
43 #include <fcntl.h>
44 #include <poll.h>
45 #include <pthread.h>
46 #include <sys/time.h>
47 #include <limits.h>
48
49 #include "wayland-util.h"
50 #include "wayland-os.h"
51 #include "wayland-client.h"
52 #include "wayland-private.h"
53
54 //#define WL_DEBUG_QUEUE
55
56 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
57 #define WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT 10
58 // END
59
60 /** \cond */
61
62 enum wl_proxy_flag {
63         WL_PROXY_FLAG_ID_DELETED = (1 << 0),
64         WL_PROXY_FLAG_DESTROYED = (1 << 1),
65         WL_PROXY_FLAG_WRAPPER = (1 << 2),
66         WL_PROXY_FLAG_ID_OVERRIDEN = (1 << 31)
67 };
68
69 struct wl_zombie {
70         int event_count;
71         int *fd_count;
72 };
73
74 struct wl_proxy {
75         struct wl_object object;
76         struct wl_display *display;
77         struct wl_event_queue *queue;
78         uint32_t flags;
79         int refcount;
80         void *user_data;
81         wl_dispatcher_func_t dispatcher;
82         uint32_t version;
83         const char * const *tag;
84 };
85
86 struct wl_event_queue {
87         struct wl_list event_list;
88         struct wl_display *display;
89 };
90
91 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
92 /* thread status */
93 typedef enum
94 {
95         WL_THREAD_STATE_INITIAL = 0,
96         WL_THREAD_STATE_PREPARE_READ = 1 << 0,
97         WL_THREAD_STATE_POLL_DONE = 1 << 1,
98         WL_THREAD_STATE_READ_EVENTS_BEGIN = 1 << 2,
99         WL_THREAD_STATE_READ_EVENTS_DONE = 1 << 3,
100         WL_THREAD_STATE_READ_EVENTS_CANCELD = 1 << 4,
101         WL_THREAD_STATE_WAIT_WAKEUP_BEGIN = 1 << 5,
102         WL_THREAD_STATE_WAIT_WAKEUP_DONE = 1 << 6,
103         WL_THREAD_STATE_WAIT_WAKEUP_TIMEOUT = 1 << 7,
104         WL_THREAD_STATE_WAIT_WAKEUP_ERROR = 1 << 8,
105         WL_THREAD_STATE_FORCE_DISPLAY_SYNC_BEGIN = 1 << 9,
106         WL_THREAD_STATE_FORCE_DISPLAY_SYNC_DONE = 1 << 10,
107         WL_THREAD_STATE_FORCE_DISPLAY_SYNC_ERROR = 1 << 11
108 } thread_state;
109 // END
110
111 struct wl_thread_data {
112         struct wl_list link;
113         int reader_count_in_thread;
114         int pid;
115         int tid;
116 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
117         thread_state state;
118         pthread_t thread_id;
119 // END
120         struct wl_display *display;
121 };
122
123 struct wl_display {
124         struct wl_proxy proxy;
125         struct wl_connection *connection;
126
127         /* errno of the last wl_display error */
128         int last_error;
129
130         /* When display gets an error event from some object, it stores
131          * information about it here, so that client can get this
132          * information afterwards */
133         struct {
134                 /* Code of the error. It can be compared to
135                  * the interface's errors enumeration. */
136                 uint32_t code;
137                 /* interface (protocol) in which the error occurred */
138                 const struct wl_interface *interface;
139                 /* id of the proxy that caused the error. There's no warranty
140                  * that the proxy is still valid. It's up to client how it will
141                  * use it */
142                 uint32_t id;
143                 char message[512];
144         } protocol_error;
145         int fd;
146         struct wl_map objects;
147         struct wl_event_queue display_queue;
148         struct wl_event_queue default_queue;
149         pthread_mutex_t mutex;
150
151         int reader_count;
152         uint32_t read_serial;
153         pthread_cond_t reader_cond;
154
155         pthread_key_t thread_data_key;
156         struct wl_list  threads;
157 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
158         uint32_t force_sync_count;
159 // END
160         uint32_t threads_count;
161         /* last errno value */
162         int prev_errno;
163         char *name;
164 };
165
166 /** \endcond */
167
168 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
169 /* leave log about threads information and abort
170    when pthread_cond_timedwait() returns ETIMEDOUT */
171 static void log_threads_reader_info(struct wl_display *display);
172 // END
173
174 /**
175  * This helper function wakes up all threads that are
176  * waiting for display->reader_cond (i. e. when reading is done,
177  * canceled, or an error occurred)
178  *
179  * NOTE: must be called with display->mutex locked
180  */
181 static void
182 display_wakeup_threads(struct wl_display *display)
183 {
184         /* Thread can get sleeping only in read_events(). If we're
185          * waking it up, it means that the read completed or was
186          * canceled, so we must increase the read_serial.
187          * This prevents from indefinite sleeping in read_events().
188          */
189         ++display->read_serial;
190
191         pthread_cond_broadcast(&display->reader_cond);
192 }
193
194 /**
195  * This function is called for local errors (no memory, server hung up)
196  *
197  * \param display
198  * \param error    error value (EINVAL, EFAULT, ...)
199  *
200  * \note this function is called with display mutex locked
201  */
202 static void
203 display_fatal_error(struct wl_display *display, int error)
204 {
205         if (display->last_error)
206                 return;
207
208         if (!error)
209                 error = EFAULT;
210
211         wl_log("[WL_LAST_ERROR_SET][FUNC:%s][LINE:%d] display:%p last_error (%d -> %d)\n", __FUNCTION__, __LINE__, display, display->last_error, error);
212         display->last_error = error;
213
214         wl_log("got fatal error: %d (display %p, last_error=%d)\n", error, display, display->last_error);
215
216         display_wakeup_threads(display);
217 }
218
219 static void
220 display_print_protocol_error_information(struct wl_display *display, int error)
221 {
222         if (error == EINVAL || error == ENOMEM || error == EFAULT || error == EPROTO)
223                 wl_log("error(%d) %s, display:%p, last_error:%d", error, display->protocol_error.message,
224                                 display, display->last_error);
225 }
226
227 /**
228  * This function is called for error events
229  * and indicates that in some object an error occurred.
230  * The difference between this function and display_fatal_error()
231  * is that this one handles errors that will come by wire,
232  * whereas display_fatal_error() is called for local errors.
233  *
234  * \param display
235  * \param code    error code
236  * \param id      id of the object that generated the error
237  * \param intf    protocol interface
238  */
239 static void
240 display_protocol_error(struct wl_display *display, uint32_t code,
241                        uint32_t id, const struct wl_interface *intf)
242 {
243         int err;
244
245         if (display->last_error)
246                 return;
247
248         /* set correct errno */
249         if (intf && wl_interface_equal(intf, &wl_display_interface)) {
250                 switch (code) {
251                 case WL_DISPLAY_ERROR_INVALID_OBJECT:
252                 case WL_DISPLAY_ERROR_INVALID_METHOD:
253                         err = EINVAL;
254                         break;
255                 case WL_DISPLAY_ERROR_NO_MEMORY:
256                         err = ENOMEM;
257                         break;
258                 case WL_DISPLAY_ERROR_IMPLEMENTATION:
259                         err = EPROTO;
260                         break;
261                 default:
262                         err = EFAULT;
263                 }
264         } else {
265                 err = EPROTO;
266         }
267
268         pthread_mutex_lock(&display->mutex);
269
270         wl_log("[WL_LAST_ERROR_SET][FUNC:%s][LINE:%d] display:%p last_error (%d -> %d)\n", __FUNCTION__, __LINE__, display, display->last_error, err);
271         display->last_error = err;
272
273         display->protocol_error.code = code;
274         display->protocol_error.id = id;
275         display->protocol_error.interface = intf;
276
277         wl_log("[WL_PROTOCOL_ERROR] display:%p last_error:%d, errno:%d\n", display, display->last_error, errno);
278         wl_log("... protocol_error.code : %d\n", display->protocol_error.code);
279         wl_log("... protocol_error.id : %d\n", display->protocol_error.id);
280         wl_log("... protocol_error.interface->name : %s\n", intf ? intf->name : NULL);
281         wl_log("... protocol_error.interface->version : %d\n", intf ? intf->version : -1);
282         wl_log("... protocol_error.message : %s\n", display->protocol_error.message);
283
284         /*
285          * here it is not necessary to wake up threads like in
286          * display_fatal_error, because this function is called from
287          * an event handler and that means that read_events() is done
288          * and woke up all threads. Since wl_display_prepare_read()
289          * fails when there are events in the queue, no threads
290          * can sleep in read_events() during dispatching
291          * (and therefore during calling this function), so this is safe.
292          */
293
294         pthread_mutex_unlock(&display->mutex);
295 }
296
297 static void
298 wl_event_queue_init(struct wl_event_queue *queue, struct wl_display *display)
299 {
300         wl_list_init(&queue->event_list);
301         queue->display = display;
302 }
303
304 static void
305 wl_proxy_unref(struct wl_proxy *proxy)
306 {
307         assert(proxy->refcount > 0);
308         if (--proxy->refcount > 0)
309                 return;
310
311         /* If we get here, the client must have explicitly requested
312          * deletion. */
313         assert(proxy->flags & WL_PROXY_FLAG_DESTROYED);
314         free(proxy);
315 }
316
317 static void
318 validate_closure_objects(struct wl_closure *closure)
319 {
320         const char *signature;
321         struct argument_details arg;
322         int i, count;
323         struct wl_proxy *proxy;
324
325         signature = closure->message->signature;
326         count = arg_count_for_signature(signature);
327         for (i = 0; i < count; i++) {
328                 signature = get_next_argument(signature, &arg);
329                 switch (arg.type) {
330                 case 'n':
331                 case 'o':
332                         proxy = (struct wl_proxy *) closure->args[i].o;
333                         if (proxy && proxy->flags & WL_PROXY_FLAG_DESTROYED)
334                                 closure->args[i].o = NULL;
335                         break;
336                 default:
337                         break;
338                 }
339         }
340 }
341
342 /* Destroys a closure which was demarshaled for dispatch; unrefs all the
343  * proxies in its arguments, as well as its own proxy, and destroys the
344  * closure itself. */
345 static void
346 destroy_queued_closure(struct wl_closure *closure)
347 {
348         const char *signature;
349         struct argument_details arg;
350         struct wl_proxy *proxy;
351         int i, count;
352
353         signature = closure->message->signature;
354         count = arg_count_for_signature(signature);
355         for (i = 0; i < count; i++) {
356                 signature = get_next_argument(signature, &arg);
357                 switch (arg.type) {
358                 case 'n':
359                 case 'o':
360                         proxy = (struct wl_proxy *) closure->args[i].o;
361                         if (proxy)
362                                 wl_proxy_unref(proxy);
363                         break;
364                 default:
365                         break;
366                 }
367         }
368
369         wl_proxy_unref(closure->proxy);
370         wl_closure_destroy(closure);
371 }
372
373 static void
374 wl_event_queue_release(struct wl_event_queue *queue)
375 {
376         struct wl_closure *closure;
377
378         while (!wl_list_empty(&queue->event_list)) {
379                 closure = wl_container_of(queue->event_list.next,
380                                           closure, link);
381                 wl_list_remove(&closure->link);
382                 destroy_queued_closure(closure);
383         }
384 }
385
386 /** Destroy an event queue
387  *
388  * \param queue The event queue to be destroyed
389  *
390  * Destroy the given event queue. Any pending event on that queue is
391  * discarded.
392  *
393  * The \ref wl_display object used to create the queue should not be
394  * destroyed until all event queues created with it are destroyed with
395  * this function.
396  *
397  * \memberof wl_event_queue
398  */
399 WL_EXPORT void
400 wl_event_queue_destroy(struct wl_event_queue *queue)
401 {
402         struct wl_display *display = queue->display;
403
404         pthread_mutex_lock(&display->mutex);
405         wl_event_queue_release(queue);
406 #ifdef WL_DEBUG_QUEUE
407         if (debug_client)
408                 wl_dlog("queue(%p) destroyed", queue);
409 #endif
410         free(queue);
411         pthread_mutex_unlock(&display->mutex);
412 }
413
414 /** Create a new event queue for this display
415  *
416  * \param display The display context object
417  * \return A new event queue associated with this display or NULL on
418  * failure.
419  *
420  * \memberof wl_display
421  */
422 WL_EXPORT struct wl_event_queue *
423 wl_display_create_queue(struct wl_display *display)
424 {
425         struct wl_event_queue *queue;
426
427         queue = zalloc(sizeof *queue);
428         if (queue == NULL)
429                 return NULL;
430
431 #ifdef WL_DEBUG_QUEUE
432         if (debug_client)
433                 wl_dlog("display(%p) queue(%p) created", display, queue);
434 #endif
435
436         pthread_mutex_lock(&display->mutex);
437         wl_event_queue_init(queue, display);
438         pthread_mutex_unlock(&display->mutex);
439
440         return queue;
441 }
442
443 static int
444 message_count_fds(const char *signature)
445 {
446         unsigned int count, i, fds = 0;
447         struct argument_details arg;
448
449         count = arg_count_for_signature(signature);
450         for (i = 0; i < count; i++) {
451                 signature = get_next_argument(signature, &arg);
452                 if (arg.type == 'h')
453                         fds++;
454         }
455
456         return fds;
457 }
458
459 static struct wl_zombie *
460 prepare_zombie(struct wl_proxy *proxy)
461 {
462         const struct wl_interface *interface = proxy->object.interface;
463         const struct wl_message *message;
464         int i, count;
465         struct wl_zombie *zombie = NULL;
466
467         /* If we hit an event with an FD, ensure we have a zombie object and
468          * fill the fd_count slot for that event with the number of FDs for
469          * that event. Interfaces with no events containing FDs will not have
470          * zombie objects created. */
471         for (i = 0; i < interface->event_count; i++) {
472                 message = &interface->events[i];
473                 count = message_count_fds(message->signature);
474
475                 if (!count)
476                         continue;
477
478                 if (!zombie) {
479                         zombie = zalloc(sizeof(*zombie) +
480                                         (interface->event_count * sizeof(int)));
481                         if (!zombie)
482                                 return NULL;
483
484                         zombie->event_count = interface->event_count;
485                         zombie->fd_count = (int *) &zombie[1];
486                 }
487
488                 zombie->fd_count[i] = count;
489         }
490
491         return zombie;
492 }
493
494 static enum wl_iterator_result
495 free_zombies(void *element, void *data, uint32_t flags)
496 {
497         if (flags & WL_MAP_ENTRY_ZOMBIE)
498                 free(element);
499
500         return WL_ITERATOR_CONTINUE;
501 }
502
503 static struct wl_proxy *
504 proxy_create(struct wl_proxy *factory, const struct wl_interface *interface,
505              uint32_t version)
506 {
507         struct wl_proxy *proxy;
508         struct wl_display *display = factory->display;
509
510         proxy = zalloc(sizeof *proxy);
511         if (proxy == NULL)
512                 return NULL;
513
514         proxy->object.interface = interface;
515         proxy->display = display;
516         proxy->queue = factory->queue;
517         proxy->refcount = 1;
518         proxy->version = version;
519
520         proxy->object.id = wl_map_insert_new(&display->objects, 0, proxy);
521         if (proxy->object.id == 0) {
522                 free(proxy);
523                 return NULL;
524         }
525
526         return proxy;
527 }
528
529 /** Create a proxy object with a given interface
530  *
531  * \param factory Factory proxy object
532  * \param interface Interface the proxy object should use
533  * \return A newly allocated proxy object or NULL on failure
534  *
535  * This function creates a new proxy object with the supplied interface. The
536  * proxy object will have an id assigned from the client id space. The id
537  * should be created on the compositor side by sending an appropriate request
538  * with \ref wl_proxy_marshal().
539  *
540  * The proxy will inherit the display and event queue of the factory object.
541  *
542  * \note This should not normally be used by non-generated code.
543  *
544  * \sa wl_display, wl_event_queue, wl_proxy_marshal()
545  *
546  * \memberof wl_proxy
547  */
548 WL_EXPORT struct wl_proxy *
549 wl_proxy_create(struct wl_proxy *factory, const struct wl_interface *interface)
550 {
551         struct wl_display *display = factory->display;
552         struct wl_proxy *proxy;
553
554         pthread_mutex_lock(&display->mutex);
555         proxy = proxy_create(factory, interface, factory->version);
556         pthread_mutex_unlock(&display->mutex);
557
558         return proxy;
559 }
560
561 /* The caller should hold the display lock */
562 static struct wl_proxy *
563 wl_proxy_create_for_id(struct wl_proxy *factory,
564                        uint32_t id, const struct wl_interface *interface)
565 {
566         struct wl_proxy *proxy;
567         struct wl_display *display = factory->display;
568
569         proxy = zalloc(sizeof *proxy);
570         if (proxy == NULL)
571                 return NULL;
572
573         proxy->object.interface = interface;
574         proxy->object.id = id;
575         proxy->display = display;
576         proxy->queue = factory->queue;
577         proxy->refcount = 1;
578         proxy->version = factory->version;
579
580         if (wl_map_insert_at(&display->objects, 0, id, proxy) == -1) {
581                 free(proxy);
582                 return NULL;
583         }
584
585         return proxy;
586 }
587
588 static void
589 proxy_destroy(struct wl_proxy *proxy)
590 {
591         if (proxy->flags & WL_PROXY_FLAG_ID_DELETED) {
592                 wl_map_remove(&proxy->display->objects, proxy->object.id);
593         } else if (proxy->object.id < WL_SERVER_ID_START) {
594                 struct wl_zombie *zombie = prepare_zombie(proxy);
595
596                 /* The map now contains the zombie entry, until the delete_id
597                  * event arrives. */
598                 wl_map_insert_at(&proxy->display->objects,
599                                  WL_MAP_ENTRY_ZOMBIE,
600                                  proxy->object.id,
601                                  zombie);
602         } else {
603                 /* Clear the given proxy information from the map
604                  * only if it is not overriden. */
605                 if (!(proxy->flags & WL_PROXY_FLAG_ID_OVERRIDEN))
606                         wl_map_insert_at(&proxy->display->objects, 0,
607                                          proxy->object.id, NULL);
608         }
609
610         proxy->flags |= WL_PROXY_FLAG_DESTROYED;
611
612         wl_proxy_unref(proxy);
613 }
614
615 static void
616 wl_proxy_destroy_caller_locks(struct wl_proxy *proxy)
617 {
618         if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
619                 wl_abort("Tried to destroy wrapper with wl_proxy_destroy()\n");
620
621         proxy_destroy(proxy);
622 }
623
624 /** Destroy a proxy object
625  *
626  * \param proxy The proxy to be destroyed
627  *
628  * \c proxy must not be a proxy wrapper.
629  *
630  * \note This function will abort in response to egregious
631  * errors, and will do so with the display lock held. This means
632  * SIGABRT handlers must not perform any actions that would
633  * attempt to take that lock, or a deadlock would occur.
634  *
635  * \memberof wl_proxy
636  */
637 WL_EXPORT void
638 wl_proxy_destroy(struct wl_proxy *proxy)
639 {
640         struct wl_display *display = proxy->display;
641
642         pthread_mutex_lock(&display->mutex);
643
644         wl_proxy_destroy_caller_locks(proxy);
645
646         pthread_mutex_unlock(&display->mutex);
647 }
648
649 /** Set a proxy's listener
650  *
651  * \param proxy The proxy object
652  * \param implementation The listener to be added to proxy
653  * \param data User data to be associated with the proxy
654  * \return 0 on success or -1 on failure
655  *
656  * Set proxy's listener to \c implementation and its user data to
657  * \c data. If a listener has already been set, this function
658  * fails and nothing is changed.
659  *
660  * \c implementation is a vector of function pointers. For an opcode
661  * \c n, \c implementation[n] should point to the handler of \c n for
662  * the given object.
663  *
664  * \c proxy must not be a proxy wrapper.
665  *
666  * \memberof wl_proxy
667  */
668 WL_EXPORT int
669 wl_proxy_add_listener(struct wl_proxy *proxy,
670                       void (**implementation)(void), void *data)
671 {
672         struct wl_display *display = proxy->display;
673
674         if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
675                 wl_abort("Proxy %p is a wrapper\n", proxy);
676
677         pthread_mutex_lock(&display->mutex);
678         if (proxy->object.implementation || proxy->dispatcher) {
679                 wl_log("proxy %s@%u already has listener\n",
680                        proxy->object.interface->name, proxy->object.id);
681                 pthread_mutex_unlock(&display->mutex);
682                 return -1;
683         }
684
685         proxy->object.implementation = implementation;
686         proxy->user_data = data;
687
688         pthread_mutex_unlock(&display->mutex);
689
690         return 0;
691 }
692
693 /** Get a proxy's listener
694  *
695  * \param proxy The proxy object
696  * \return The address of the proxy's listener or NULL if no listener is set
697  *
698  * Gets the address to the proxy's listener; which is the listener set with
699  * \ref wl_proxy_add_listener.
700  *
701  * This function is useful in clients with multiple listeners on the same
702  * interface to allow the identification of which code to execute.
703  *
704  * \memberof wl_proxy
705  */
706 WL_EXPORT const void *
707 wl_proxy_get_listener(struct wl_proxy *proxy)
708 {
709         struct wl_display *display = proxy->display;
710         const void *listener;
711
712         pthread_mutex_lock(&display->mutex);
713         listener = proxy->object.implementation;
714         pthread_mutex_unlock(&display->mutex);
715
716         return listener;
717 }
718
719 /** Set a proxy's listener (with dispatcher)
720  *
721  * \param proxy The proxy object
722  * \param dispatcher The dispatcher to be used for this proxy
723  * \param implementation The dispatcher-specific listener implementation
724  * \param data User data to be associated with the proxy
725  * \return 0 on success or -1 on failure
726  *
727  * Set proxy's listener to use \c dispatcher_func as its dispatcher and \c
728  * dispatcher_data as its dispatcher-specific implementation and its user data
729  * to \c data. If a listener has already been set, this function
730  * fails and nothing is changed.
731  *
732  * The exact details of dispatcher_data depend on the dispatcher used.  This
733  * function is intended to be used by language bindings, not user code.
734  *
735  * \c proxy must not be a proxy wrapper.
736  *
737  * \memberof wl_proxy
738  */
739 WL_EXPORT int
740 wl_proxy_add_dispatcher(struct wl_proxy *proxy,
741                         wl_dispatcher_func_t dispatcher,
742                         const void *implementation, void *data)
743 {
744         struct wl_display *display = proxy->display;
745
746         if (proxy->flags & WL_PROXY_FLAG_WRAPPER)
747                 wl_abort("Proxy %p is a wrapper\n", proxy);
748
749         pthread_mutex_lock(&display->mutex);
750
751         if (proxy->object.implementation || proxy->dispatcher) {
752                 wl_log("proxy %s@%u already has listener\n",
753                        proxy->object.interface->name, proxy->object.id);
754                 pthread_mutex_unlock(&display->mutex);
755                 return -1;
756         }
757
758         proxy->object.implementation = implementation;
759         proxy->dispatcher = dispatcher;
760         proxy->user_data = data;
761
762         pthread_mutex_unlock(&display->mutex);
763
764         return 0;
765 }
766
767 static struct wl_proxy *
768 create_outgoing_proxy(struct wl_proxy *proxy, const struct wl_message *message,
769                       union wl_argument *args,
770                       const struct wl_interface *interface, uint32_t version)
771 {
772         int i, count;
773         const char *signature;
774         struct argument_details arg;
775         struct wl_proxy *new_proxy = NULL;
776
777         signature = message->signature;
778         count = arg_count_for_signature(signature);
779         for (i = 0; i < count; i++) {
780                 signature = get_next_argument(signature, &arg);
781
782                 switch (arg.type) {
783                 case 'n':
784                         new_proxy = proxy_create(proxy, interface, version);
785                         if (new_proxy == NULL)
786                                 return NULL;
787
788                         args[i].o = &new_proxy->object;
789                         break;
790                 }
791         }
792
793         return new_proxy;
794 }
795
796 /** Prepare a request to be sent to the compositor
797  *
798  * \param proxy The proxy object
799  * \param opcode Opcode of the request to be sent
800  * \param args Extra arguments for the given request
801  * \param interface The interface to use for the new proxy
802  *
803  * This function translates a request given an opcode, an interface and a
804  * wl_argument array to the wire format and writes it to the connection
805  * buffer.
806  *
807  * For new-id arguments, this function will allocate a new wl_proxy
808  * and send the ID to the server.  The new wl_proxy will be returned
809  * on success or NULL on error with errno set accordingly.  The newly
810  * created proxy will inherit their version from their parent.
811  *
812  * \note This is intended to be used by language bindings and not in
813  * non-generated code.
814  *
815  * \sa wl_proxy_marshal()
816  *
817  * \memberof wl_proxy
818  */
819 WL_EXPORT struct wl_proxy *
820 wl_proxy_marshal_array_constructor(struct wl_proxy *proxy,
821                                    uint32_t opcode, union wl_argument *args,
822                                    const struct wl_interface *interface)
823 {
824         return wl_proxy_marshal_array_constructor_versioned(proxy, opcode,
825                                                             args, interface,
826                                                             proxy->version);
827 }
828
829 // TIZEN_ONLY(20190716) : leave log about pending requests from clients if sendmsg() fails due to EAGAIN error
830 /** Print the client_entries of the wl_map
831  * \param map  Pointer to wl_map.
832  */
833 static void
834 print_map_client_enteries(struct wl_map *map)
835 {
836         struct wl_proxy *proxy = NULL;
837         char data[4096] = {'\0'};
838         char *str_ptr = data;
839         int length = sizeof(data), id = 0, count = 0;
840         int *len = &length;
841
842         count = wl_map_client_entries_count(map);
843         if(count <= 0)
844                 return;
845
846         WL_SNPRINTF(str_ptr, len, "Map Client Entries:\n"
847                                 " [Interface Name, ID]\n");
848         for (id = 0; id < count; id++) {
849                 proxy = wl_map_lookup(map, id);
850                 if (proxy && !wl_object_is_zombie(map, id)) {
851                         WL_SNPRINTF(str_ptr, len, "[%-15s, %-3d]\n",
852                                 proxy->object.interface->name, id);
853
854                         /* If the current data to be printed exceeds
855                          * 4096 bytes, print it and start to fill
856                          * from the beginning
857                          */
858                         if(length <= 0) {
859 #ifdef HAVE_DLOG
860                                 wl_dlog("%s", data);
861 #else
862                                 fprintf(stderr, "[%s][%d][Pid: %d] %s",
863                                         __FILE__, __LINE__, (int)getpid(), data);
864 #endif
865                                 length = sizeof(data);
866                                 memset(data, '\0', length);
867                                 str_ptr = data;
868                                 id--;
869                         }
870                 }
871         }
872 #ifdef HAVE_DLOG
873         wl_dlog("\n%s", data);
874 #else
875         fprintf(stderr, "[%s][%d][Pid: %d] \n%s",
876                 __FILE__, __LINE__, (int)getpid(), data);
877 #endif
878 }
879 // TIZEN_ONLY : END
880
881 /** Prepare a request to be sent to the compositor
882  *
883  * \param proxy The proxy object
884  * \param opcode Opcode of the request to be sent
885  * \param args Extra arguments for the given request
886  * \param interface The interface to use for the new proxy
887  * \param version The protocol object version for the new proxy
888  *
889  * Translates the request given by opcode and the extra arguments into the
890  * wire format and write it to the connection buffer.  This version takes an
891  * array of the union type wl_argument.
892  *
893  * For new-id arguments, this function will allocate a new wl_proxy
894  * and send the ID to the server.  The new wl_proxy will be returned
895  * on success or NULL on error with errno set accordingly.  The newly
896  * created proxy will have the version specified.
897  *
898  * \note This is intended to be used by language bindings and not in
899  * non-generated code.
900  *
901  * \sa wl_proxy_marshal()
902  *
903  * \memberof wl_proxy
904  */
905 WL_EXPORT struct wl_proxy *
906 wl_proxy_marshal_array_constructor_versioned(struct wl_proxy *proxy,
907                                              uint32_t opcode,
908                                              union wl_argument *args,
909                                              const struct wl_interface *interface,
910                                              uint32_t version)
911 {
912         return wl_proxy_marshal_array_flags(proxy, opcode, interface, version, 0, args);
913 }
914
915 /** Prepare a request to be sent to the compositor
916  *
917  * \param proxy The proxy object
918  * \param opcode Opcode of the request to be sent
919  * \param interface The interface to use for the new proxy
920  * \param version The protocol object version of the new proxy
921  * \param flags Flags that modify marshalling behaviour
922  * \param ... Extra arguments for the given request
923  * \return A new wl_proxy for the new_id argument or NULL on error
924  *
925  * Translates the request given by opcode and the extra arguments into the
926  * wire format and write it to the connection buffer.
927  *
928  * For new-id arguments, this function will allocate a new wl_proxy
929  * and send the ID to the server.  The new wl_proxy will be returned
930  * on success or NULL on error with errno set accordingly.  The newly
931  * created proxy will have the version specified.
932  *
933  * The flag WL_MARSHAL_FLAG_DESTROY may be passed to ensure the proxy
934  * is destroyed atomically with the marshalling in order to prevent
935  * races that can occur if the display lock is dropped between the
936  * marshal and destroy operations.
937  *
938  * \note This should not normally be used by non-generated code.
939  *
940  * \memberof wl_proxy
941  */
942 WL_EXPORT struct wl_proxy *
943 wl_proxy_marshal_flags(struct wl_proxy *proxy, uint32_t opcode,
944                        const struct wl_interface *interface, uint32_t version,
945                        uint32_t flags, ...)
946 {
947         union wl_argument args[WL_CLOSURE_MAX_ARGS];
948         va_list ap;
949
950         va_start(ap, flags);
951         wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
952                                  args, WL_CLOSURE_MAX_ARGS, ap);
953         va_end(ap);
954
955         return wl_proxy_marshal_array_flags(proxy, opcode, interface, version, flags, args);
956 }
957
958 /** Prepare a request to be sent to the compositor
959  *
960  * \param proxy The proxy object
961  * \param opcode Opcode of the request to be sent
962  * \param interface The interface to use for the new proxy
963  * \param version The protocol object version for the new proxy
964  * \param flags Flags that modify marshalling behaviour
965  * \param args Extra arguments for the given request
966  *
967  * Translates the request given by opcode and the extra arguments into the
968  * wire format and write it to the connection buffer.  This version takes an
969  * array of the union type wl_argument.
970  *
971  * For new-id arguments, this function will allocate a new wl_proxy
972  * and send the ID to the server.  The new wl_proxy will be returned
973  * on success or NULL on error with errno set accordingly.  The newly
974  * created proxy will have the version specified.
975  *
976  * The flag WL_MARSHAL_FLAG_DESTROY may be passed to ensure the proxy
977  * is destroyed atomically with the marshalling in order to prevent
978  * races that can occur if the display lock is dropped between the
979  * marshal and destroy operations.
980  *
981  * \note This is intended to be used by language bindings and not in
982  * non-generated code.
983  *
984  * \sa wl_proxy_marshal_flags()
985  *
986  * \memberof wl_proxy
987  */
988 WL_EXPORT struct wl_proxy *
989 wl_proxy_marshal_array_flags(struct wl_proxy *proxy, uint32_t opcode,
990                              const struct wl_interface *interface, uint32_t version,
991                              uint32_t flags, union wl_argument *args)
992 {
993         struct wl_closure *closure;
994         struct wl_proxy *new_proxy = NULL;
995         const struct wl_message *message;
996         struct wl_display *disp = proxy->display;
997
998         pthread_mutex_lock(&disp->mutex);
999
1000         message = &proxy->object.interface->methods[opcode];
1001         if (interface) {
1002                 new_proxy = create_outgoing_proxy(proxy, message,
1003                                                   args, interface,
1004                                                   version);
1005                 if (new_proxy == NULL)
1006                         goto err_unlock;
1007         }
1008
1009         if (proxy->display->last_error) {
1010                 goto err_unlock;
1011         }
1012
1013         closure = wl_closure_marshal(&proxy->object, opcode, args, message);
1014         if (closure == NULL) {
1015                 // TIZEN_ONLY(20210310) : wayland-client : do not abort when there is an EBADF error on marshalling request
1016                 if (errno == EBADF) {
1017                         wl_log("fail wl_closure_marshal with EBADF");
1018                         if (new_proxy) {
1019                                 new_proxy->flags |= WL_PROXY_FLAG_ID_DELETED;
1020                                 proxy_destroy(new_proxy);
1021                                 new_proxy = NULL;
1022                         }
1023                         goto err_unlock;
1024                 }
1025                 // TIZEN_ONLY : END
1026
1027                 // TIZEN_ONLY(20200306) : wayland-client : do abort when there is an error on marshalling request
1028                 wl_abort("Error marshalling request: %m\n");
1029                 // TIZEN_ONLY : END
1030                 //wl_log("Error marshalling request: %m\n");
1031                 //display_fatal_error(proxy->display, errno);
1032                 //goto err_unlock;
1033         }
1034
1035         if (debug_client)
1036                 wl_closure_print(closure, &proxy->object, true, false, NULL);
1037
1038         if (wl_closure_send(closure, proxy->display->connection)) {
1039                 // TIZEN_ONLY(20170328) : leave log about pending requests from clients if sendmsg() fails due to EAGAIN error
1040                 if (errno == EAGAIN) {
1041                         wl_closure_print(closure, &proxy->object, true, false, NULL);
1042                         wl_print_connection_data(proxy->display->connection, OUT);
1043                         print_map_client_enteries(&(proxy->display->objects));
1044                 }
1045                 // TIZEN_ONLY : END
1046                 wl_abort("Error sending request: %m\n");
1047                 //wl_log("Error sending request: %m\n");
1048                 //display_fatal_error(proxy->display, errno);
1049         }
1050
1051         wl_closure_destroy(closure);
1052
1053  err_unlock:
1054         if (flags & WL_MARSHAL_FLAG_DESTROY)
1055                 wl_proxy_destroy_caller_locks(proxy);
1056
1057         pthread_mutex_unlock(&disp->mutex);
1058
1059         return new_proxy;
1060 }
1061
1062
1063 /** Prepare a request to be sent to the compositor
1064  *
1065  * \param proxy The proxy object
1066  * \param opcode Opcode of the request to be sent
1067  * \param ... Extra arguments for the given request
1068  *
1069  * This function is similar to wl_proxy_marshal_constructor(), except
1070  * it doesn't create proxies for new-id arguments.
1071  *
1072  * \note This should not normally be used by non-generated code.
1073  *
1074  * \sa wl_proxy_create()
1075  *
1076  * \memberof wl_proxy
1077  */
1078 WL_EXPORT void
1079 wl_proxy_marshal(struct wl_proxy *proxy, uint32_t opcode, ...)
1080 {
1081         union wl_argument args[WL_CLOSURE_MAX_ARGS];
1082         va_list ap;
1083
1084         va_start(ap, opcode);
1085         wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
1086                                  args, WL_CLOSURE_MAX_ARGS, ap);
1087         va_end(ap);
1088
1089         wl_proxy_marshal_array_constructor(proxy, opcode, args, NULL);
1090 }
1091
1092 /** Prepare a request to be sent to the compositor
1093  *
1094  * \param proxy The proxy object
1095  * \param opcode Opcode of the request to be sent
1096  * \param interface The interface to use for the new proxy
1097  * \param ... Extra arguments for the given request
1098  * \return A new wl_proxy for the new_id argument or NULL on error
1099  *
1100  * This function translates a request given an opcode, an interface and extra
1101  * arguments to the wire format and writes it to the connection buffer. The
1102  * types of the extra arguments must correspond to the argument types of the
1103  * method associated with the opcode in the interface.
1104  *
1105  * For new-id arguments, this function will allocate a new wl_proxy
1106  * and send the ID to the server.  The new wl_proxy will be returned
1107  * on success or NULL on error with errno set accordingly.  The newly
1108  * created proxy will inherit their version from their parent.
1109  *
1110  * \note This should not normally be used by non-generated code.
1111  *
1112  * \memberof wl_proxy
1113  */
1114 WL_EXPORT struct wl_proxy *
1115 wl_proxy_marshal_constructor(struct wl_proxy *proxy, uint32_t opcode,
1116                              const struct wl_interface *interface, ...)
1117 {
1118         union wl_argument args[WL_CLOSURE_MAX_ARGS];
1119         va_list ap;
1120
1121         va_start(ap, interface);
1122         wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
1123                                  args, WL_CLOSURE_MAX_ARGS, ap);
1124         va_end(ap);
1125
1126         return wl_proxy_marshal_array_constructor(proxy, opcode,
1127                                                   args, interface);
1128 }
1129
1130
1131 /** Prepare a request to be sent to the compositor
1132  *
1133  * \param proxy The proxy object
1134  * \param opcode Opcode of the request to be sent
1135  * \param interface The interface to use for the new proxy
1136  * \param version The protocol object version of the new proxy
1137  * \param ... Extra arguments for the given request
1138  * \return A new wl_proxy for the new_id argument or NULL on error
1139  *
1140  * Translates the request given by opcode and the extra arguments into the
1141  * wire format and write it to the connection buffer.
1142  *
1143  * For new-id arguments, this function will allocate a new wl_proxy
1144  * and send the ID to the server.  The new wl_proxy will be returned
1145  * on success or NULL on error with errno set accordingly.  The newly
1146  * created proxy will have the version specified.
1147  *
1148  * \note This should not normally be used by non-generated code.
1149  *
1150  * \memberof wl_proxy
1151  */
1152 WL_EXPORT struct wl_proxy *
1153 wl_proxy_marshal_constructor_versioned(struct wl_proxy *proxy, uint32_t opcode,
1154                                        const struct wl_interface *interface,
1155                                        uint32_t version, ...)
1156 {
1157         union wl_argument args[WL_CLOSURE_MAX_ARGS];
1158         va_list ap;
1159
1160         va_start(ap, version);
1161         wl_argument_from_va_list(proxy->object.interface->methods[opcode].signature,
1162                                  args, WL_CLOSURE_MAX_ARGS, ap);
1163         va_end(ap);
1164
1165         return wl_proxy_marshal_array_constructor_versioned(proxy, opcode,
1166                                                             args, interface,
1167                                                             version);
1168 }
1169
1170 /** Prepare a request to be sent to the compositor
1171  *
1172  * \param proxy The proxy object
1173  * \param opcode Opcode of the request to be sent
1174  * \param args Extra arguments for the given request
1175  *
1176  * This function is similar to wl_proxy_marshal_array_constructor(), except
1177  * it doesn't create proxies for new-id arguments.
1178  *
1179  * \note This is intended to be used by language bindings and not in
1180  * non-generated code.
1181  *
1182  * \sa wl_proxy_marshal()
1183  *
1184  * \memberof wl_proxy
1185  */
1186 WL_EXPORT void
1187 wl_proxy_marshal_array(struct wl_proxy *proxy, uint32_t opcode,
1188                        union wl_argument *args)
1189 {
1190         wl_proxy_marshal_array_constructor(proxy, opcode, args, NULL);
1191 }
1192
1193 static void
1194 destroy_thread_data(void *data)
1195 {
1196         struct wl_display *display = NULL;
1197         struct wl_thread_data *thread_data = data;
1198
1199         display = thread_data->display;
1200         assert(display);
1201
1202         wl_list_remove(&thread_data->link);
1203         display->threads_count--;
1204         wl_log("Thread removed[%p pid:%d tid: %d] from display:%p, threads_cnt=%d\n",
1205                 thread_data, thread_data->pid, thread_data->tid, display, display->threads_count);
1206
1207         if (thread_data->reader_count_in_thread > 0)
1208         {
1209                 wl_log("######################################################################\n");
1210                 wl_log("The thread's reader count is GREATER than zero. Must do cancellation !\n");
1211                 wl_log("... [PID:%d][TID:%d] reader_count:%d, reader_count_in_thread:%d ...\n",
1212                         thread_data->pid, thread_data->tid, display->reader_count, thread_data->reader_count_in_thread);
1213                 wl_log("######################################################################\n");
1214         }
1215
1216         free(thread_data);
1217 }
1218
1219 static struct wl_thread_data*
1220 get_thread_data(struct wl_display *display)
1221 {
1222         struct wl_thread_data *thread_data;
1223         struct wl_thread_data *th_data, *th_data_next;
1224
1225         int pid = (int)getpid();
1226         int tid = (int)syscall(SYS_gettid);
1227
1228         thread_data = pthread_getspecific(display->thread_data_key);
1229         if (!thread_data) {
1230                 wl_list_for_each_safe(th_data, th_data_next, &display->threads, link) {
1231                         if (th_data && th_data->pid == pid && th_data->tid == tid) {
1232                                 wl_log("[pid:%d tid:%d] Failed to pthread_getspecific. errno(%d, %m)\n", pid, tid, errno);
1233                                 thread_data = th_data;
1234                                 break;
1235                         }
1236                         if (!th_data && !th_data_next)
1237                         {
1238                                 wl_log("[pid:%d, tid:%d] Invalid thread data stored in threads ! errno(%d, %m)\n", pid, tid, errno);
1239                                 break;
1240                         }
1241                 }
1242         }
1243
1244         if (!thread_data) {
1245                 int ret = 0;
1246                 thread_data = zalloc(sizeof *thread_data);
1247                 if (!thread_data)
1248                         return NULL;
1249
1250                 if ((ret = pthread_setspecific(display->thread_data_key, thread_data)) != 0) {
1251                         wl_log("[pid:%d tid:%d] Failed to pthread_setspecific. err = %d\n", pid, tid, ret);
1252                 }
1253
1254                 thread_data->reader_count_in_thread = 0;
1255                 thread_data->pid = pid;
1256                 thread_data->tid = tid;
1257                 thread_data->display = display;
1258 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
1259                 thread_data->state = WL_THREAD_STATE_INITIAL;
1260                 thread_data->thread_id = pthread_self();
1261 // END
1262                 wl_list_insert(&display->threads, &thread_data->link);
1263                 display->threads_count++;
1264                 wl_log("Thread added[%p, pid:%d tid: %d] to display:%p, threads_cnt=%d, errno(%d, %m)\n",
1265                         thread_data, thread_data->pid, thread_data->tid, display, display->threads_count, errno);
1266         }
1267
1268         return thread_data;
1269 }
1270
1271 static void
1272 display_handle_error(void *data,
1273                      struct wl_display *display, void *object,
1274                      uint32_t code, const char *message)
1275 {
1276         struct wl_proxy *proxy = object;
1277         uint32_t object_id;
1278         const struct wl_interface *interface;
1279
1280         if (proxy) {
1281                 wl_log("%s@%u: error %d: %s\n",
1282                        proxy->object.interface->name,
1283                        proxy->object.id,
1284                        code, message);
1285
1286                 object_id = proxy->object.id;
1287                 interface = proxy->object.interface;
1288
1289                 pthread_mutex_lock(&display->mutex);
1290                 if (!display->last_error)
1291                         snprintf(display->protocol_error.message, 512, "%s@%u: error %d: %s\n",
1292                                  proxy->object.interface->name, proxy->object.id, code, message);
1293                 pthread_mutex_unlock(&display->mutex);
1294
1295         } else {
1296                 wl_log("[destroyed object]: error %d: %s\n",
1297                        code, message);
1298
1299                 object_id = 0;
1300                 interface = NULL;
1301
1302                 pthread_mutex_lock(&display->mutex);
1303                 if (!display->last_error)
1304                         snprintf(display->protocol_error.message, 512,
1305                                  "[destroyed object]: error %d: %s\n", code, message);
1306                 pthread_mutex_unlock(&display->mutex);
1307         }
1308
1309         display_protocol_error(display, code, object_id, interface);
1310 }
1311
1312 static void
1313 display_handle_delete_id(void *data, struct wl_display *display, uint32_t id)
1314 {
1315         struct wl_proxy *proxy;
1316
1317         pthread_mutex_lock(&display->mutex);
1318
1319         proxy = wl_map_lookup(&display->objects, id);
1320
1321         if (wl_object_is_zombie(&display->objects, id)) {
1322                 /* For zombie objects, the 'proxy' is actually the zombie
1323                  * event-information structure, which we can free. */
1324                 free(proxy);
1325                 wl_map_remove(&display->objects, id);
1326         } else if (proxy) {
1327                 proxy->flags |= WL_PROXY_FLAG_ID_DELETED;
1328         } else {
1329                 wl_log("error: received delete_id for unknown id (%u)\n", id);
1330         }
1331
1332         pthread_mutex_unlock(&display->mutex);
1333 }
1334
1335 static const struct wl_display_listener display_listener = {
1336         display_handle_error,
1337         display_handle_delete_id
1338 };
1339
1340 static int
1341 connect_to_socket(const char *name)
1342 {
1343         struct sockaddr_un addr;
1344         socklen_t size;
1345         const char *runtime_dir;
1346         int name_size, fd;
1347         bool path_is_absolute;
1348
1349         if (name == NULL)
1350                 name = getenv("WAYLAND_DISPLAY");
1351         if (name == NULL)
1352                 name = "wayland-0";
1353
1354         path_is_absolute = name[0] == '/';
1355
1356         runtime_dir = getenv("XDG_RUNTIME_DIR");
1357         if (((!runtime_dir || runtime_dir[0] != '/') && !path_is_absolute)) {
1358                 wl_log("error: XDG_RUNTIME_DIR is invalid or not set in the environment.\n");
1359                 /* to prevent programs reporting
1360                  * "failed to create display: Success" */
1361                 errno = ENOENT;
1362                 return -1;
1363         }
1364
1365         fd = wl_os_socket_cloexec(PF_LOCAL, SOCK_STREAM, 0);
1366         if (fd < 0)
1367                 return -1;
1368
1369         memset(&addr, 0, sizeof addr);
1370         addr.sun_family = AF_LOCAL;
1371         if (!path_is_absolute) {
1372                 name_size =
1373                         snprintf(addr.sun_path, sizeof addr.sun_path,
1374                                  "%s/%s", runtime_dir, name) + 1;
1375         } else {
1376                 /* absolute path */
1377                 name_size =
1378                         snprintf(addr.sun_path, sizeof addr.sun_path,
1379                                  "%s", name) + 1;
1380         }
1381
1382         assert(name_size > 0);
1383         if (name_size > (int)sizeof addr.sun_path) {
1384                 if (!path_is_absolute) {
1385                         wl_log("error: socket path \"%s/%s\" plus null terminator"
1386                                " exceeds %i bytes\n", runtime_dir, name, (int) sizeof(addr.sun_path));
1387                 } else {
1388                         wl_log("error: socket path \"%s\" plus null terminator"
1389                                " exceeds %i bytes\n", name, (int) sizeof(addr.sun_path));
1390                 }
1391                 close(fd);
1392                 /* to prevent programs reporting
1393                  * "failed to add socket: Success" */
1394                 errno = ENAMETOOLONG;
1395                 return -1;
1396         };
1397
1398         size = offsetof (struct sockaddr_un, sun_path) + name_size;
1399
1400         if (connect(fd, (struct sockaddr *) &addr, size) < 0) {
1401                 // TIZEN_ONLY(20170410): Debug logs to identify the failure cause of wl_display_connect()
1402                 wl_log("connect() failed: fd(%d) errno(%d, %m) socket path(%s)\n", fd, errno, addr.sun_path);
1403                 // END
1404                 close(fd);
1405                 return -1;
1406         }
1407
1408         return fd;
1409 }
1410
1411 /** Connect to Wayland display on an already open fd
1412  *
1413  * \param fd The fd to use for the connection
1414  * \return A \ref wl_display object or \c NULL on failure
1415  *
1416  * The wl_display takes ownership of the fd and will close it when the
1417  * display is destroyed.  The fd will also be closed in case of
1418  * failure.
1419  *
1420  * \memberof wl_display
1421  */
1422 WL_EXPORT struct wl_display *
1423 wl_display_connect_to_fd(int fd)
1424 {
1425         struct wl_display *display;
1426         struct wl_thread_data *thread_data;
1427         const char *debug;
1428
1429         debug = getenv("WAYLAND_DLOG");
1430         if (debug && (strstr(debug, "client") || strstr(debug, "1")))
1431                 debug_dlog = 1;
1432
1433         debug = getenv("WAYLAND_DEBUG");
1434         if (debug && (strstr(debug, "client") || strstr(debug, "1")))
1435                 debug_client = 1;
1436
1437         display = zalloc(sizeof *display);
1438         if (display == NULL) {
1439                 // TIZEN_ONLY(20170410): Debbug logs to identify the failure cause of wl_display_connect()
1440                 wl_log("no memory\n");
1441                 errno = ENOMEM;
1442                 // END
1443                 close(fd);
1444                 return NULL;
1445         }
1446
1447         display->fd = fd;
1448         display->prev_errno = 0;
1449         display->last_error = 0;
1450         display->name = NULL;
1451         wl_map_init(&display->objects, WL_MAP_CLIENT_SIDE);
1452         wl_event_queue_init(&display->default_queue, display);
1453         wl_event_queue_init(&display->display_queue, display);
1454         pthread_mutex_init(&display->mutex, NULL);
1455         pthread_mutex_lock(&display->mutex);
1456         pthread_cond_init(&display->reader_cond, NULL);
1457         display->reader_count = 0;
1458 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
1459         display->force_sync_count = 0;
1460 // END
1461
1462         if (wl_map_insert_at(&display->objects, 0, 0, NULL) == -1)
1463                 goto err_connection;
1464
1465         display->proxy.object.id =
1466                 wl_map_insert_new(&display->objects, 0, display);
1467
1468         if (display->proxy.object.id == 0)
1469                 goto err_connection;
1470
1471         display->proxy.object.interface = &wl_display_interface;
1472         display->proxy.display = display;
1473         display->proxy.object.implementation = (void(**)(void)) &display_listener;
1474         display->proxy.user_data = display;
1475         display->proxy.queue = &display->default_queue;
1476         display->proxy.flags = 0;
1477         display->proxy.refcount = 1;
1478
1479         display->protocol_error.message[0] = '\0';
1480
1481         /* We set this version to 0 for backwards compatibility.
1482          *
1483          * If a client is using old versions of protocol headers,
1484          * it will use unversioned API to create proxies.  Those
1485          * proxies will inherit this 0.
1486          *
1487          * A client could be passing these proxies into library
1488          * code newer than the headers that checks proxy
1489          * versions.  When the proxy version is reported as 0
1490          * the library will know that it can't reliably determine
1491          * the proxy version, and should do whatever fallback is
1492          * required.
1493          *
1494          * This trick forces wl_display to always report 0, but
1495          * since it's a special object that we can't bind
1496          * specific versions of anyway, this should be fine.
1497          */
1498         display->proxy.version = 0;
1499
1500         display->connection = wl_connection_create(display->fd);
1501         if (display->connection == NULL)
1502                 goto err_connection;
1503
1504         display->threads_count = 0;
1505         wl_list_init(&display->threads);
1506         if (pthread_key_create(&display->thread_data_key, destroy_thread_data) < 0)
1507                 goto err_connection;
1508
1509         thread_data = get_thread_data(display);
1510         if (!thread_data)
1511                 goto err_connection;
1512
1513 #ifdef WL_DEBUG_QUEUE
1514         if (debug_client)
1515                 wl_dlog("display(%p) default_queue(%p) display_queue(%p) fd(%d)",
1516                         display, &display->default_queue, &display->display_queue, display->fd);
1517 #endif
1518
1519         pthread_mutex_unlock(&display->mutex);
1520
1521         return display;
1522
1523  err_connection:
1524         // TIZEN_ONLY(20170410): Debug logs to identify the failure cause of wl_display_connect()
1525         wl_log("%s() failed. display(%p), fd(%d), errno(%d, %m)\n", __func__, display, fd, errno);
1526         // END
1527         pthread_mutex_unlock(&display->mutex);
1528         pthread_mutex_destroy(&display->mutex);
1529         pthread_cond_destroy(&display->reader_cond);
1530         wl_map_release(&display->objects);
1531         close(display->fd);
1532         free(display);
1533
1534         return NULL;
1535 }
1536
1537 /** Connect to a Wayland display
1538  *
1539  * \param name Name of the Wayland display to connect to
1540  * \return A \ref wl_display object or \c NULL on failure
1541  *
1542  * Connect to the Wayland display named \c name. If \c name is \c NULL,
1543  * its value will be replaced with the WAYLAND_DISPLAY environment
1544  * variable if it is set, otherwise display "wayland-0" will be used.
1545  *
1546  * If WAYLAND_SOCKET is set, it's interpreted as a file descriptor number
1547  * referring to an already opened socket. In this case, the socket is used
1548  * as-is and \c name is ignored.
1549  *
1550  * If \c name is a relative path, then the socket is opened relative to
1551  * the XDG_RUNTIME_DIR directory.
1552  *
1553  * If \c name is an absolute path, then that path is used as-is for
1554  * the location of the socket at which the Wayland server is listening;
1555  * no qualification inside XDG_RUNTIME_DIR is attempted.
1556  *
1557  * If \c name is \c NULL and the WAYLAND_DISPLAY environment variable
1558  * is set to an absolute pathname, then that pathname is used as-is
1559  * for the socket in the same manner as if \c name held an absolute
1560  * path. Support for absolute paths in \c name and WAYLAND_DISPLAY
1561  * is present since Wayland version 1.15.
1562  *
1563  * \memberof wl_display
1564  */
1565 WL_EXPORT struct wl_display *
1566 wl_display_connect(const char *name)
1567 {
1568         char *connection, *end;
1569         int flags, fd;
1570
1571         connection = getenv("WAYLAND_SOCKET");
1572         if (connection) {
1573                 int prev_errno = errno;
1574                 errno = 0;
1575                 fd = strtol(connection, &end, 10);
1576                 if (errno != 0 || connection == end || *end != '\0')
1577                 {
1578                         wl_log("error: fd(%d), errno(%d, %m)\n", fd, errno);
1579                         return NULL;
1580                 }
1581                 errno = prev_errno;
1582
1583                 if (fd < 0 || fd > INT_MAX - 1)
1584                         return NULL;
1585
1586                 flags = fcntl(fd, F_GETFD);
1587                 if (flags == -1 && errno == EBADF)
1588                         return NULL;
1589                 else if (flags != -1)
1590                         fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
1591                 unsetenv("WAYLAND_SOCKET");
1592         } else {
1593                 fd = connect_to_socket(name);
1594                 if (fd < 0)
1595                         return NULL;
1596         }
1597
1598         return wl_display_connect_to_fd(fd);
1599 }
1600
1601 /** Close a connection to a Wayland display
1602  *
1603  * \param display The display context object
1604  *
1605  * Close the connection to \c display and free all resources associated
1606  * with it.
1607  *
1608  * \memberof wl_display
1609  */
1610 WL_EXPORT void
1611 wl_display_disconnect(struct wl_display *display)
1612 {
1613         struct wl_thread_data *thread_data;
1614
1615         pthread_mutex_lock(&display->mutex);
1616
1617         thread_data = get_thread_data(display);
1618         if (thread_data)
1619                 destroy_thread_data(thread_data);
1620         pthread_key_delete(display->thread_data_key);
1621
1622         wl_connection_destroy(display->connection);
1623         wl_map_for_each(&display->objects, free_zombies, NULL);
1624         wl_map_release(&display->objects);
1625         wl_event_queue_release(&display->default_queue);
1626         wl_event_queue_release(&display->display_queue);
1627         pthread_mutex_unlock(&display->mutex);
1628         pthread_mutex_destroy(&display->mutex);
1629         pthread_cond_destroy(&display->reader_cond);
1630         close(display->fd);
1631
1632 #ifdef WL_DEBUG_QUEUE
1633         if (debug_client)
1634                 wl_dlog("display(%p) disconnected", display);
1635 #endif
1636
1637         if (display->name)
1638                 free(display->name);
1639         free(display);
1640 }
1641
1642 /** Get a display context's file descriptor
1643  *
1644  * \param display The display context object
1645  * \return Display object file descriptor
1646  *
1647  * Return the file descriptor associated with a display so it can be
1648  * integrated into the client's main loop.
1649  *
1650  * \memberof wl_display
1651  */
1652 WL_EXPORT int
1653 wl_display_get_fd(struct wl_display *display)
1654 {
1655         return display->fd;
1656 }
1657
1658 static void
1659 sync_callback(void *data, struct wl_callback *callback, uint32_t serial)
1660 {
1661         int *done = data;
1662
1663         *done = 1;
1664         wl_callback_destroy(callback);
1665 }
1666
1667 static const struct wl_callback_listener sync_listener = {
1668         sync_callback
1669 };
1670
1671 /** Block until all pending request are processed by the server
1672  *
1673  * \param display The display context object
1674  * \param queue The queue on which to run the roundtrip
1675  * \return The number of dispatched events on success or -1 on failure
1676  *
1677  * This function blocks until the server has processed all currently issued
1678  * requests by sending a request to the display server and waiting for a
1679  * reply before returning.
1680  *
1681  * This function uses wl_display_dispatch_queue() internally. It is not allowed
1682  * to call this function while the thread is being prepared for reading events,
1683  * and doing so will cause a dead lock.
1684  *
1685  * \note This function may dispatch other events being received on the given
1686  * queue.
1687  *
1688  * \sa wl_display_roundtrip()
1689  * \memberof wl_display
1690  */
1691 WL_EXPORT int
1692 wl_display_roundtrip_queue(struct wl_display *display, struct wl_event_queue *queue)
1693 {
1694         struct wl_display *display_wrapper;
1695         struct wl_callback *callback;
1696         int done, ret = 0;
1697
1698         done = 0;
1699
1700         display_wrapper = wl_proxy_create_wrapper(display);
1701         if (!display_wrapper)
1702                 return -1;
1703
1704         wl_proxy_set_queue((struct wl_proxy *) display_wrapper, queue);
1705         callback = wl_display_sync(display_wrapper);
1706         wl_proxy_wrapper_destroy(display_wrapper);
1707
1708         if (callback == NULL)
1709                 return -1;
1710
1711         wl_callback_add_listener(callback, &sync_listener, &done);
1712         while (!done && ret >= 0)
1713                 ret = wl_display_dispatch_queue(display, queue);
1714
1715         if (ret == -1 && !done)
1716                 wl_callback_destroy(callback);
1717
1718         return ret;
1719 }
1720
1721 /** Block until all pending request are processed by the server
1722  *
1723  * \param display The display context object
1724  * \return The number of dispatched events on success or -1 on failure
1725  *
1726  * This function blocks until the server has processed all currently issued
1727  * requests by sending a request to the display server and waiting for a reply
1728  * before returning.
1729  *
1730  * This function uses wl_display_dispatch_queue() internally. It is not allowed
1731  * to call this function while the thread is being prepared for reading events,
1732  * and doing so will cause a dead lock.
1733  *
1734  * \note This function may dispatch other events being received on the default
1735  * queue.
1736  *
1737  * \memberof wl_display
1738  */
1739 WL_EXPORT int
1740 wl_display_roundtrip(struct wl_display *display)
1741 {
1742         return wl_display_roundtrip_queue(display, &display->default_queue);
1743 }
1744
1745 static int
1746 create_proxies(struct wl_proxy *sender, struct wl_closure *closure)
1747 {
1748         struct wl_proxy *proxy;
1749         const char *signature;
1750         struct argument_details arg;
1751         uint32_t id;
1752         int i;
1753         int count;
1754
1755         signature = closure->message->signature;
1756         count = arg_count_for_signature(signature);
1757         for (i = 0; i < count; i++) {
1758                 signature = get_next_argument(signature, &arg);
1759                 switch (arg.type) {
1760                 case 'n':
1761                         id = closure->args[i].n;
1762                         if (id == 0) {
1763                                 closure->args[i].o = NULL;
1764                                 break;
1765                         }
1766                         proxy = wl_proxy_create_for_id(sender, id,
1767                                                        closure->message->types[i]);
1768                         if (proxy == NULL)
1769                                 return -1;
1770                         closure->args[i].o = (struct wl_object *)proxy;
1771                         break;
1772                 default:
1773                         break;
1774                 }
1775         }
1776
1777         return 0;
1778 }
1779
1780 static void
1781 increase_closure_args_refcount(struct wl_closure *closure)
1782 {
1783         const char *signature;
1784         struct argument_details arg;
1785         int i, count;
1786         struct wl_proxy *proxy;
1787
1788         signature = closure->message->signature;
1789         count = arg_count_for_signature(signature);
1790         for (i = 0; i < count; i++) {
1791                 signature = get_next_argument(signature, &arg);
1792                 switch (arg.type) {
1793                 case 'n':
1794                 case 'o':
1795                         proxy = (struct wl_proxy *) closure->args[i].o;
1796                         if (proxy)
1797                                 proxy->refcount++;
1798                         break;
1799                 default:
1800                         break;
1801                 }
1802         }
1803
1804         closure->proxy->refcount++;
1805 }
1806
1807 int
1808 wl_display_override_object_id(void *object, const uint32_t id, int side)
1809 {
1810         struct wl_proxy *proxy = (struct wl_proxy *)object;
1811         struct wl_proxy *overriden_proxy;
1812
1813         /* Check if the given object is the pointer of wl_proxy object */
1814         if (!proxy || (sizeof(*proxy) != sizeof(struct wl_proxy))) {
1815                 wl_log("errno:%d\n", errno);
1816                 wl_abort("invalid object data to override (id:%u, errno:%d)\n", id, errno = EINVAL);
1817                 return 0;
1818         }
1819         else if (id < WL_SERVER_ID_START || side != WL_MAP_CLIENT_SIDE) {
1820                 wl_log("errno:%d\n", errno);
1821                 wl_abort("invalid object id to override (id:%u, side:%d, errno:%d)\n", id, side, errno = EINVAL);
1822                 return 0;
1823         }
1824
1825         overriden_proxy = wl_map_lookup(&proxy->display->objects, id);
1826         if (!overriden_proxy) {
1827                 if (errno || proxy->display->last_error)
1828                         wl_log("display:%p, errno:%d, last_error:%d\n", proxy->display, errno, proxy->display->last_error);
1829                 wl_abort("no proxy found with the given object id(%u), errno(%d)\n", id, errno = EINVAL);
1830                 return 0;
1831         }
1832         else if (overriden_proxy != proxy) {
1833                 if (errno || proxy->display->last_error)
1834                         wl_log("display:%p, errno:%d, last_error:%d\n", proxy->display, errno, proxy->display->last_error);
1835                 wl_abort("invalid proxy objects(%p, %p) found (id:%u), errno(%d)\n", overriden_proxy, proxy, id, errno = EINVAL);
1836                 return 0;
1837         }
1838
1839         /* Set overriden flag for the overriden proxy not to set data as NULL later. */
1840         overriden_proxy->flags |= WL_PROXY_FLAG_ID_OVERRIDEN;
1841         overriden_proxy->object.id = 0;
1842
1843         wl_log("proxy(%p) with id(%u) has been overriden\n", overriden_proxy, id);
1844         return 1;
1845 }
1846
1847 static int
1848 queue_event(struct wl_display *display, int len)
1849 {
1850         uint32_t p[2], id;
1851         int opcode, size;
1852         struct wl_proxy *proxy;
1853         struct wl_closure *closure;
1854         const struct wl_message *message;
1855         struct wl_event_queue *queue;
1856         struct timespec tp;
1857         unsigned int time;
1858         int num_zombie_fds;
1859
1860         wl_connection_copy(display->connection, p, sizeof p);
1861         id = p[0];
1862         opcode = p[1] & 0xffff;
1863         size = p[1] >> 16;
1864         if (len < size)
1865                 return 0;
1866
1867         /* If our proxy is gone or a zombie, just eat the event (and any FDs,
1868          * if applicable). */
1869         proxy = wl_map_lookup(&display->objects, id);
1870         if (!proxy || wl_object_is_zombie(&display->objects, id)) {
1871                 struct wl_zombie *zombie = wl_map_lookup(&display->objects, id);
1872                 num_zombie_fds = (zombie && opcode < zombie->event_count) ?
1873                         zombie->fd_count[opcode] : 0;
1874
1875                 if (debug_client) {
1876                         clock_gettime(CLOCK_REALTIME, &tp);
1877                         time = (tp.tv_sec * 1000000L) + (tp.tv_nsec / 1000);
1878
1879                         fprintf(stderr, "[%7u.%03u] discarded [%s]@%d.[event %d]"
1880                                 "(%d fd, %d byte)\n",
1881                                 time / 1000, time % 1000,
1882                                 zombie ? "zombie" : "unknown",
1883                                 id, opcode,
1884                                 num_zombie_fds, size);
1885                 }
1886                 if (num_zombie_fds > 0)
1887                         wl_connection_close_fds_in(display->connection,
1888                                                    num_zombie_fds);
1889
1890                 wl_connection_consume(display->connection, size);
1891                 return size;
1892         }
1893
1894         if (opcode >= proxy->object.interface->event_count) {
1895                 wl_log("interface '%s' has no event %u\n",
1896                        proxy->object.interface->name, opcode);
1897                 return -1;
1898         }
1899
1900         message = &proxy->object.interface->events[opcode];
1901         closure = wl_connection_demarshal(display->connection, size,
1902                                           &display->objects, message);
1903         if (!closure) {
1904                 wl_log("wl_connection_demarshal failed\n");
1905                 return -1;
1906         }
1907
1908         if (create_proxies(proxy, closure) < 0) {
1909                 wl_log("create_proxies failed\n");
1910                 wl_closure_destroy(closure);
1911                 return -1;
1912         }
1913
1914         if (wl_closure_lookup_objects(closure, &display->objects) != 0) {
1915                 wl_log("wl_closure_lookup_objects failed\n");
1916                 wl_closure_destroy(closure);
1917                 return -1;
1918         }
1919
1920         closure->proxy = proxy;
1921         increase_closure_args_refcount(closure);
1922
1923         if (proxy == &display->proxy)
1924                 queue = &display->display_queue;
1925         else
1926                 queue = proxy->queue;
1927
1928 #ifdef WL_DEBUG_QUEUE
1929         if (debug_client) {
1930                 wl_dlog("display_q(%p) default_q(%p) queue(%p) add event", &display->display_queue, &display->default_queue, queue);
1931                 wl_closure_print(closure, &proxy->object, false);
1932         }
1933 #endif
1934
1935         wl_list_insert(queue->event_list.prev, &closure->link);
1936
1937         return size;
1938 }
1939
1940 static uint32_t
1941 id_from_object(union wl_argument *arg)
1942 {
1943         struct wl_proxy *proxy;
1944
1945         if (arg->o) {
1946                 proxy = (struct wl_proxy *)arg->o;
1947                 return proxy->object.id;
1948         }
1949
1950         return 0;
1951 }
1952
1953 static void
1954 dispatch_event(struct wl_display *display, struct wl_event_queue *queue)
1955 {
1956         struct wl_closure *closure;
1957         struct wl_proxy *proxy;
1958         int opcode;
1959         bool proxy_destroyed;
1960
1961         closure = wl_container_of(queue->event_list.next, closure, link);
1962         wl_list_remove(&closure->link);
1963         opcode = closure->opcode;
1964
1965         /* Verify that the receiving object is still valid by checking if has
1966          * been destroyed by the application. */
1967         validate_closure_objects(closure);
1968         proxy = closure->proxy;
1969         proxy_destroyed = !!(proxy->flags & WL_PROXY_FLAG_DESTROYED);
1970         if (proxy_destroyed) {
1971                 if (debug_client)
1972                         wl_closure_print(closure, &proxy->object, false, true, id_from_object);
1973                 destroy_queued_closure(closure);
1974                 return;
1975         }
1976
1977         pthread_mutex_unlock(&display->mutex);
1978
1979         if (proxy->dispatcher) {
1980                 if (debug_client)
1981                         wl_closure_print(closure, &proxy->object, false, false, id_from_object);
1982
1983                 wl_closure_dispatch(closure, proxy->dispatcher,
1984                                     &proxy->object, opcode);
1985         } else if (proxy->object.implementation) {
1986                 if (debug_client)
1987                         wl_closure_print(closure, &proxy->object, false, false, id_from_object);
1988
1989                 wl_closure_invoke(closure, WL_CLOSURE_INVOKE_CLIENT,
1990                                   &proxy->object, opcode, proxy->user_data);
1991         }
1992
1993         pthread_mutex_lock(&display->mutex);
1994
1995         destroy_queued_closure(closure);
1996 }
1997
1998 static int
1999 _check_reader_counts(struct wl_display *display)
2000 {
2001         struct wl_thread_data *thread_data;
2002         struct wl_thread_data *th_data, *th_data_next;
2003
2004         int cnt = 0;
2005         int threads_reader_counts = 0;
2006
2007         thread_data = get_thread_data(display);
2008         assert(thread_data);
2009
2010         wl_log("[check_reader_counts] Number of threads=%d, reader_count=%d\n", display->threads_count, display->reader_count);
2011
2012         wl_list_for_each_safe(th_data, th_data_next, &display->threads, link) {
2013                 wl_log("... thread[%d]:reader_count_in_thread=%d\n", cnt++, th_data->reader_count_in_thread);
2014
2015                 if (th_data->reader_count_in_thread > 0)
2016                         threads_reader_counts++;
2017         }
2018
2019         if (threads_reader_counts < display->reader_count)
2020         {
2021                 wl_log("[check_reader_counts] Abnormal  reader_count !\n");
2022                 wl_log("... reader_count=%d, total reader counts of threads=%d\n", display->reader_count, threads_reader_counts);
2023
2024                 return 1;
2025         }
2026
2027         return 0;
2028 }
2029
2030 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2031 static void
2032 log_threads_reader_info(struct wl_display *display)
2033 {
2034         struct wl_thread_data *thread_data;
2035         struct wl_thread_data *th_data, *th_data_next;
2036         int thread_cnt = 0;
2037
2038         thread_data = get_thread_data(display);
2039         assert(thread_data);
2040
2041         wl_log("[thread info] current pid : %d, tid : %d\n", thread_data->pid, thread_data->tid);
2042         wl_log("[thread info] display->reader_count : %d\n", display->reader_count);
2043
2044         wl_list_for_each_safe(th_data, th_data_next, &display->threads, link) {
2045                 wl_log("[thread info] thread[%d][PID:%d][TID:%d][id:%lu] reader_count_in_thread:%d, state:%d\n",
2046                                 thread_cnt++, th_data->pid, th_data->tid, th_data->thread_id, th_data->reader_count_in_thread, th_data->state);
2047         }
2048 }
2049
2050 static void
2051 force_sync_callback(void *data, struct wl_callback *callback, uint32_t serial)
2052 {
2053         wl_callback_destroy(callback);
2054         wl_log("[force_sync_callback] serial=%d\n", serial);
2055 }
2056
2057 static const struct wl_callback_listener force_sync_listener = {
2058         force_sync_callback
2059 };
2060
2061 static int
2062 force_display_sync(struct wl_display *display)
2063 {
2064         struct wl_callback *callback;
2065         int ret = 0;
2066
2067         pthread_mutex_unlock(&display->mutex);
2068
2069         callback = wl_display_sync(display);
2070
2071         if (!callback)
2072         {
2073                 wl_log("[force_display_sync] failed to get a callback (display:%p)!\n", display);
2074                 return -2;
2075         }
2076
2077         wl_callback_add_listener(callback, &force_sync_listener, NULL);
2078
2079         pthread_mutex_lock(&display->mutex);
2080
2081         if (display->last_error)
2082                 wl_log("[force_display_sync] display:%p, last_error:%d, errno:%d\n", display, display->last_error, errno);
2083
2084         /* We don't make EPIPE a fatal error here, so that we may try to
2085          * read events after the failed flush. When the compositor sends
2086          * an error it will close the socket, and if we make EPIPE fatal
2087          * here we don't get a chance to process the error. */
2088         ret = wl_connection_flush(display->connection);
2089         if (ret < 0 && errno != EAGAIN && errno != EPIPE)
2090                 display_fatal_error(display, errno);
2091
2092         if (ret < 0)
2093                 wl_log("[force_display_sync] error on flushing display (display:%p, ret:%d, errno:%d)\n", display, ret, errno);
2094
2095         return ret;
2096 }
2097 // END
2098
2099 static int
2100 read_events(struct wl_display *display)
2101 {
2102         struct wl_thread_data *thread_data;
2103         int total, rem, size;
2104         uint32_t serial;
2105
2106 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2107         struct timeval now;
2108         struct timespec ts;
2109         int ret = 0, res = 0;
2110 // END
2111         uint32_t _force_sync_count = 0;
2112
2113         thread_data = get_thread_data(display);
2114         assert(thread_data);
2115
2116 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2117         thread_data->state |= WL_THREAD_STATE_POLL_DONE;
2118 // END
2119
2120         thread_data->reader_count_in_thread--;
2121         display->reader_count--;
2122         if (thread_data->reader_count_in_thread || display->reader_count < 0) {
2123                 wl_log("read_events[%p, pid:%d, tid:%d]: check reader count(T:%d, A:%d)", thread_data, thread_data->pid, thread_data->tid,
2124                                                 thread_data->reader_count_in_thread, display->reader_count);
2125
2126 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2127                 /* do wl_abort() when a thread specific reader count > 1 */
2128                 log_threads_reader_info(display);
2129                 wl_abort("=== Invalid reader count (pid:%d, tid:%d, reader_count:%d, reader_count_in_thread:%d) ===\n",
2130                                 thread_data->pid, thread_data->tid, display->reader_count, thread_data->reader_count_in_thread);
2131 // END
2132         }
2133
2134         if (display->reader_count == 0) {
2135 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2136                 thread_data->state |=  WL_THREAD_STATE_READ_EVENTS_BEGIN;
2137 // END
2138                 total = wl_connection_read(display->connection);
2139                 if (total < 0 && errno != EAGAIN && errno != EPIPE)
2140                         wl_log("read failed: total(%d) errno(%d), display(%p)", total, errno, display);
2141                 if (total == -1) {
2142                         if (errno == EAGAIN) {
2143 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2144                                 thread_data->state |= WL_THREAD_STATE_READ_EVENTS_DONE;
2145 // END
2146
2147                                 /* we must wake up threads whenever
2148                                  * the reader_count dropped to 0 */
2149                                 display_wakeup_threads(display);
2150
2151                                 if (thread_data->reader_count_in_thread > 0)
2152                                         display->reader_count++;
2153
2154                                 return 0;
2155                         }
2156
2157                         wl_log("errno(%d)\n", errno);
2158                         display_fatal_error(display, errno);
2159                         return -1;
2160                 } else if (total == 0) {
2161 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2162                         thread_data->state |= WL_THREAD_STATE_READ_EVENTS_DONE;
2163 // END
2164
2165                         /* The compositor has closed the socket. This
2166                          * should be considered an error so we'll fake
2167                          * an errno */
2168                         errno = EPIPE;
2169                         display_fatal_error(display, errno);
2170                         wl_log("pipe error\n");
2171                         return -1;
2172                 }
2173
2174                 for (rem = total; rem >= 8; rem -= size) {
2175                         size = queue_event(display, rem);
2176                         if (size == -1) {
2177 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2178                                 thread_data->state |= WL_THREAD_STATE_READ_EVENTS_DONE;
2179 // END
2180                                 wl_log("queue_event failed\n");
2181                                 display_fatal_error(display, errno);
2182                                 return -1;
2183                         } else if (size == 0) {
2184                                 break;
2185                         }
2186                 }
2187
2188                 display_wakeup_threads(display);
2189 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2190                 thread_data->state |= WL_THREAD_STATE_READ_EVENTS_DONE;
2191 // END
2192         } else {
2193                 serial = display->read_serial;
2194                 while (display->read_serial == serial)
2195 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2196                 {
2197                         gettimeofday(&now, NULL);
2198
2199                         ts.tv_nsec = now.tv_usec * 1000;
2200                         ts.tv_sec = now.tv_sec + WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT;// 10 seconds
2201
2202                         thread_data->state |= WL_THREAD_STATE_WAIT_WAKEUP_BEGIN;
2203
2204                         ret = pthread_cond_timedwait(&display->reader_cond,
2205                                           &display->mutex, &ts);
2206
2207                         thread_data->state |= WL_THREAD_STATE_WAIT_WAKEUP_DONE;
2208
2209                         if (ETIMEDOUT == ret)
2210                         {
2211                                 thread_data->state |= WL_THREAD_STATE_WAIT_WAKEUP_TIMEOUT;
2212                                 wl_log("=== Timeout on pthread_cond_timedwait. Start leaving data (timeout=%d)!===\n", WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT);
2213
2214                                 log_threads_reader_info(display);
2215
2216                                 wl_log("[read events] display->read_serial : %d, serial : %d\n", display->read_serial, serial);
2217                                 wl_log("=== Timeout on pthread_cond_timedwait. End of data leaving !===\n");
2218
2219                                 /* After having waited for two times by calling pthread_cond_timedwait() and
2220                                   * if the last reader (thread) doesn't wake the waiting threads up, it is considered to be an abnormal situation.
2221                                   * Do wl_abort().
2222                                   */
2223                                 if (_force_sync_count > 1 && display->read_serial == serial)
2224                                 {
2225                                         if (_check_reader_counts(display))
2226                                         {
2227                                                 if (!errno)
2228                                                 {
2229                                                         wl_log("[WL_ERRNO_SET][FUNC:%s][LINE:%d] errno (%d -> %d), display:%p\n", __FUNCTION__, __LINE__, errno, display->last_error, display);
2230                                                         errno = display->last_error;
2231                                                 }
2232
2233                                                 wl_abort("Invalid reader count ! Abort !(reader_count=%d, errno=%d, last_error=%d, display:%p)\n", display->reader_count, errno, display->last_error, display);
2234                                         }
2235                                 }
2236
2237                                 thread_data->state |= WL_THREAD_STATE_FORCE_DISPLAY_SYNC_BEGIN;
2238                                 wl_log("=== FORCE_DISPLAY_SYNC BEGIN ===\n");
2239
2240                                 res = force_display_sync(display);
2241                                 display->force_sync_count++;
2242                                 _force_sync_count++;
2243
2244                                 thread_data->state |= WL_THREAD_STATE_FORCE_DISPLAY_SYNC_DONE;
2245                                 wl_log("=== FORCE_DISPLAY_SYNC DONE (res=%d, force_sync_count=%d) ===\n", res, display->force_sync_count);
2246
2247                                 /* return if there is any error on doing display sync and leave display protocol error if exits */
2248                                 if (res < 0)
2249                                 {
2250                                         thread_data->state |= WL_THREAD_STATE_FORCE_DISPLAY_SYNC_ERROR;
2251                                         wl_log("=== FORCE_DISPLAY_SYNC ERROR (res=%d) ===\n", res);
2252
2253                                         if (display->last_error)
2254                                         {
2255                                                 wl_log("[read_events] display:%p, last_error:%d\n", display, display->last_error);
2256                                                 display_print_protocol_error_information(display, display->last_error);
2257
2258                                                 wl_log("[WL_ERRNO_SET][FUNC:%s][LINE:%d] errno (%d -> %d), display:%p\n", __FUNCTION__, __LINE__, errno, display->last_error, display);
2259                                                 errno = display->last_error;
2260                                         }
2261
2262                                         return -1;
2263                                 }
2264                         }
2265                         else if (ret)
2266                         {
2267                                 thread_data->state |= WL_THREAD_STATE_WAIT_WAKEUP_ERROR;
2268                                 wl_log("=== Error waiting pthread_cond_timedwait : continue, errno(%d) ===\n", ret);
2269                         }
2270                 }
2271 // END
2272
2273                 if (display->last_error) {
2274                         errno = display->last_error;
2275                         return -1;
2276                 }
2277         }
2278
2279         /* If reader_count_in_thread > 0, it means that this thread is still polling
2280          * in somewhere. So inclease +1 for it.
2281          */
2282         if (thread_data->reader_count_in_thread > 0)
2283                 display->reader_count++;
2284
2285         return 0;
2286 }
2287
2288 static void
2289 cancel_read(struct wl_display *display)
2290 {
2291         struct wl_thread_data *thread_data;
2292
2293         thread_data = get_thread_data(display);
2294         assert(thread_data);
2295
2296         thread_data->reader_count_in_thread--;
2297         display->reader_count--;
2298         if (thread_data->reader_count_in_thread  || display->reader_count < 0) {
2299                 wl_log("Cancel_events[%p, pid:%d, tid:%d]: check reader count(T:%d, A:%d)\n", thread_data, thread_data->pid, thread_data->tid,
2300                                                 thread_data->reader_count_in_thread, display->reader_count);
2301
2302 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2303                 /* do wl_abort() when a thread specific reader count > 1 */
2304                 log_threads_reader_info(display);
2305                 wl_abort("=== Invalid reader count (pid:%d, tid:%d, reader_count:%d, reader_count_in_thread:%d) ===\n",
2306                                 thread_data->pid, thread_data->tid, display->reader_count, thread_data->reader_count_in_thread);
2307 // END
2308         }
2309
2310         if (display->reader_count == 0)
2311                 display_wakeup_threads(display);
2312
2313         if (thread_data->reader_count_in_thread > 0)
2314                 display->reader_count++;
2315
2316 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2317         thread_data->state |= WL_THREAD_STATE_READ_EVENTS_CANCELD;
2318 // END
2319 }
2320
2321 /** Read events from display file descriptor
2322  *
2323  * \param display The display context object
2324  * \return 0 on success or -1 on error.  In case of error errno will
2325  * be set accordingly
2326  *
2327  * Calling this function will result in data available on the display file
2328  * descriptor being read and read events will be queued on their corresponding
2329  * event queues.
2330  *
2331  * Before calling this function, depending on what thread it is to be called
2332  * from, wl_display_prepare_read_queue() or wl_display_prepare_read() needs to
2333  * be called. See wl_display_prepare_read_queue() for more details.
2334  *
2335  * When being called at a point where other threads have been prepared to read
2336  * (using wl_display_prepare_read_queue() or wl_display_prepare_read()) this
2337  * function will sleep until all other prepared threads have either been
2338  * cancelled (using wl_display_cancel_read()) or them self entered this
2339  * function. The last thread that calls this function will then read and queue
2340  * events on their corresponding event queues, and finally wake up all other
2341  * wl_display_read_events() calls causing them to return.
2342  *
2343  * If a thread cancels a read preparation when all other threads that have
2344  * prepared to read has either called wl_display_cancel_read() or
2345  * wl_display_read_events(), all reader threads will return without having read
2346  * any data.
2347  *
2348  * To dispatch events that may have been queued, call
2349  * wl_display_dispatch_pending() or wl_display_dispatch_queue_pending().
2350  *
2351  * \sa wl_display_prepare_read(), wl_display_cancel_read(),
2352  * wl_display_dispatch_pending(), wl_display_dispatch()
2353  *
2354  * \memberof wl_display
2355  */
2356 WL_EXPORT int
2357 wl_display_read_events(struct wl_display *display)
2358 {
2359         int ret;
2360
2361         pthread_mutex_lock(&display->mutex);
2362
2363         if (display->last_error) {
2364                 cancel_read(display);
2365                 pthread_mutex_unlock(&display->mutex);
2366
2367                 errno = display->last_error;
2368                 return -1;
2369         }
2370
2371         ret = read_events(display);
2372
2373         pthread_mutex_unlock(&display->mutex);
2374
2375         return ret;
2376 }
2377
2378 static int
2379 dispatch_queue(struct wl_display *display, struct wl_event_queue *queue)
2380 {
2381         int count;
2382
2383         if (display->last_error)
2384                 goto err;
2385
2386         count = 0;
2387         while (!wl_list_empty(&display->display_queue.event_list)) {
2388                 dispatch_event(display, &display->display_queue);
2389                 if (display->last_error)
2390                         goto err;
2391                 count++;
2392         }
2393
2394         while (!wl_list_empty(&queue->event_list)) {
2395                 dispatch_event(display, queue);
2396                 if (display->last_error)
2397                         goto err;
2398                 count++;
2399         }
2400
2401         return count;
2402
2403 err:
2404         errno = display->last_error;
2405
2406         return -1;
2407 }
2408
2409 /** Prepare to read events from the display's file descriptor to a queue
2410  *
2411  * \param display The display context object
2412  * \param queue The event queue to use
2413  * \return 0 on success or -1 if event queue was not empty
2414  *
2415  * This function (or wl_display_prepare_read()) must be called before reading
2416  * from the file descriptor using wl_display_read_events(). Calling
2417  * wl_display_prepare_read_queue() announces the calling thread's intention to
2418  * read and ensures that until the thread is ready to read and calls
2419  * wl_display_read_events(), no other thread will read from the file descriptor.
2420  * This only succeeds if the event queue is empty, and if not -1 is returned and
2421  * errno set to EAGAIN.
2422  *
2423  * If a thread successfully calls wl_display_prepare_read_queue(), it must
2424  * either call wl_display_read_events() when it's ready or cancel the read
2425  * intention by calling wl_display_cancel_read().
2426  *
2427  * Use this function before polling on the display fd or integrate the fd into a
2428  * toolkit event loop in a race-free way. A correct usage would be (with most
2429  * error checking left out):
2430  *
2431  * \code
2432  * while (wl_display_prepare_read_queue(display, queue) != 0)
2433  *         wl_display_dispatch_queue_pending(display, queue);
2434  * wl_display_flush(display);
2435  *
2436  * ret = poll(fds, nfds, -1);
2437  * if (has_error(ret))
2438  *         wl_display_cancel_read(display);
2439  * else
2440  *         wl_display_read_events(display);
2441  *
2442  * wl_display_dispatch_queue_pending(display, queue);
2443  * \endcode
2444  *
2445  * Here we call wl_display_prepare_read_queue(), which ensures that between
2446  * returning from that call and eventually calling wl_display_read_events(), no
2447  * other thread will read from the fd and queue events in our queue. If the call
2448  * to wl_display_prepare_read_queue() fails, we dispatch the pending events and
2449  * try again until we're successful.
2450  *
2451  * The wl_display_prepare_read_queue() function doesn't acquire exclusive access
2452  * to the display's fd. It only registers that the thread calling this function
2453  * has intention to read from fd. When all registered readers call
2454  * wl_display_read_events(), only one (at random) eventually reads and queues
2455  * the events and the others are sleeping meanwhile. This way we avoid races and
2456  * still can read from more threads.
2457  *
2458  * \sa wl_display_cancel_read(), wl_display_read_events(),
2459  * wl_display_prepare_read()
2460  *
2461  * \memberof wl_display
2462  */
2463 WL_EXPORT int
2464 wl_display_prepare_read_queue(struct wl_display *display,
2465                               struct wl_event_queue *queue)
2466 {
2467         int ret;
2468
2469         pthread_mutex_lock(&display->mutex);
2470
2471         if (!wl_list_empty(&queue->event_list)) {
2472                 errno = EAGAIN;
2473                 ret = -1;
2474         } else {
2475                 struct wl_thread_data *thread_data;
2476
2477                 thread_data = get_thread_data(display);
2478                 assert(thread_data);
2479
2480                 /* increase +1 per thread */
2481                 if (thread_data->reader_count_in_thread == 0)
2482                         display->reader_count++;
2483                 else {
2484                         wl_log("Prepare_read[%d]: check reader count(T:%d, A:%d)\n", thread_data->tid, thread_data->reader_count_in_thread, display->reader_count);
2485
2486 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2487                         /* do wl_abort() when a thread specific reader count > 1 */
2488                         log_threads_reader_info(display);
2489                         wl_abort("=== Invalid reader count (pid:%d, tid:%d, reader_count:%d, reader_count_in_thread:%d) ===\n",
2490                                         thread_data->pid, thread_data->tid, display->reader_count, thread_data->reader_count_in_thread);
2491 // END
2492                 }
2493
2494 // TIZEN_ONLY(20190716) : wayland-client : force sync of display when threads are waiting for over WL_PTHREAD_COND_TIMEDWAIT_TIMEOUT
2495                 thread_data->state = WL_THREAD_STATE_PREPARE_READ;
2496 // END
2497                 thread_data->reader_count_in_thread++;
2498                 ret = 0;
2499         }
2500
2501         pthread_mutex_unlock(&display->mutex);
2502
2503         return ret;
2504 }
2505
2506 /** Prepare to read events from the display's file descriptor
2507  *
2508  * \param display The display context object
2509  * \return 0 on success or -1 if event queue was not empty
2510  *
2511  * This function does the same thing as wl_display_prepare_read_queue()
2512  * with the default queue passed as the queue.
2513  *
2514  * \sa wl_display_prepare_read_queue
2515  * \memberof wl_display
2516  */
2517 WL_EXPORT int
2518 wl_display_prepare_read(struct wl_display *display)
2519 {
2520         return wl_display_prepare_read_queue(display, &display->default_queue);
2521 }
2522
2523 /** Cancel read intention on display's fd
2524  *
2525  * \param display The display context object
2526  *
2527  * After a thread successfully called wl_display_prepare_read() it must
2528  * either call wl_display_read_events() or wl_display_cancel_read().
2529  * If the threads do not follow this rule it will lead to deadlock.
2530  *
2531  * \sa wl_display_prepare_read(), wl_display_read_events()
2532  *
2533  * \memberof wl_display
2534  */
2535 WL_EXPORT void
2536 wl_display_cancel_read(struct wl_display *display)
2537 {
2538         pthread_mutex_lock(&display->mutex);
2539
2540         cancel_read(display);
2541
2542         pthread_mutex_unlock(&display->mutex);
2543 }
2544
2545 static int
2546 wl_display_poll(struct wl_display *display, short int events)
2547 {
2548         int ret;
2549         struct pollfd pfd[1];
2550
2551         pfd[0].fd = display->fd;
2552         pfd[0].events = events;
2553         do {
2554                 ret = poll(pfd, 1, -1);
2555         } while (ret == -1 && errno == EINTR);
2556
2557         return ret;
2558 }
2559
2560 /** Dispatch events in an event queue
2561  *
2562  * \param display The display context object
2563  * \param queue The event queue to dispatch
2564  * \return The number of dispatched events on success or -1 on failure
2565  *
2566  * Dispatch events on the given event queue.
2567  *
2568  * If the given event queue is empty, this function blocks until there are
2569  * events to be read from the display fd. Events are read and queued on
2570  * the appropriate event queues. Finally, events on given event queue are
2571  * dispatched. On failure -1 is returned and errno set appropriately.
2572  *
2573  * In a multi threaded environment, do not manually wait using poll() (or
2574  * equivalent) before calling this function, as doing so might cause a dead
2575  * lock. If external reliance on poll() (or equivalent) is required, see
2576  * wl_display_prepare_read_queue() of how to do so.
2577  *
2578  * This function is thread safe as long as it dispatches the right queue on the
2579  * right thread. It is also compatible with the multi thread event reading
2580  * preparation API (see wl_display_prepare_read_queue()), and uses the
2581  * equivalent functionality internally. It is not allowed to call this function
2582  * while the thread is being prepared for reading events, and doing so will
2583  * cause a dead lock.
2584  *
2585  * It can be used as a helper function to ease the procedure of reading and
2586  * dispatching events.
2587  *
2588  * \note Since Wayland 1.5 the display has an extra queue
2589  * for its own events (i. e. delete_id). This queue is dispatched always,
2590  * no matter what queue we passed as an argument to this function.
2591  * That means that this function can return non-0 value even when it
2592  * haven't dispatched any event for the given queue.
2593  *
2594  * \sa wl_display_dispatch(), wl_display_dispatch_pending(),
2595  * wl_display_dispatch_queue_pending(), wl_display_prepare_read_queue()
2596  *
2597  * \memberof wl_display
2598  */
2599 WL_EXPORT int
2600 wl_display_dispatch_queue(struct wl_display *display,
2601                           struct wl_event_queue *queue)
2602 {
2603         int ret;
2604
2605         if (wl_display_prepare_read_queue(display, queue) == -1)
2606                 return wl_display_dispatch_queue_pending(display, queue);
2607
2608         while (true) {
2609                 ret = wl_display_flush(display);
2610
2611                 if (ret != -1 || errno != EAGAIN)
2612                         break;
2613
2614                 if (wl_display_poll(display, POLLOUT) == -1) {
2615                         wl_display_cancel_read(display);
2616                         wl_log("wl_display_poll failed (display:%p)\n", display);
2617                         return -1;
2618                 }
2619         }
2620
2621         /* Don't stop if flushing hits an EPIPE; continue so we can read any
2622          * protocol error that may have triggered it. */
2623         if (ret < 0 && errno != EPIPE) {
2624                 display_print_protocol_error_information(display, errno);
2625                 wl_display_cancel_read(display);
2626                 return -1;
2627         }
2628
2629         if (wl_display_poll(display, POLLIN) == -1) {
2630                 wl_log("wl_display_poll failed (display:%p)\n", display);
2631                 wl_display_cancel_read(display);
2632                 return -1;
2633         }
2634
2635         if (wl_display_read_events(display) == -1) {
2636                 wl_log("wl_display_read_events failed (display:%p)\n", display);
2637                 return -1;
2638         }
2639
2640         ret = wl_display_dispatch_queue_pending(display, queue);
2641
2642         if (ret < 0)
2643                 wl_log("wl_display_dispatch_queue_pending failed (display:%p)\n", display);
2644
2645         return ret;
2646 }
2647
2648 /** Dispatch pending events in an event queue
2649  *
2650  * \param display The display context object
2651  * \param queue The event queue to dispatch
2652  * \return The number of dispatched events on success or -1 on failure
2653  *
2654  * Dispatch all incoming events for objects assigned to the given
2655  * event queue. On failure -1 is returned and errno set appropriately.
2656  * If there are no events queued, this function returns immediately.
2657  *
2658  * \memberof wl_display
2659  * \since 1.0.2
2660  */
2661 WL_EXPORT int
2662 wl_display_dispatch_queue_pending(struct wl_display *display,
2663                                   struct wl_event_queue *queue)
2664 {
2665         int ret;
2666
2667         pthread_mutex_lock(&display->mutex);
2668
2669         ret = dispatch_queue(display, queue);
2670
2671         pthread_mutex_unlock(&display->mutex);
2672
2673         return ret;
2674 }
2675
2676 /** Process incoming events
2677  *
2678  * \param display The display context object
2679  * \return The number of dispatched events on success or -1 on failure
2680  *
2681  * Dispatch events on the default event queue.
2682  *
2683  * If the default event queue is empty, this function blocks until there are
2684  * events to be read from the display fd. Events are read and queued on
2685  * the appropriate event queues. Finally, events on the default event queue
2686  * are dispatched. On failure -1 is returned and errno set appropriately.
2687  *
2688  * In a multi threaded environment, do not manually wait using poll() (or
2689  * equivalent) before calling this function, as doing so might cause a dead
2690  * lock. If external reliance on poll() (or equivalent) is required, see
2691  * wl_display_prepare_read_queue() of how to do so.
2692  *
2693  * This function is thread safe as long as it dispatches the right queue on the
2694  * right thread. It is also compatible with the multi thread event reading
2695  * preparation API (see wl_display_prepare_read_queue()), and uses the
2696  * equivalent functionality internally. It is not allowed to call this function
2697  * while the thread is being prepared for reading events, and doing so will
2698  * cause a dead lock.
2699  *
2700  * \note It is not possible to check if there are events on the queue
2701  * or not. For dispatching default queue events without blocking, see \ref
2702  * wl_display_dispatch_pending().
2703  *
2704  * \sa wl_display_dispatch_pending(), wl_display_dispatch_queue(),
2705  * wl_display_read_events()
2706  *
2707  * \memberof wl_display
2708  */
2709 WL_EXPORT int
2710 wl_display_dispatch(struct wl_display *display)
2711 {
2712         return wl_display_dispatch_queue(display, &display->default_queue);
2713 }
2714
2715 /** Dispatch default queue events without reading from the display fd
2716  *
2717  * \param display The display context object
2718  * \return The number of dispatched events or -1 on failure
2719  *
2720  * This function dispatches events on the main event queue. It does not
2721  * attempt to read the display fd and simply returns zero if the main
2722  * queue is empty, i.e., it doesn't block.
2723  *
2724  * \sa wl_display_dispatch(), wl_display_dispatch_queue(),
2725  * wl_display_flush()
2726  *
2727  * \memberof wl_display
2728  */
2729 WL_EXPORT int
2730 wl_display_dispatch_pending(struct wl_display *display)
2731 {
2732         return wl_display_dispatch_queue_pending(display,
2733                                                  &display->default_queue);
2734 }
2735
2736 /** Retrieve the last error that occurred on a display
2737  *
2738  * \param display The display context object
2739  * \return The last error that occurred on \c display or 0 if no error occurred
2740  *
2741  * Return the last error that occurred on the display. This may be an error sent
2742  * by the server or caused by the local client.
2743  *
2744  * \note Errors are \b fatal. If this function returns non-zero the display
2745  * can no longer be used.
2746  *
2747  * \memberof wl_display
2748  */
2749 WL_EXPORT int
2750 wl_display_get_error(struct wl_display *display)
2751 {
2752         int ret;
2753
2754         pthread_mutex_lock(&display->mutex);
2755
2756         ret = display->last_error;
2757
2758         pthread_mutex_unlock(&display->mutex);
2759
2760         return ret;
2761 }
2762
2763 /** Retrieves the information about a protocol error:
2764  *
2765  * \param display    The Wayland display
2766  * \param interface  if not NULL, stores the interface where the error occurred,
2767  *                   or NULL, if unknown.
2768  * \param id         if not NULL, stores the object id that generated
2769  *                   the error, or 0, if the object id is unknown. There's no
2770  *                   guarantee the object is still valid; the client must know
2771  *                   if it deleted the object.
2772  * \return           The error code as defined in the interface specification.
2773  *
2774  * \code
2775  * int err = wl_display_get_error(display);
2776  *
2777  * if (err == EPROTO) {
2778  *        code = wl_display_get_protocol_error(display, &interface, &id);
2779  *        handle_error(code, interface, id);
2780  * }
2781  *
2782  * ...
2783  * \endcode
2784  * \memberof wl_display
2785  */
2786 WL_EXPORT uint32_t
2787 wl_display_get_protocol_error(struct wl_display *display,
2788                               const struct wl_interface **interface,
2789                               uint32_t *id)
2790 {
2791         uint32_t ret;
2792
2793         pthread_mutex_lock(&display->mutex);
2794
2795         ret = display->protocol_error.code;
2796
2797         if (interface)
2798                 *interface = display->protocol_error.interface;
2799         if (id)
2800                 *id = display->protocol_error.id;
2801
2802         pthread_mutex_unlock(&display->mutex);
2803
2804         return ret;
2805 }
2806
2807
2808 /** Send all buffered requests on the display to the server
2809  *
2810  * \param display The display context object
2811  * \return The number of bytes sent on success or -1 on failure
2812  *
2813  * Send all buffered data on the client side to the server. Clients should
2814  * always call this function before blocking on input from the display fd.
2815  * On success, the number of bytes sent to the server is returned. On
2816  * failure, this function returns -1 and errno is set appropriately.
2817  *
2818  * wl_display_flush() never blocks.  It will write as much data as
2819  * possible, but if all data could not be written, errno will be set
2820  * to EAGAIN and -1 returned.  In that case, use poll on the display
2821  * file descriptor to wait for it to become writable again.
2822  *
2823  * \memberof wl_display
2824  */
2825 WL_EXPORT int
2826 wl_display_flush(struct wl_display *display)
2827 {
2828         int ret;
2829
2830         pthread_mutex_lock(&display->mutex);
2831
2832         if (display->last_error) {
2833                 errno = display->last_error;
2834                 ret = -1;
2835         } else {
2836                 /* We don't make EPIPE a fatal error here, so that we may try to
2837                  * read events after the failed flush. When the compositor sends
2838                  * an error it will close the socket, and if we make EPIPE fatal
2839                  * here we don't get a chance to process the error. */
2840                 ret = wl_connection_flush(display->connection);
2841                 if (ret < 0 && errno != EAGAIN && errno != EPIPE)
2842                         display_fatal_error(display, errno);
2843         }
2844
2845         pthread_mutex_unlock(&display->mutex);
2846
2847         return ret;
2848 }
2849
2850 /** Set the user data associated with a proxy
2851  *
2852  * \param proxy The proxy object
2853  * \param user_data The data to be associated with proxy
2854  *
2855  * Set the user data associated with \c proxy. When events for this
2856  * proxy are received, \c user_data will be supplied to its listener.
2857  *
2858  * \memberof wl_proxy
2859  */
2860 WL_EXPORT void
2861 wl_proxy_set_user_data(struct wl_proxy *proxy, void *user_data)
2862 {
2863         struct wl_display *display = proxy->display;
2864
2865         pthread_mutex_lock(&display->mutex);
2866         proxy->user_data = user_data;
2867         pthread_mutex_unlock(&display->mutex);
2868 }
2869
2870 /** Get the user data associated with a proxy
2871  *
2872  * \param proxy The proxy object
2873  * \return The user data associated with proxy
2874  *
2875  * \memberof wl_proxy
2876  */
2877 WL_EXPORT void *
2878 wl_proxy_get_user_data(struct wl_proxy *proxy)
2879 {
2880         struct wl_display *display = proxy->display;
2881         void *user_data;
2882
2883         pthread_mutex_lock(&display->mutex);
2884         user_data = proxy->user_data;
2885         pthread_mutex_unlock(&display->mutex);
2886
2887         return user_data;
2888 }
2889
2890 /** Get the protocol object version of a proxy object
2891  *
2892  * \param proxy The proxy object
2893  * \return The protocol object version of the proxy or 0
2894  *
2895  * Gets the protocol object version of a proxy object, or 0
2896  * if the proxy was created with unversioned API.
2897  *
2898  * A returned value of 0 means that no version information is
2899  * available, so the caller must make safe assumptions about
2900  * the object's real version.
2901  *
2902  * wl_display's version will always return 0.
2903  *
2904  * \memberof wl_proxy
2905  */
2906 WL_EXPORT uint32_t
2907 wl_proxy_get_version(struct wl_proxy *proxy)
2908 {
2909         struct wl_display *display = proxy->display;
2910         uint32_t version;
2911
2912         pthread_mutex_lock(&display->mutex);
2913         version = proxy->version;
2914         pthread_mutex_unlock(&display->mutex);
2915
2916         return version;
2917 }
2918
2919 /** Get the id of a proxy object
2920  *
2921  * \param proxy The proxy object
2922  * \return The id the object associated with the proxy
2923  *
2924  * \memberof wl_proxy
2925  */
2926 WL_EXPORT uint32_t
2927 wl_proxy_get_id(struct wl_proxy *proxy)
2928 {
2929         struct wl_display *display = proxy->display;
2930         uint32_t id;
2931
2932         pthread_mutex_lock(&display->mutex);
2933         id = proxy->object.id;
2934         pthread_mutex_unlock(&display->mutex);
2935
2936         return id;
2937 }
2938
2939 /** Set the tag of a proxy object
2940  *
2941  * A toolkit or application can set a unique tag on a proxy in order to
2942  * identify whether an object is managed by itself or some external part.
2943  *
2944  * To create a tag, the recommended way is to define a statically allocated
2945  * constant char array containing some descriptive string. The tag will be the
2946  * pointer to the non-const pointer to the beginning of the array.
2947  *
2948  * For example, to define and set a tag on a surface managed by a certain
2949  * subsystem:
2950  *
2951  *      static const char *my_tag = "my tag";
2952  *
2953  *      wl_proxy_set_tag((struct wl_proxy *) surface, &my_tag);
2954  *
2955  * Then, in a callback with wl_surface as an argument, in order to check
2956  * whether it's a surface managed by the same subsystem.
2957  *
2958  *      const char * const *tag;
2959  *
2960  *      tag = wl_proxy_get_tag((struct wl_proxy *) surface);
2961  *      if (tag != &my_tag)
2962  *              return;
2963  *
2964  *      ...
2965  *
2966  * For debugging purposes, a tag should be suitable to be included in a debug
2967  * log entry, e.g.
2968  *
2969  *      const char * const *tag;
2970  *
2971  *      tag = wl_proxy_get_tag((struct wl_proxy *) surface);
2972  *      printf("Got a surface with the tag %p (%s)\n",
2973  *             tag, (tag && *tag) ? *tag : "");
2974  *
2975  * \param proxy The proxy object
2976  * \param tag The tag
2977  *
2978  * \memberof wl_proxy
2979  * \since 1.17.90
2980  */
2981 WL_EXPORT void
2982 wl_proxy_set_tag(struct wl_proxy *proxy,
2983                  const char * const *tag)
2984 {
2985         proxy->tag = tag;
2986 }
2987
2988 /** Get the tag of a proxy object
2989  *
2990  * See wl_proxy_set_tag for details.
2991  *
2992  * \param proxy The proxy object
2993  *
2994  * \memberof wl_proxy
2995  * \since 1.17.90
2996  */
2997 WL_EXPORT const char * const *
2998 wl_proxy_get_tag(struct wl_proxy *proxy)
2999 {
3000         return proxy->tag;
3001 }
3002
3003 /** Get the interface name (class) of a proxy object
3004  *
3005  * \param proxy The proxy object
3006  * \return The interface name of the object associated with the proxy
3007  *
3008  * \memberof wl_proxy
3009  */
3010 WL_EXPORT const char *
3011 wl_proxy_get_class(struct wl_proxy *proxy)
3012 {
3013         struct wl_display *display = proxy->display;
3014         const char *name;
3015
3016         pthread_mutex_lock(&display->mutex);
3017         name = proxy->object.interface->name;
3018         pthread_mutex_unlock(&display->mutex);
3019
3020         return name;
3021 }
3022
3023 /** Assign a proxy to an event queue
3024  *
3025  * \param proxy The proxy object
3026  * \param queue The event queue that will handle this proxy or NULL
3027  *
3028  * Assign proxy to event queue. Events coming from \c proxy will be
3029  * queued in \c queue from now. If queue is NULL, then the display's
3030  * default queue is set to the proxy.
3031  *
3032  * In order to guarantee proper handing of all events which were queued
3033  * before the queue change takes effect, it is required to dispatch the
3034  * proxy's old event queue after setting a new event queue.
3035  *
3036  * This is particularly important for multi-threaded setups, where it is
3037  * possible for events to be queued to the proxy's old queue from a
3038  * different thread during the invocation of this function.
3039  *
3040  * To ensure that all events for a newly created proxy are dispatched
3041  * on a particular queue, it is necessary to use a proxy wrapper if
3042  * events are read and dispatched on more than one thread. See
3043  * wl_proxy_create_wrapper() for more details.
3044  *
3045  * \note By default, the queue set in proxy is the one inherited from parent.
3046  *
3047  * \sa wl_display_dispatch_queue()
3048  *
3049  * \memberof wl_proxy
3050  */
3051 WL_EXPORT void
3052 wl_proxy_set_queue(struct wl_proxy *proxy, struct wl_event_queue *queue)
3053 {
3054         struct wl_display *display = proxy->display;
3055
3056         pthread_mutex_lock(&display->mutex);
3057         if (queue) {
3058                 assert(proxy->display == queue->display);
3059                 proxy->queue = queue;
3060         } else {
3061                 proxy->queue = &proxy->display->default_queue;
3062         }
3063         pthread_mutex_unlock(&display->mutex);
3064 }
3065
3066 /** Create a proxy wrapper for making queue assignments thread-safe
3067  *
3068  * \param proxy The proxy object to be wrapped
3069  * \return A proxy wrapper for the given proxy or NULL on failure
3070  *
3071  * A proxy wrapper is type of 'struct wl_proxy' instance that can be used when
3072  * sending requests instead of using the original proxy. A proxy wrapper does
3073  * not have an implementation or dispatcher, and events received on the
3074  * object is still emitted on the original proxy. Trying to set an
3075  * implementation or dispatcher will have no effect but result in a warning
3076  * being logged.
3077  *
3078  * Setting the proxy queue of the proxy wrapper will make new objects created
3079  * using the proxy wrapper use the set proxy queue.
3080  * Even though there is no implementation nor dispatcher, the proxy queue can
3081  * be changed. This will affect the default queue of new objects created by
3082  * requests sent via the proxy wrapper.
3083  *
3084  * A proxy wrapper can only be destroyed using wl_proxy_wrapper_destroy().
3085  *
3086  * A proxy wrapper must be destroyed before the proxy it was created from.
3087  *
3088  * If a user reads and dispatches events on more than one thread, it is
3089  * necessary to use a proxy wrapper when sending requests on objects when the
3090  * intention is that a newly created proxy is to use a proxy queue different
3091  * from the proxy the request was sent on, as creating the new proxy and then
3092  * setting the queue is not thread safe.
3093  *
3094  * For example, a module that runs using its own proxy queue that needs to
3095  * do display roundtrip must wrap the wl_display proxy object before sending
3096  * the wl_display.sync request. For example:
3097  *
3098  * \code
3099  *
3100  *   struct wl_event_queue *queue = ...;
3101  *   struct wl_display *wrapped_display;
3102  *   struct wl_callback *callback;
3103  *
3104  *   wrapped_display = wl_proxy_create_wrapper(display);
3105  *   wl_proxy_set_queue((struct wl_proxy *) wrapped_display, queue);
3106  *   callback = wl_display_sync(wrapped_display);
3107  *   wl_proxy_wrapper_destroy(wrapped_display);
3108  *   wl_callback_add_listener(callback, ...);
3109  *
3110  * \endcode
3111  *
3112  * \memberof wl_proxy
3113  */
3114 WL_EXPORT void *
3115 wl_proxy_create_wrapper(void *proxy)
3116 {
3117         struct wl_proxy *wrapped_proxy = proxy;
3118         struct wl_proxy *wrapper;
3119
3120         wrapper = zalloc(sizeof *wrapper);
3121         if (!wrapper)
3122                 return NULL;
3123
3124         pthread_mutex_lock(&wrapped_proxy->display->mutex);
3125
3126         wrapper->object.interface = wrapped_proxy->object.interface;
3127         wrapper->object.id = wrapped_proxy->object.id;
3128         wrapper->version = wrapped_proxy->version;
3129         wrapper->display = wrapped_proxy->display;
3130         wrapper->queue = wrapped_proxy->queue;
3131         wrapper->flags = WL_PROXY_FLAG_WRAPPER;
3132         wrapper->refcount = 1;
3133
3134         pthread_mutex_unlock(&wrapped_proxy->display->mutex);
3135
3136         return wrapper;
3137 }
3138
3139 /** Destroy a proxy wrapper
3140  * \param proxy_wrapper The proxy wrapper to be destroyed
3141  *
3142  * \memberof wl_proxy
3143  */
3144 WL_EXPORT void
3145 wl_proxy_wrapper_destroy(void *proxy_wrapper)
3146 {
3147         struct wl_proxy *wrapper = proxy_wrapper;
3148         struct wl_display *display = wrapper->display;
3149
3150         if (!(wrapper->flags & WL_PROXY_FLAG_WRAPPER))
3151                 wl_abort("Tried to destroy non-wrapper proxy with "
3152                          "wl_proxy_wrapper_destroy\n");
3153
3154         assert(wrapper->refcount == 1);
3155
3156         pthread_mutex_lock(&display->mutex);
3157         wrapper->flags |= WL_PROXY_FLAG_DESTROYED;
3158         free(wrapper);
3159         pthread_mutex_unlock(&display->mutex);
3160 }
3161
3162 WL_EXPORT void
3163 wl_log_set_handler_client(wl_log_func_t handler)
3164 {
3165         wl_log_handler = handler;
3166 }
3167
3168 //TIZEN_ONLY(20200516) : add APIs for setting/getting name of a display
3169 void
3170 wl_display_set_name(struct wl_display *display, char *name)
3171 {
3172         if (!display || !name)
3173                 return;
3174
3175         if (display->name)
3176                 free(display->name);
3177
3178         display->name = strdup(name);
3179 }
3180
3181 char *
3182 wl_display_get_name(struct wl_display *display)
3183 {
3184         if (!display)
3185                 return NULL;
3186
3187         return display->name;
3188 }
3189 // END