File: hsgclosure.c

package info (click to toggle)
haskell-haskell-gi-base 0.26.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 408 kB
  • sloc: haskell: 1,604; ansic: 324; makefile: 5
file content (477 lines) | stat: -rw-r--r-- 13,301 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#define _GNU_SOURCE

/* GHC's semi-public Rts API */
#include <Rts.h>

#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#include <glib-object.h>
#include <glib.h>

static int print_debug_info ()
{
  static int __print_debug_info = -1;

  if (__print_debug_info == -1) {
    __print_debug_info = getenv ("HASKELL_GI_DEBUG_MEM") != NULL;
  }

  return __print_debug_info;
}

/*
  A mutex protecting the log file handle. We make it recursive,
  i.e. refcounted, so it is OK to lock repeatedly in the same thread.
*/
static pthread_mutex_t log_mutex
#if defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
  = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
#elif defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
  = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
#else
  ;
__attribute__ ((constructor)) static void init_log_mutex()
{
  pthread_mutexattr_t attr;
  pthread_mutexattr_init(&attr);
  pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  pthread_mutex_init(&log_mutex, &attr);
  pthread_mutexattr_destroy(&attr);
}
#endif

/* Give the current thread exclusive access to the log */
static void lock_log()
{
  pthread_mutex_lock(&log_mutex);
}

/* Decrease the refcount of the mutex protecting access to the log
   from other threads */
static void unlock_log()
{
  pthread_mutex_unlock(&log_mutex);
}

/* Print the given message to the log. The passed in string does not
   need to be zero-terminated. The message is only printed if the
   HASKELL_GI_DEBUG_MEM variable is set. */
void dbg_log_with_len (const char *msg, int len)
{
  if (print_debug_info()) {
    lock_log();
    fwrite(msg, len, 1, stderr);
    unlock_log();
  }
}

/* Print the given printf-style message to the log. The message is
   only printed if the HASKELL_GI_DEBUG_MEM variable is set. */
__attribute__ ((format (printf, 1, 2)))
static void dbg_log (const char *msg, ...)
{
  va_list args;

  va_start(args, msg);

  if (print_debug_info()) {
    lock_log();
    vfprintf(stderr, msg, args);
    unlock_log();
  }

  va_end(args);
}

int check_object_type (void *instance, GType type)
{
  int result;

  if (instance != NULL) {
     result = !!G_TYPE_CHECK_INSTANCE_TYPE(instance, type);
  } else {
    result = 0;
    dbg_log("Check failed: got a null pointer\n");
  }

  return result;
}

GType _haskell_gi_g_value_get_type (GValue *gvalue)
{
  return G_VALUE_TYPE (gvalue);
}

/* Information about a boxed type to free */
typedef struct {
  GType gtype;
  gpointer boxed;
} BoxedFreeInfo;

/* Auxiliary function for freeing boxed types in the main loop. See
   the annotation in g_object_unref_in_main_loop() below. */
static gboolean main_loop_boxed_free_helper (gpointer _info)
{
  BoxedFreeInfo *info = (BoxedFreeInfo*)_info;

  if (print_debug_info()) {
    GThread *self = g_thread_self ();
    lock_log();
    dbg_log("Freeing a boxed object at %p from idle callback [thread: %p]\n",
            info->boxed, self);
    dbg_log("\tIt is of type %s\n", g_type_name(info->gtype));
  }

  g_boxed_free (info->gtype, info->boxed);

  if (print_debug_info()) {
    dbg_log("\tdone freeing %p.\n", info->boxed);
    unlock_log();
  }

  g_free(info);

  return FALSE; /* Do not invoke again */
}

void boxed_free_helper (GType gtype, void *boxed)
{
  BoxedFreeInfo *info = g_malloc(sizeof(BoxedFreeInfo));

  info->gtype = gtype;
  info->boxed = boxed;

  g_idle_add (main_loop_boxed_free_helper, info);
}

void dbg_g_object_disown (GObject *obj)
{
  GType gtype;

  if (print_debug_info()) {
    lock_log();
    GThread *self = g_thread_self();
    dbg_log("Disowning a GObject at %p [thread: %p]\n", obj, self);
    gtype = G_TYPE_FROM_INSTANCE (obj);
    dbg_log("\tIt is of type %s\n", g_type_name(gtype));
    dbg_log("\tIts refcount before disowning is %d\n", (int)obj->ref_count);
    unlock_log();
  }
}

static void print_object_dbg_info (GObject *obj)
{
  GThread *self = g_thread_self();
  GType gtype;

  dbg_log("Unref of %p from idle callback [thread: %p]\n", obj, self);
  gtype = G_TYPE_FROM_INSTANCE (obj);
  dbg_log("\tIt is of type %s\n", g_type_name(gtype));
  dbg_log("\tIts refcount before unref is %d\n", (int)obj->ref_count);
}

/*
  We schedule all GObject deletions to happen in the main loop. The
  reason is that for some types the destructor is not thread safe, and
  assumes that it is being run from the same thread as the main loop
  that created the object.
 */
static gboolean
g_object_unref_in_main_loop (gpointer obj)
{
  if (print_debug_info()) {
    lock_log();
    print_object_dbg_info ((GObject*)obj);
  }

  g_object_unref (obj);

  if (print_debug_info()) {
    fprintf(stderr, "\tUnref done\n");
    unlock_log();
  }

  return FALSE; /* Do not invoke again */
}

void dbg_g_object_unref (GObject *obj)
{
  g_idle_add(g_object_unref_in_main_loop, obj);
}

static gboolean gvalue_unref_in_main_loop(void *gv)
{
  g_boxed_free(G_TYPE_VALUE, gv);

  return FALSE; /* Do not invoke again */
}

void haskell_gi_gvalue_free(GValue *gv)
{
  g_idle_add(gvalue_unref_in_main_loop, gv);
}

/**
 * dbg_g_object_new:
 * @gtype: #GType for the object to construct.
 * @n_props: Number of parameters for g_object_new_with_properties().
 * @names: Names of the properties to be set.
 * @values: Parameters for g_object_new_with_properties().
 *
 * Allocate a #GObject of #GType @gtype, with the given @params. The
 * returned object is never floating, and we always own a reference to
 * it. (It might not be the only existing to the object, but it is in
 * any case safe to call g_object_unref() when we are not wrapping the
 * object ourselves anymore.)
 *
 * Returns: A new #GObject.
 */
gpointer dbg_g_object_new (GType gtype, guint n_props,
                           const char *names[], const GValue values[])
{
  gpointer result;

  if (print_debug_info()) {
    GThread *self = g_thread_self();

    lock_log();
    dbg_log("Creating a new GObject of type %s [thread: %p]\n",
            g_type_name(gtype), self);
  }

#if GLIB_CHECK_VERSION(2,54,0)
  result = g_object_new_with_properties (gtype, n_props, names, values);
#else
  { GParameter params[n_props];
    int i;

    for (i=0; i<n_props; i++) {
      memcpy (&params[i].value, &values[i], sizeof(GValue));
      params[i].name = names[i];
    }

    result = g_object_newv (gtype, n_props, params);
  }
#endif

  /*
    Initially unowned GObjects can be either floating or not after
    construction. They are generally floating, but GtkWindow for
    instance is not floating after construction.

    In either case we want to call g_object_ref_sink(): if the object
    is floating to take ownership of the reference, and otherwise to
    add a reference that we own.

    If the object is not initially unowned we simply take control of
    the initial reference (implicitly).
   */
  if (G_IS_INITIALLY_UNOWNED (result)) {
    g_object_ref_sink (result);
  }

  if (print_debug_info()) {
    dbg_log("\tdone, got a pointer at %p\n", result);
    unlock_log();
  }

  return result;
}

/* Same as freeHaskellFunctionPtr, but it does nothing when given a
   null pointer, instead of crashing */
void safeFreeFunPtr(void *ptr)
{
  if (ptr != NULL)
    freeHaskellFunctionPtr(ptr);
}

/* Same as safeFreeFunPtr, but it accepts (but ignores) an extra argument */
void safeFreeFunPtr2(void *ptr, void *unused)
{
  safeFreeFunPtr(ptr);
}

/* Returns the GType associated to a class instance */
GType haskell_gi_gtype_from_class (gpointer klass)
{
  return G_TYPE_FROM_CLASS (klass);
}

/* Returns the GType associated to a given instance */
GType haskell_gi_gtype_from_instance (gpointer instance)
{
  return G_TYPE_FROM_INSTANCE (instance);
}

static pthread_mutex_t gtypes_mutex = PTHREAD_MUTEX_INITIALIZER;

typedef struct {
  GType gtype;
  GInterfaceInfo *info;
} CombinedInterfaceInfo;

/* Register a new type into the GObject class hierarchy, if it has not
   been registered already */
GType haskell_gi_register_gtype (GType parent, const char *name,
                                 GClassInitFunc class_init,
                                 GInstanceInitFunc instance_init,
                                 GSList* interfaces)
{
  GType result;

  /* We lock here in order to make sure that we don't try to register
     the same type twice. */
  pthread_mutex_lock(&gtypes_mutex);
  result = g_type_from_name (name);

  if (result == 0) {
    /* Note that class_init and instance_init are HsFunPtrs, which we
       keep alive for the duration of the program. */
    GTypeQuery query;
    g_type_query (parent, &query);
    result = g_type_register_static_simple (parent, name,
                                            query.class_size, class_init,
                                            query.instance_size, instance_init,
                                            0);
    while (interfaces != NULL) {
      CombinedInterfaceInfo *info = (CombinedInterfaceInfo*) interfaces->data;
      g_type_add_interface_static (result, info->gtype, info->info);
      interfaces = interfaces -> next;
    }
  } else {
    /* Free the memory associated with the HsFunPtrs that we are
       given, to avoid a (small) memory leak. */
    hs_free_fun_ptr ((HsFunPtr)class_init);
    hs_free_fun_ptr ((HsFunPtr)instance_init);

    while (interfaces != NULL) {
      CombinedInterfaceInfo *info = (CombinedInterfaceInfo*) interfaces->data;
      hs_free_fun_ptr ((HsFunPtr) info -> info -> interface_init);
      if (info -> info -> interface_finalize)
        hs_free_fun_ptr ((HsFunPtr) info -> info -> interface_finalize);
      interfaces = interfaces -> next;
    }
  }
  pthread_mutex_unlock(&gtypes_mutex);

  return result;
}

static HsStablePtr duplicateStablePtr(HsStablePtr stable_ptr)
{
  return getStablePtr(deRefStablePtr(stable_ptr));
}

GType haskell_gi_StablePtr_get_type (void)
{
  static gsize g_define_type_id = 0;

  if (g_once_init_enter (&g_define_type_id))
    {
      GType type_id =
        g_boxed_type_register_static (g_intern_static_string ("HaskellGIStablePtr"),
                                      duplicateStablePtr,
                                      hs_free_stable_ptr);

      g_once_init_leave (&g_define_type_id, type_id);
    }

  return g_define_type_id;
}

/* This is identical to haskell_gi_StablePtr_get_type, other than the
   type name. The reason for this is that we want two different types,
   to distinguish between GValues wrapping generic StablePtrs, and
   those wrapping specifically wrapping StablePtrs to Dynamic
   values. */
GType haskell_gi_HaskellValue_get_type (void)
{
  static gsize g_define_type_id = 0;

  if (g_once_init_enter (&g_define_type_id))
    {
      GType type_id =
        g_boxed_type_register_static (g_intern_static_string ("HaskellGIHaskellValue"),
                                      duplicateStablePtr,
                                      hs_free_stable_ptr);

      g_once_init_leave (&g_define_type_id, type_id);
    }

  return g_define_type_id;
}

/* A safer version of get_boxed, that checks that the GValue contains
   the right boxed type. */
gpointer haskell_gi_safe_get_boxed_haskell_value(const GValue *gv)
{
  if (G_VALUE_TYPE(gv) != haskell_gi_HaskellValue_get_type()) {
    fprintf(stderr, "Unexpected type inside the GValue: ā€˜%s’\n.",
            G_VALUE_TYPE_NAME(gv));

    return NULL;
  }

  return g_value_get_boxed(gv);
}

/* Release the FunPtr allocated for a Haskell signal handler */
void
haskell_gi_release_signal_closure (gpointer unused,
                                   GCClosure *closure)
{
  lock_log();
  dbg_log("Releasing a signal closure %p\n", closure->callback);

  hs_free_fun_ptr (closure->callback);

  dbg_log("\tDone.\n");
  unlock_log();
}

/* Check whether the given closure is floating */
gboolean
haskell_gi_g_closure_is_floating (GClosure *closure)
{
  return !!(closure->floating);
}

/* GParamSpec* types are registered as GObjects, but they do not have
   an exported type_init function. They only export CPP macros, so
   we have to provide our own. */
#define PARAM_TYPE(CamelCase, UPPERCASE) \
  GType haskell_gi_pspec_type_init_##CamelCase (void) { \
    return G_TYPE_##UPPERCASE;                          \
  }

PARAM_TYPE(ParamSpec, PARAM);
PARAM_TYPE(ParamSpecBoolean, PARAM_BOOLEAN);
PARAM_TYPE(ParamSpecBoxed, PARAM_BOXED);
PARAM_TYPE(ParamSpecChar, PARAM_CHAR);
PARAM_TYPE(ParamSpecDouble, PARAM_DOUBLE);
PARAM_TYPE(ParamSpecEnum, PARAM_ENUM);
PARAM_TYPE(ParamSpecFlags, PARAM_FLAGS);
PARAM_TYPE(ParamSpecFloat, PARAM_FLOAT);
PARAM_TYPE(ParamSpecGType, PARAM_GTYPE);
PARAM_TYPE(ParamSpecInt, PARAM_INT);
PARAM_TYPE(ParamSpecInt64, PARAM_INT64);
PARAM_TYPE(ParamSpecLong, PARAM_LONG);
PARAM_TYPE(ParamSpecObject, PARAM_OBJECT);
PARAM_TYPE(ParamSpecOverride, PARAM_OVERRIDE);
PARAM_TYPE(ParamSpecParam, PARAM_PARAM);
PARAM_TYPE(ParamSpecPointer, PARAM_POINTER);
PARAM_TYPE(ParamSpecString, PARAM_STRING);
PARAM_TYPE(ParamSpecUChar, PARAM_UCHAR);
PARAM_TYPE(ParamSpecUInt, PARAM_UINT);
PARAM_TYPE(ParamSpecUInt64, PARAM_UINT64);
PARAM_TYPE(ParamSpecULong, PARAM_ULONG);
PARAM_TYPE(ParamSpecUnichar, PARAM_UNICHAR);
PARAM_TYPE(ParamSpecVariant, PARAM_VARIANT);
/* The following is deprecated, ignore the warning that GLib raises. */
#undef GLIB_DEPRECATED_MACRO
#define GLIB_DEPRECATED_MACRO
PARAM_TYPE(ParamSpecValueArray, PARAM_VALUE_ARRAY);