gstpad: Probes that return HANDLED can reset the data info field
[platform/upstream/gstreamer.git] / gst / gstpluginloader.c
1 /* GStreamer
2  * Copyright (C) 2008 Jan Schmidt <jan.schmidt@sun.com>
3  *
4  * gstpluginloader.c: GstPluginLoader helper for loading plugin files
5  * out of process.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include <gst/gst_private.h>
28
29 #ifndef G_OS_WIN32
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #else
36 #define WIN32_LEAN_AND_MEAN
37
38 #define fsync(fd) _commit(fd)
39 #include <io.h>
40
41 #include <windows.h>
42 extern HMODULE _priv_gst_dll_handle;
43 #endif
44
45 #ifdef HAVE_SYS_UTSNAME_H
46 #include <sys/utsname.h>
47 #endif
48
49 #include <errno.h>
50
51 #include <gst/gstconfig.h>
52
53 #include <gst/gstpoll.h>
54 #include <gst/gstutils.h>
55
56 #include <gst/gstpluginloader.h>
57 #include <gst/gstregistrychunks.h>
58 #include <gst/gstregistrybinary.h>
59
60 /* IMPORTANT: Bump the version number if the plugin loader packet protocol
61  * changes. Changes in the binary registry format itself are handled by
62  * bumping the GST_MAGIC_BINARY_VERSION_STR
63  */
64 static const guint32 loader_protocol_version = 3;
65
66 #define GST_CAT_DEFAULT GST_CAT_PLUGIN_LOADING
67
68 static GstPluginLoader *plugin_loader_new (GstRegistry * registry);
69 static gboolean plugin_loader_free (GstPluginLoader * loader);
70 static gboolean plugin_loader_load (GstPluginLoader * loader,
71     const gchar * filename, off_t file_size, time_t file_mtime);
72
73 /* functions used in GstRegistry scanning */
74 const GstPluginLoaderFuncs _priv_gst_plugin_loader_funcs = {
75   plugin_loader_new, plugin_loader_free, plugin_loader_load
76 };
77
78 typedef struct _PendingPluginEntry
79 {
80   /* sequence number */
81   guint32 tag;
82   gchar *filename;
83   off_t file_size;
84   time_t file_mtime;
85 } PendingPluginEntry;
86
87 struct _GstPluginLoader
88 {
89   GstRegistry *registry;
90   GstPoll *fdset;
91
92   gboolean child_running;
93   GPid child_pid;
94   GstPollFD fd_w;
95   GstPollFD fd_r;
96
97   gboolean is_child;
98   gboolean got_plugin_details;
99
100   /* Transmit buffer */
101   guint8 *tx_buf;
102   guint tx_buf_size;
103   guint tx_buf_write;
104   guint tx_buf_read;
105
106   /* next sequence number (for PendingPluginEntry) */
107   guint32 next_tag;
108
109   guint8 *rx_buf;
110   guint rx_buf_size;
111   gboolean rx_done;
112   gboolean rx_got_sync;
113
114   /* Head and tail of the pending plugins list. List of
115      PendingPluginEntry structs */
116   GList *pending_plugins;
117   GList *pending_plugins_tail;
118 };
119
120 #define PACKET_EXIT 1
121 #define PACKET_LOAD_PLUGIN 2
122 #define PACKET_SYNC 3
123 #define PACKET_PLUGIN_DETAILS 4
124 #define PACKET_VERSION 5
125
126 #define BUF_INIT_SIZE 512
127 #define BUF_GROW_EXTRA 512
128 #define BUF_MAX_SIZE (32 * 1024 * 1024)
129
130 #define HEADER_SIZE 12
131 /* 4 magic hex bytes to mark each packet */
132 #define HEADER_MAGIC 0xbefec0ae
133 #define ALIGNMENT   (sizeof (void *))
134
135 static gboolean gst_plugin_loader_spawn (GstPluginLoader * loader);
136 static void put_packet (GstPluginLoader * loader, guint type, guint32 tag,
137     const guint8 * payload, guint32 payload_len);
138 static gboolean exchange_packets (GstPluginLoader * l);
139 static gboolean plugin_loader_replay_pending (GstPluginLoader * l);
140 static gboolean plugin_loader_load_and_sync (GstPluginLoader * l,
141     PendingPluginEntry * entry);
142 static void plugin_loader_create_blacklist_plugin (GstPluginLoader * l,
143     PendingPluginEntry * entry);
144 static void plugin_loader_cleanup_child (GstPluginLoader * loader);
145 static gboolean plugin_loader_sync_with_child (GstPluginLoader * l);
146
147 static GstPluginLoader *
148 plugin_loader_new (GstRegistry * registry)
149 {
150   GstPluginLoader *l = g_slice_new0 (GstPluginLoader);
151
152   if (registry)
153     l->registry = gst_object_ref (registry);
154   l->fdset = gst_poll_new (FALSE);
155   gst_poll_fd_init (&l->fd_w);
156   gst_poll_fd_init (&l->fd_r);
157
158   l->tx_buf_size = BUF_INIT_SIZE;
159   l->tx_buf = g_malloc (BUF_INIT_SIZE);
160
161   l->next_tag = 0;
162
163   l->rx_buf_size = BUF_INIT_SIZE;
164   l->rx_buf = g_malloc (BUF_INIT_SIZE);
165
166   return l;
167 }
168
169 static gboolean
170 plugin_loader_free (GstPluginLoader * loader)
171 {
172   GList *cur;
173   gboolean got_plugin_details;
174
175   fsync (loader->fd_w.fd);
176
177   if (loader->child_running) {
178     put_packet (loader, PACKET_EXIT, 0, NULL, 0);
179
180     /* Swap packets with the child until it exits cleanly */
181     while (!loader->rx_done) {
182       if (exchange_packets (loader) || loader->rx_done)
183         continue;
184
185       if (!plugin_loader_replay_pending (loader))
186         break;
187       put_packet (loader, PACKET_EXIT, 0, NULL, 0);
188     }
189
190     plugin_loader_cleanup_child (loader);
191   } else {
192     close (loader->fd_w.fd);
193     close (loader->fd_r.fd);
194   }
195
196   gst_poll_free (loader->fdset);
197
198   g_free (loader->rx_buf);
199   g_free (loader->tx_buf);
200
201   if (loader->registry)
202     gst_object_unref (loader->registry);
203
204   got_plugin_details = loader->got_plugin_details;
205
206   /* Free any pending plugin entries */
207   cur = loader->pending_plugins;
208   while (cur) {
209     PendingPluginEntry *entry = (PendingPluginEntry *) (cur->data);
210     g_free (entry->filename);
211     g_slice_free (PendingPluginEntry, entry);
212
213     cur = g_list_delete_link (cur, cur);
214   }
215
216   g_slice_free (GstPluginLoader, loader);
217
218   return got_plugin_details;
219 }
220
221 static gboolean
222 plugin_loader_load (GstPluginLoader * loader, const gchar * filename,
223     off_t file_size, time_t file_mtime)
224 {
225   gint len;
226   PendingPluginEntry *entry;
227
228   if (!gst_plugin_loader_spawn (loader))
229     return FALSE;
230
231   /* Send a packet to the child requesting that it load the given file */
232   GST_LOG_OBJECT (loader->registry,
233       "Sending file %s to child. tag %u", filename, loader->next_tag);
234
235   entry = g_slice_new (PendingPluginEntry);
236   entry->tag = loader->next_tag++;
237   entry->filename = g_strdup (filename);
238   entry->file_size = file_size;
239   entry->file_mtime = file_mtime;
240   loader->pending_plugins_tail =
241       g_list_append (loader->pending_plugins_tail, entry);
242
243   if (loader->pending_plugins == NULL)
244     loader->pending_plugins = loader->pending_plugins_tail;
245   else
246     loader->pending_plugins_tail = g_list_next (loader->pending_plugins_tail);
247
248   len = strlen (filename);
249   put_packet (loader, PACKET_LOAD_PLUGIN, entry->tag,
250       (guint8 *) filename, len + 1);
251
252   if (!exchange_packets (loader)) {
253     if (!plugin_loader_replay_pending (loader))
254       return FALSE;
255   }
256
257   return TRUE;
258 }
259
260 static gboolean
261 plugin_loader_replay_pending (GstPluginLoader * l)
262 {
263   GList *cur, *next;
264
265 restart:
266   if (!gst_plugin_loader_spawn (l))
267     return FALSE;
268
269   /* Load each plugin one by one synchronously until we find the
270    * crashing one */
271   while ((cur = l->pending_plugins)) {
272     PendingPluginEntry *entry = (PendingPluginEntry *) (cur->data);
273
274     if (!plugin_loader_load_and_sync (l, entry)) {
275       /* Create dummy plugin entry to block re-scanning this file */
276       GST_ERROR ("Plugin file %s failed to load. Blacklisting",
277           entry->filename);
278       plugin_loader_create_blacklist_plugin (l, entry);
279       l->got_plugin_details = TRUE;
280       /* Now remove this crashy plugin from the head of the list */
281       l->pending_plugins = g_list_delete_link (cur, cur);
282       g_free (entry->filename);
283       g_slice_free (PendingPluginEntry, entry);
284       if (l->pending_plugins == NULL)
285         l->pending_plugins_tail = NULL;
286       if (!gst_plugin_loader_spawn (l))
287         return FALSE;
288       break;
289     }
290   }
291
292   /* We exited after finding the crashing one. If there's any more pending,
293    * dispatch them post-haste, but don't wait */
294   for (cur = l->pending_plugins; cur != NULL; cur = next) {
295     PendingPluginEntry *entry = (PendingPluginEntry *) (cur->data);
296
297     next = g_list_next (cur);
298
299     put_packet (l, PACKET_LOAD_PLUGIN, entry->tag,
300         (guint8 *) entry->filename, strlen (entry->filename) + 1);
301
302     /* This might invalidate cur, which is why we grabbed 'next' above */
303     if (!exchange_packets (l))
304       goto restart;
305   }
306
307   return TRUE;
308 }
309
310 static gboolean
311 plugin_loader_sync_with_child (GstPluginLoader * l)
312 {
313   put_packet (l, PACKET_SYNC, 0, NULL, 0);
314
315   l->rx_got_sync = FALSE;
316   while (!l->rx_got_sync) {
317     if (!exchange_packets (l))
318       return FALSE;
319   }
320   return TRUE;
321 }
322
323 static gboolean
324 plugin_loader_load_and_sync (GstPluginLoader * l, PendingPluginEntry * entry)
325 {
326   gint len;
327
328   GST_DEBUG_OBJECT (l->registry, "Synchronously loading plugin file %s",
329       entry->filename);
330
331   len = strlen (entry->filename);
332   put_packet (l, PACKET_LOAD_PLUGIN, entry->tag,
333       (guint8 *) entry->filename, len + 1);
334
335   return plugin_loader_sync_with_child (l);
336 }
337
338 static void
339 plugin_loader_create_blacklist_plugin (GstPluginLoader * l,
340     PendingPluginEntry * entry)
341 {
342   GstPlugin *plugin = g_object_new (GST_TYPE_PLUGIN, NULL);
343
344   plugin->filename = g_strdup (entry->filename);
345   plugin->file_mtime = entry->file_mtime;
346   plugin->file_size = entry->file_size;
347   GST_OBJECT_FLAG_SET (plugin, GST_PLUGIN_FLAG_BLACKLISTED);
348
349   plugin->basename = g_path_get_basename (plugin->filename);
350   plugin->desc.name = g_intern_string (plugin->basename);
351   plugin->desc.description = "Plugin for blacklisted file";
352   plugin->desc.version = "0.0.0";
353   plugin->desc.license = "BLACKLIST";
354   plugin->desc.source = plugin->desc.license;
355   plugin->desc.package = plugin->desc.license;
356   plugin->desc.origin = plugin->desc.license;
357
358   GST_DEBUG ("Adding blacklist plugin '%s'", plugin->desc.name);
359   gst_registry_add_plugin (l->registry, plugin);
360 }
361
362 #ifdef __APPLE__
363 #if defined(__x86_64__)
364 #define USR_BIN_ARCH_SWITCH "-x86_64"
365 #elif defined(__i386__)
366 #define USR_BIN_ARCH_SWITCH "-i386"
367 #elif defined(__ppc__)
368 #define USR_BIN_ARCH_SWITCH "-ppc"
369 #elif defined(__ppc64__)
370 #define USR_BIN_ARCH_SWITCH "-ppc64"
371 #endif
372 #endif
373
374 #define YES_MULTIARCH 1
375 #define NO_MULTIARCH  2
376
377 #if defined (__APPLE__) && defined (USR_BIN_ARCH_SWITCH)
378 static gboolean
379 gst_plugin_loader_use_usr_bin_arch (void)
380 {
381   static volatile gsize multiarch = 0;
382
383   if (g_once_init_enter (&multiarch)) {
384     gsize res = NO_MULTIARCH;
385
386 #ifdef HAVE_SYS_UTSNAME_H
387     {
388       struct utsname uname_data;
389
390       if (uname (&uname_data) == 0) {
391         /* Check for OS X >= 10.5 (darwin kernel 9.0) */
392         GST_LOG ("%s %s", uname_data.sysname, uname_data.release);
393         if (g_ascii_strcasecmp (uname_data.sysname, "Darwin") == 0 &&
394             g_strtod (uname_data.release, NULL) >= 9.0) {
395           res = YES_MULTIARCH;
396         }
397       }
398     }
399 #endif
400
401     GST_INFO ("multiarch: %s", (res == YES_MULTIARCH) ? "yes" : "no");
402     g_once_init_leave (&multiarch, res);
403   }
404   return (multiarch == YES_MULTIARCH);
405 }
406 #endif /* __APPLE__ && USR_BIN_ARCH_SWITCH */
407
408 static gboolean
409 gst_plugin_loader_try_helper (GstPluginLoader * loader, gchar * location)
410 {
411   char *argv[6] = { NULL, };
412   int c = 0;
413
414 #if defined (__APPLE__) && defined (USR_BIN_ARCH_SWITCH)
415   if (gst_plugin_loader_use_usr_bin_arch ()) {
416     argv[c++] = (char *) "/usr/bin/arch";
417     argv[c++] = (char *) USR_BIN_ARCH_SWITCH;
418   }
419 #endif
420   argv[c++] = location;
421   argv[c++] = (char *) "-l";
422   argv[c++] = _gst_executable_path;
423   argv[c++] = NULL;
424
425   if (c > 4) {
426     GST_LOG ("Trying to spawn gst-plugin-scanner helper at %s with arch %s",
427         location, argv[1]);
428   } else {
429     GST_LOG ("Trying to spawn gst-plugin-scanner helper at %s", location);
430   }
431
432   if (!g_spawn_async_with_pipes (NULL, argv, NULL,
433           G_SPAWN_DO_NOT_REAP_CHILD /* | G_SPAWN_STDERR_TO_DEV_NULL */ ,
434           NULL, NULL, &loader->child_pid, &loader->fd_w.fd, &loader->fd_r.fd,
435           NULL, NULL))
436     return FALSE;
437
438   gst_poll_add_fd (loader->fdset, &loader->fd_w);
439   gst_poll_add_fd (loader->fdset, &loader->fd_r);
440
441   gst_poll_fd_ctl_read (loader->fdset, &loader->fd_r, TRUE);
442
443   loader->tx_buf_write = loader->tx_buf_read = 0;
444
445   put_packet (loader, PACKET_VERSION, 0, NULL, 0);
446   if (!plugin_loader_sync_with_child (loader))
447     return FALSE;
448
449   loader->child_running = TRUE;
450
451   return TRUE;
452 }
453
454 static gboolean
455 gst_plugin_loader_spawn (GstPluginLoader * loader)
456 {
457   const gchar *env;
458   char *helper_bin;
459   gboolean res = FALSE;
460
461   if (loader->child_running)
462     return TRUE;
463
464   /* Find the gst-plugin-scanner: first try the env-var if it is set,
465    * otherwise use the installed version */
466   env = g_getenv ("GST_PLUGIN_SCANNER_1_0");
467   if (env == NULL)
468     env = g_getenv ("GST_PLUGIN_SCANNER");
469
470   if (env != NULL && *env != '\0') {
471     GST_LOG ("Trying GST_PLUGIN_SCANNER env var: %s", env);
472     helper_bin = g_strdup (env);
473     res = gst_plugin_loader_try_helper (loader, helper_bin);
474     g_free (helper_bin);
475   }
476
477   if (!res) {
478     GST_LOG ("Trying installed plugin scanner");
479
480 #ifdef G_OS_WIN32
481     {
482       gchar *basedir;
483
484       basedir =
485           g_win32_get_package_installation_directory_of_module
486           (_priv_gst_dll_handle);
487       helper_bin =
488           g_build_filename (basedir, GST_PLUGIN_SCANNER_SUBDIR,
489           "gstreamer-" GST_API_VERSION, "gst-plugin-scanner.exe", NULL);
490       g_free (basedir);
491     }
492 #else
493     helper_bin = g_strdup (GST_PLUGIN_SCANNER_INSTALLED);
494 #endif
495     res = gst_plugin_loader_try_helper (loader, helper_bin);
496     g_free (helper_bin);
497
498     if (!res) {
499       GST_INFO ("No gst-plugin-scanner available, or not working");
500     }
501   }
502
503   return loader->child_running;
504 }
505
506 static void
507 plugin_loader_cleanup_child (GstPluginLoader * l)
508 {
509   if (!l->child_running || l->is_child)
510     return;
511
512   gst_poll_remove_fd (l->fdset, &l->fd_w);
513   gst_poll_remove_fd (l->fdset, &l->fd_r);
514
515   close (l->fd_w.fd);
516   close (l->fd_r.fd);
517
518 #ifndef G_OS_WIN32
519   GST_LOG ("waiting for child process to exit");
520   waitpid (l->child_pid, NULL, 0);
521 #else
522   g_warning ("FIXME: Implement child process shutdown for Win32");
523 #endif
524   g_spawn_close_pid (l->child_pid);
525
526   l->child_running = FALSE;
527 }
528
529 gboolean
530 _gst_plugin_loader_client_run (void)
531 {
532   gboolean res = TRUE;
533   GstPluginLoader *l;
534
535   l = plugin_loader_new (NULL);
536   if (l == NULL)
537     return FALSE;
538
539   /* On entry, the inward pipe is STDIN, and outward is STDOUT.
540    * Dup those somewhere better so that plugins printing things
541    * won't interfere with anything */
542 #ifndef G_OS_WIN32
543   {
544     int dup_fd;
545
546     dup_fd = dup (0);           /* STDIN */
547     if (dup_fd == -1) {
548       GST_ERROR ("Failed to start. Could not dup STDIN, errno %d", errno);
549       res = FALSE;
550       goto beach;
551     }
552     l->fd_r.fd = dup_fd;
553     close (0);
554
555     dup_fd = dup (1);           /* STDOUT */
556     if (dup_fd == -1) {
557       GST_ERROR ("Failed to start. Could not dup STDOUT, errno %d", errno);
558       res = FALSE;
559       goto beach;
560     }
561     l->fd_w.fd = dup_fd;
562     close (1);
563
564     /* Dup stderr down to stdout so things that plugins print are visible,
565      * but don't care if it fails */
566     dup2 (2, 1);
567   }
568 #else
569   /* FIXME: Use DuplicateHandle and friends on win32 */
570   l->fd_w.fd = 1;               /* STDOUT */
571   l->fd_r.fd = 0;               /* STDIN */
572 #endif
573
574   gst_poll_add_fd (l->fdset, &l->fd_w);
575   gst_poll_add_fd (l->fdset, &l->fd_r);
576   gst_poll_fd_ctl_read (l->fdset, &l->fd_r, TRUE);
577
578   l->is_child = TRUE;
579
580   GST_DEBUG ("Plugin scanner child running. Waiting for instructions");
581
582   /* Loop, listening for incoming packets on the fd and writing responses */
583   while (!l->rx_done && exchange_packets (l));
584
585 #ifndef G_OS_WIN32
586 beach:
587 #endif
588
589   plugin_loader_free (l);
590
591   return res;
592 }
593
594 static void
595 put_packet (GstPluginLoader * l, guint type, guint32 tag,
596     const guint8 * payload, guint32 payload_len)
597 {
598   guint8 *out;
599   guint len = payload_len + HEADER_SIZE;
600
601   if (l->tx_buf_write + len >= l->tx_buf_size) {
602     GST_LOG ("Expanding tx buf from %d to %d for packet of size %d",
603         l->tx_buf_size, l->tx_buf_write + len + BUF_GROW_EXTRA, len);
604     l->tx_buf_size = l->tx_buf_write + len + BUF_GROW_EXTRA;
605     l->tx_buf = g_realloc (l->tx_buf, l->tx_buf_size);
606   }
607
608   out = l->tx_buf + l->tx_buf_write;
609
610   /* one byte packet type */
611   out[0] = type;
612   /* 3 byte packet tag number */
613   GST_WRITE_UINT24_BE (out + 1, tag);
614   /* 4 bytes packet length */
615   GST_WRITE_UINT32_BE (out + 4, payload_len);
616   /* payload */
617   if (payload && payload_len)
618     memcpy (out + HEADER_SIZE, payload, payload_len);
619   /* Write magic into the header */
620   GST_WRITE_UINT32_BE (out + 8, HEADER_MAGIC);
621
622   l->tx_buf_write += len;
623   gst_poll_fd_ctl_write (l->fdset, &l->fd_w, TRUE);
624 }
625
626 static void
627 put_chunk (GstPluginLoader * l, GstRegistryChunk * chunk, guint * pos)
628 {
629   guint padsize = 0;
630   guint len;
631   guint8 *out;
632
633   /* Might need to align the chunk */
634   if (chunk->align && ((*pos) % ALIGNMENT) != 0)
635     padsize = ALIGNMENT - ((*pos) % ALIGNMENT);
636
637   len = padsize + chunk->size;
638
639   if (G_UNLIKELY (l->tx_buf_write + len >= l->tx_buf_size)) {
640     guint new_size = MAX (l->tx_buf_write + len,
641         l->tx_buf_size + l->tx_buf_size / 4) + BUF_GROW_EXTRA;
642     GST_LOG ("Expanding tx buf from %d to %d for chunk of size %d",
643         l->tx_buf_size, new_size, chunk->size);
644     l->tx_buf_size = new_size;
645     l->tx_buf = g_realloc (l->tx_buf, l->tx_buf_size);
646   }
647
648   out = l->tx_buf + l->tx_buf_write;
649   /* Clear the padding */
650   if (padsize)
651     memset (out, 0, padsize);
652   memcpy (out + padsize, chunk->data, chunk->size);
653
654   l->tx_buf_write += len;
655   *pos += len;
656
657   gst_poll_fd_ctl_write (l->fdset, &l->fd_w, TRUE);
658 };
659
660 static gboolean
661 write_one (GstPluginLoader * l)
662 {
663   guint8 *out;
664   guint32 to_write, magic;
665   int res;
666
667   if (l->tx_buf_read + HEADER_SIZE > l->tx_buf_write)
668     return FALSE;
669
670   out = l->tx_buf + l->tx_buf_read;
671
672   magic = GST_READ_UINT32_BE (out + 8);
673   if (magic != HEADER_MAGIC) {
674     GST_ERROR ("Packet magic number is missing. Memory corruption detected");
675     goto fail_and_cleanup;
676   }
677
678   to_write = GST_READ_UINT32_BE (out + 4) + HEADER_SIZE;
679   /* Check that the magic is intact, and the size is sensible */
680   if (to_write > l->tx_buf_size) {
681     GST_ERROR ("Indicated packet size is too large. Corruption detected");
682     goto fail_and_cleanup;
683   }
684
685   l->tx_buf_read += to_write;
686
687   GST_LOG ("Writing packet of size %d bytes to fd %d", to_write, l->fd_w.fd);
688
689   do {
690     res = write (l->fd_w.fd, out, to_write);
691     if (G_UNLIKELY (res < 0)) {
692       if (errno == EAGAIN || errno == EINTR)
693         continue;
694       /* Failed to write -> child died */
695       goto fail_and_cleanup;
696     }
697     to_write -= res;
698     out += res;
699   } while (to_write > 0);
700
701   if (l->tx_buf_read == l->tx_buf_write) {
702     gst_poll_fd_ctl_write (l->fdset, &l->fd_w, FALSE);
703     l->tx_buf_read = l->tx_buf_write = 0;
704   }
705
706   return TRUE;
707
708 fail_and_cleanup:
709   plugin_loader_cleanup_child (l);
710   return FALSE;
711 }
712
713 static gboolean
714 do_plugin_load (GstPluginLoader * l, const gchar * filename, guint tag)
715 {
716   GstPlugin *newplugin;
717   GList *chunks = NULL;
718
719   GST_DEBUG ("Plugin scanner loading file %s. tag %u", filename, tag);
720
721 #if 0                           /* Test code - crash based on filename */
722   if (strstr (filename, "coreelements") == NULL) {
723     g_printerr ("Crashing on file %s\n", filename);
724     g_printerr ("%d", *(gint *) (NULL));
725   }
726 #endif
727
728   newplugin = gst_plugin_load_file ((gchar *) filename, NULL);
729   if (newplugin) {
730     guint hdr_pos;
731     guint offset;
732
733     /* Now serialise the plugin details and send */
734     if (!_priv_gst_registry_chunks_save_plugin (&chunks,
735             gst_registry_get (), newplugin))
736       goto fail;
737
738     /* Store where the header is, write an empty one, then write
739      * all the payload chunks, then fix up the header size */
740     hdr_pos = l->tx_buf_write;
741     offset = HEADER_SIZE;
742     put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0);
743
744     if (chunks) {
745       GList *walk;
746       for (walk = chunks; walk; walk = g_list_next (walk)) {
747         GstRegistryChunk *cur = walk->data;
748         put_chunk (l, cur, &offset);
749
750         _priv_gst_registry_chunk_free (cur);
751       }
752
753       g_list_free (chunks);
754
755       /* Store the size of the written payload */
756       GST_WRITE_UINT32_BE (l->tx_buf + hdr_pos + 4, offset - HEADER_SIZE);
757     }
758 #if 0                           /* Test code - corrupt the tx buffer based on filename */
759     if (strstr (filename, "sink") != NULL) {
760       int fd, res;
761       g_printerr ("Corrupting tx buf on file %s\n", filename);
762       fd = open ("/dev/urandom", O_RDONLY);
763       res = read (fd, l->tx_buf, l->tx_buf_size);
764       close (fd);
765     }
766 #endif
767
768     gst_object_unref (newplugin);
769   } else {
770     put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0);
771   }
772
773   return TRUE;
774 fail:
775   put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0);
776   if (chunks) {
777     GList *walk;
778     for (walk = chunks; walk; walk = g_list_next (walk)) {
779       GstRegistryChunk *cur = walk->data;
780
781       _priv_gst_registry_chunk_free (cur);
782     }
783
784     g_list_free (chunks);
785   }
786
787   return FALSE;
788 }
789
790 static gboolean
791 check_protocol_version (GstPluginLoader * l, guint8 * payload,
792     guint payload_len)
793 {
794   guint32 got_version;
795   guint8 *binary_reg_ver;
796
797   if (payload_len < sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN)
798     return FALSE;
799
800   got_version = GST_READ_UINT32_BE (payload);
801   GST_LOG ("Got VERSION %u from child. Ours is %u", got_version,
802       loader_protocol_version);
803   if (got_version != loader_protocol_version)
804     return FALSE;
805
806   binary_reg_ver = payload + sizeof (guint32);
807   if (strcmp ((gchar *) binary_reg_ver, GST_MAGIC_BINARY_VERSION_STR)) {
808     GST_LOG ("Binary chunk format of child is different. Ours: %s, child %s\n",
809         GST_MAGIC_BINARY_VERSION_STR, binary_reg_ver);
810     return FALSE;
811   }
812
813   return TRUE;
814 };
815
816 static gboolean
817 handle_rx_packet (GstPluginLoader * l,
818     guint pack_type, guint32 tag, guint8 * payload, guint payload_len)
819 {
820   gboolean res = TRUE;
821
822   switch (pack_type) {
823     case PACKET_EXIT:
824       gst_poll_fd_ctl_read (l->fdset, &l->fd_r, FALSE);
825       if (l->is_child) {
826         /* Respond */
827         put_packet (l, PACKET_EXIT, 0, NULL, 0);
828       }
829       l->rx_done = TRUE;
830       return TRUE;
831     case PACKET_LOAD_PLUGIN:{
832       if (!l->is_child)
833         return TRUE;
834
835       /* Payload is the filename to load */
836       res = do_plugin_load (l, (gchar *) payload, tag);
837
838       break;
839     }
840     case PACKET_PLUGIN_DETAILS:{
841       gchar *tmp = (gchar *) payload;
842       PendingPluginEntry *entry = NULL;
843       GList *cur;
844
845       GST_DEBUG_OBJECT (l->registry,
846           "Received plugin details from child w/ tag %u. %d bytes info",
847           tag, payload_len);
848
849       /* Assume that tagged details come back in the order
850        * we requested, and delete anything before (but not
851        * including) this one */
852       cur = l->pending_plugins;
853       while (cur) {
854         PendingPluginEntry *e = (PendingPluginEntry *) (cur->data);
855
856         if (e->tag > tag)
857           break;
858
859         if (e->tag == tag) {
860           entry = e;
861           break;
862         } else {
863           cur = g_list_delete_link (cur, cur);
864           g_free (e->filename);
865           g_slice_free (PendingPluginEntry, e);
866         }
867       }
868
869       l->pending_plugins = cur;
870       if (cur == NULL)
871         l->pending_plugins_tail = NULL;
872
873       if (payload_len > 0) {
874         GstPlugin *newplugin = NULL;
875         if (!_priv_gst_registry_chunks_load_plugin (l->registry, &tmp,
876                 tmp + payload_len, &newplugin)) {
877           /* Got garbage from the child, so fail and trigger replay of plugins */
878           GST_ERROR_OBJECT (l->registry,
879               "Problems loading plugin details with tag %u from scanner", tag);
880           return FALSE;
881         }
882
883         GST_OBJECT_FLAG_UNSET (newplugin, GST_PLUGIN_FLAG_CACHED);
884         GST_LOG_OBJECT (l->registry,
885             "marking plugin %p as registered as %s", newplugin,
886             newplugin->filename);
887         newplugin->registered = TRUE;
888
889         /* We got a set of plugin details - remember it for later */
890         l->got_plugin_details = TRUE;
891       } else if (entry != NULL) {
892         /* Create a blacklist entry for this file to prevent scanning every time */
893         plugin_loader_create_blacklist_plugin (l, entry);
894         l->got_plugin_details = TRUE;
895       }
896
897       if (entry != NULL) {
898         g_free (entry->filename);
899         g_slice_free (PendingPluginEntry, entry);
900       }
901
902       /* Remove the plugin entry we just loaded */
903       cur = l->pending_plugins;
904       if (cur != NULL)
905         cur = g_list_delete_link (cur, cur);
906       l->pending_plugins = cur;
907       if (cur == NULL)
908         l->pending_plugins_tail = NULL;
909
910       break;
911     }
912     case PACKET_SYNC:
913       if (l->is_child) {
914         /* Respond with our reply - also a sync */
915         put_packet (l, PACKET_SYNC, tag, NULL, 0);
916         GST_LOG ("Got SYNC in child - replying");
917       } else
918         l->rx_got_sync = TRUE;
919       break;
920     case PACKET_VERSION:
921       if (l->is_child) {
922         /* Respond with our reply - a version packet, with the version */
923         const gint version_len =
924             sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN;
925         guint8 version_info[sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN];
926         memset (version_info, 0, version_len);
927         GST_WRITE_UINT32_BE (version_info, loader_protocol_version);
928         memcpy (version_info + sizeof (guint32), GST_MAGIC_BINARY_VERSION_STR,
929             strlen (GST_MAGIC_BINARY_VERSION_STR));
930         put_packet (l, PACKET_VERSION, tag, version_info, version_len);
931         GST_LOG ("Got VERSION in child - replying %u", loader_protocol_version);
932       } else {
933         res = check_protocol_version (l, payload, payload_len);
934       }
935       break;
936     default:
937       return FALSE;             /* Invalid packet -> something is wrong */
938   }
939
940   return res;
941 }
942
943 static gboolean
944 read_one (GstPluginLoader * l)
945 {
946   guint64 magic;
947   guint32 to_read, packet_len, tag;
948   guint8 *in;
949   gint res;
950
951   to_read = HEADER_SIZE;
952   in = l->rx_buf;
953   do {
954     res = read (l->fd_r.fd, in, to_read);
955     if (G_UNLIKELY (res < 0)) {
956       if (errno == EAGAIN || errno == EINTR)
957         continue;
958       GST_LOG ("Failed reading packet header");
959       return FALSE;
960     }
961     to_read -= res;
962     in += res;
963   } while (to_read > 0);
964
965   magic = GST_READ_UINT32_BE (l->rx_buf + 8);
966   if (magic != HEADER_MAGIC) {
967     GST_WARNING
968         ("Invalid packet (bad magic number) received from plugin scanner subprocess");
969     return FALSE;
970   }
971
972   packet_len = GST_READ_UINT32_BE (l->rx_buf + 4);
973   if (packet_len + HEADER_SIZE > BUF_MAX_SIZE) {
974     GST_WARNING
975         ("Received excessively large packet for plugin scanner subprocess");
976     return FALSE;
977   }
978   tag = GST_READ_UINT24_BE (l->rx_buf + 1);
979
980   if (packet_len > 0) {
981     if (packet_len + HEADER_SIZE >= l->rx_buf_size) {
982       GST_LOG ("Expanding rx buf from %d to %d",
983           l->rx_buf_size, packet_len + HEADER_SIZE + BUF_GROW_EXTRA);
984       l->rx_buf_size = packet_len + HEADER_SIZE + BUF_GROW_EXTRA;
985       l->rx_buf = g_realloc (l->rx_buf, l->rx_buf_size);
986     }
987
988     in = l->rx_buf + HEADER_SIZE;
989     to_read = packet_len;
990     do {
991       res = read (l->fd_r.fd, in, to_read);
992       if (G_UNLIKELY (res < 0)) {
993         if (errno == EAGAIN || errno == EINTR)
994           continue;
995         GST_ERROR ("Packet payload read failed");
996         return FALSE;
997       }
998       to_read -= res;
999       in += res;
1000     } while (to_read > 0);
1001   } else {
1002     GST_LOG ("No payload to read for 0 length packet type %d tag %u",
1003         l->rx_buf[0], tag);
1004   }
1005
1006   return handle_rx_packet (l, l->rx_buf[0], tag,
1007       l->rx_buf + HEADER_SIZE, packet_len);
1008 }
1009
1010 static gboolean
1011 exchange_packets (GstPluginLoader * l)
1012 {
1013   gint res;
1014
1015   /* Wait for activity on our FDs */
1016   do {
1017     do {
1018       res = gst_poll_wait (l->fdset, GST_SECOND);
1019     } while (res == -1 && (errno == EINTR || errno == EAGAIN));
1020
1021     if (res < 0)
1022       return FALSE;
1023
1024     GST_LOG ("Poll res = %d. %d bytes pending for write", res,
1025         l->tx_buf_write - l->tx_buf_read);
1026
1027     if (!l->rx_done) {
1028       if (gst_poll_fd_has_error (l->fdset, &l->fd_r)) {
1029         GST_LOG ("read fd %d errored", l->fd_r.fd);
1030         goto fail_and_cleanup;
1031       }
1032
1033       if (gst_poll_fd_can_read (l->fdset, &l->fd_r)) {
1034         if (!read_one (l))
1035           goto fail_and_cleanup;
1036       } else if (gst_poll_fd_has_closed (l->fdset, &l->fd_r)) {
1037         GST_LOG ("read fd %d closed", l->fd_r.fd);
1038         goto fail_and_cleanup;
1039       }
1040     }
1041
1042     if (l->tx_buf_read < l->tx_buf_write) {
1043       if (gst_poll_fd_has_error (l->fdset, &l->fd_w)) {
1044         GST_ERROR ("write fd %d errored", l->fd_w.fd);
1045         goto fail_and_cleanup;
1046       }
1047       if (gst_poll_fd_can_write (l->fdset, &l->fd_w)) {
1048         if (!write_one (l))
1049           goto fail_and_cleanup;
1050       } else if (gst_poll_fd_has_closed (l->fdset, &l->fd_w)) {
1051         GST_LOG ("write fd %d closed", l->fd_w.fd);
1052         goto fail_and_cleanup;
1053       }
1054     }
1055   } while (l->tx_buf_read < l->tx_buf_write);
1056
1057   return TRUE;
1058 fail_and_cleanup:
1059   plugin_loader_cleanup_child (l);
1060   return FALSE;
1061 }