pygi-marshal-from-py.c 45.7 KB
Newer Older
1 2 3
/* -*- Mode: C; c-basic-offset: 4 -*-
 * vim: tabstop=4 shiftwidth=4 expandtab
 *
4
 * Copyright (C) 2011 John (J5) Palmieri <johnp@redhat.com>,  Red Hat, Inc.
5
 *
6
 *   pygi-marshal-from-py.c: Functions to convert PyObjects to C types.
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
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
 * USA
 */

#include "pygi-private.h"

#include <string.h>
#include <time.h>
#include <pygobject.h>
#include <pyglib-python-compat.h>

#include "pygi-cache.h"
32
#include "pygi-marshal-cleanup.h"
33
#include "pygi-marshal-from-py.h"
34

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#ifdef _WIN32
#ifdef _MSC_VER
#include <math.h>

#ifndef NAN
static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff};
#define NAN (*(const float *) __nan)
#endif

#ifndef INFINITY
#define INFINITY HUGE_VAL
#endif

#endif
#endif

51
static gboolean
David Malcolm's avatar
David Malcolm committed
52 53 54 55 56 57 58
gi_argument_from_py_ssize_t (GIArgument   *arg_out,
                             Py_ssize_t    size_in,
                             GITypeTag     type_tag)                             
{
    switch (type_tag) {
    case GI_TYPE_TAG_VOID:
    case GI_TYPE_TAG_BOOLEAN:
59 60
        goto unhandled_type;

David Malcolm's avatar
David Malcolm committed
61
    case GI_TYPE_TAG_INT8:
62 63 64 65 66 67 68
        if (size_in >= G_MININT8 && size_in <= G_MAXINT8) {
            arg_out->v_int8 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

David Malcolm's avatar
David Malcolm committed
69
    case GI_TYPE_TAG_UINT8:
70 71 72 73 74 75 76
        if (size_in >= 0 && size_in <= G_MAXUINT8) {
            arg_out->v_uint8 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

David Malcolm's avatar
David Malcolm committed
77
    case GI_TYPE_TAG_INT16:
78 79 80 81 82 83 84
        if (size_in >= G_MININT16 && size_in <= G_MAXINT16) {
            arg_out->v_int16 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

David Malcolm's avatar
David Malcolm committed
85
    case GI_TYPE_TAG_UINT16:
86 87 88 89 90 91
        if (size_in >= 0 && size_in <= G_MAXUINT16) {
            arg_out->v_uint16 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }
David Malcolm's avatar
David Malcolm committed
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

        /* Ranges assume two's complement */
    case GI_TYPE_TAG_INT32:
        if (size_in >= G_MININT32 && size_in <= G_MAXINT32) {
            arg_out->v_int32 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

    case GI_TYPE_TAG_UINT32:
        if (size_in >= 0 && size_in <= G_MAXUINT32) {
            arg_out->v_uint32 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

    case GI_TYPE_TAG_INT64:
        arg_out->v_int64 = size_in;
        return TRUE;

    case GI_TYPE_TAG_UINT64:
        if (size_in >= 0) {
            arg_out->v_uint64 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }
            
    case GI_TYPE_TAG_FLOAT:
    case GI_TYPE_TAG_DOUBLE:
    case GI_TYPE_TAG_GTYPE:
    case GI_TYPE_TAG_UTF8:
    case GI_TYPE_TAG_FILENAME:
    case GI_TYPE_TAG_ARRAY:
    case GI_TYPE_TAG_INTERFACE:
    case GI_TYPE_TAG_GLIST:
    case GI_TYPE_TAG_GSLIST:
    case GI_TYPE_TAG_GHASH:
    case GI_TYPE_TAG_ERROR:
    case GI_TYPE_TAG_UNICHAR:
    default:
        goto unhandled_type;
    }

 overflow:
    PyErr_Format (PyExc_OverflowError,
                  "Unable to marshal C Py_ssize_t %zd to %s",
                  size_in,
                  g_type_tag_to_string (type_tag));
    return FALSE;

 unhandled_type:
    PyErr_Format (PyExc_TypeError,
                  "Unable to marshal C Py_ssize_t %zd to %s",
                  size_in,
                  g_type_tag_to_string (type_tag));
    return FALSE;
}

153
static gboolean
David Malcolm's avatar
David Malcolm committed
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
gi_argument_from_c_long (GIArgument *arg_out,
                         long        c_long_in,
                         GITypeTag   type_tag)
{
    switch (type_tag) {
      case GI_TYPE_TAG_INT8:
          arg_out->v_int8 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT8:
          arg_out->v_uint8 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_INT16:
          arg_out->v_int16 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT16:
          arg_out->v_uint16 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_INT32:
          arg_out->v_int32 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT32:
          arg_out->v_uint32 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_INT64:
          arg_out->v_int64 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT64:
          arg_out->v_uint64 = c_long_in;
          return TRUE;
      default:
          PyErr_Format (PyExc_TypeError,
                        "Unable to marshal C long %ld to %s",
                        c_long_in,
                        g_type_tag_to_string (type_tag));
          return FALSE;
    }
}

192 193 194 195 196
/*
 * _is_union_member - check to see if the py_arg is actually a member of the
 * expected C union
 */
static gboolean
197
_is_union_member (GIInterfaceInfo *interface_info, PyObject *py_arg) {
198 199 200 201 202 203
    gint i;
    gint n_fields;
    GIUnionInfo *union_info;
    GIInfoType info_type;
    gboolean is_member = FALSE;

204
    info_type = g_base_info_get_type (interface_info);
205 206 207 208

    if (info_type != GI_INFO_TYPE_UNION)
        return FALSE;

209
    union_info = (GIUnionInfo *) interface_info;
210 211 212 213 214 215 216 217 218 219 220
    n_fields = g_union_info_get_n_fields (union_info);

    for (i = 0; i < n_fields; i++) {
        GIFieldInfo *field_info;
        GITypeInfo *field_type_info;

        field_info = g_union_info_get_field (union_info, i);
        field_type_info = g_field_info_get_type (field_info);

        /* we can only check if the members are interfaces */
        if (g_type_info_get_tag (field_type_info) == GI_TYPE_TAG_INTERFACE) {
221
            GIInterfaceInfo *field_iface_info;
222 223
            PyObject *py_type;

224 225
            field_iface_info = g_type_info_get_interface (field_type_info);
            py_type = _pygi_type_import_by_gi_info ((GIBaseInfo *) field_iface_info);
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

            if (py_type != NULL && PyObject_IsInstance (py_arg, py_type)) {
                is_member = TRUE;
            }

            Py_XDECREF (py_type);
            g_base_info_unref ( ( GIBaseInfo *) field_iface_info);
        }

        g_base_info_unref ( ( GIBaseInfo *) field_type_info);
        g_base_info_unref ( ( GIBaseInfo *) field_info);

        if (is_member)
            break;
    }

    return is_member;
}

245
gboolean
246 247 248 249
_pygi_marshal_from_py_array (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
250 251
                             GIArgument        *arg,
                             gpointer          *cleanup_data)
252
{
253
    PyGIMarshalFromPyFunc from_py_marshaller;
254
    int i = 0;
255
    int success_count = 0;
256
    Py_ssize_t length;
257
    gssize item_size;
258
    gboolean is_ptr_array;
259 260
    GArray *array_ = NULL;
    PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;
261
    PyGIArgGArray *array_cache = (PyGIArgGArray *)arg_cache;
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278


    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

    if (!PySequence_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

    length = PySequence_Length (py_arg);
    if (length < 0)
        return FALSE;

279 280
    if (array_cache->fixed_size >= 0 &&
            array_cache->fixed_size != length) {
281
        PyErr_Format (PyExc_ValueError, "Must contain %zd items, not %zd",
282
                      array_cache->fixed_size, length);
283 284 285 286

        return FALSE;
    }

287 288
    item_size = array_cache->item_size;
    is_ptr_array = (array_cache->array_type == GI_ARRAY_TYPE_PTR_ARRAY);
289
    if (is_ptr_array) {
290
        array_ = (GArray *)g_ptr_array_sized_new (length);
291
    } else {
292
        array_ = g_array_sized_new (array_cache->is_zero_terminated,
293
                                    TRUE,
294
                                    item_size,
295 296
                                    length);
    }
297 298

    if (array_ == NULL) {
299
        PyErr_NoMemory ();
300 301 302 303
        return FALSE;
    }

    if (sequence_cache->item_cache->type_tag == GI_TYPE_TAG_UINT8 &&
304 305
        PYGLIB_PyBytes_Check (py_arg)) {
        memcpy(array_->data, PYGLIB_PyBytes_AsString (py_arg), length);
Martin Pitt's avatar
Martin Pitt committed
306
        array_->len = length;
307
        if (array_cache->is_zero_terminated) {
308 309 310 311
            /* If array_ has been created with zero_termination, space for the
             * terminator is properly allocated, so we're not off-by-one here. */
            array_->data[length] = '\0';
        }
312 313 314
        goto array_success;
    }

315
    from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
316 317
    for (i = 0, success_count = 0; i < length; i++) {
        GIArgument item = {0};
318
        gpointer item_cleanup_data = NULL;
319 320 321 322
        PyObject *py_item = PySequence_GetItem (py_arg, i);
        if (py_item == NULL)
            goto err;

323 324 325 326
        if (!from_py_marshaller ( state,
                                  callable_cache,
                                  sequence_cache->item_cache,
                                  py_item,
327 328
                                 &item,
                                 &item_cleanup_data)) {
329
            Py_DECREF (py_item);
330
            goto err;
331 332
        }
        Py_DECREF (py_item);
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

        if (item_cleanup_data != NULL && item_cleanup_data != item.v_pointer) {
            /* We only support one level of data discrepancy between an items
             * data and its cleanup data. This is because we only track a single
             * extra cleanup data pointer per-argument and cannot track the entire
             * array of items differing data and cleanup_data.
             * For example, this would fail if trying to marshal an array of
             * callback closures marked with SCOPE call type where the cleanup data
             * is different from the items v_pointer, likewise an array of arrays.
             */
            PyErr_SetString(PyExc_RuntimeError, "Cannot cleanup item data for array due to "
                                                "the items data its cleanup data being different.");
            goto err;
        }

348 349 350 351
        /* FIXME: it is much more efficent to have seperate marshaller
         *        for ptr arrays than doing the evaluation
         *        and casting each loop iteration
         */
352
        if (is_ptr_array) {
353
            g_ptr_array_add((GPtrArray *)array_, item.v_pointer);
354 355 356 357
        } else if (sequence_cache->item_cache->is_pointer) {
            /* if the item is a pointer, simply copy the pointer */
            g_assert (item_size == sizeof (item.v_pointer));
            g_array_insert_val (array_, i, item);
358
        } else if (sequence_cache->item_cache->type_tag == GI_TYPE_TAG_INTERFACE) {
359
            /* Special case handling of flat arrays of gvalue/boxed/struct */
360 361 362 363 364 365 366 367 368 369
            PyGIInterfaceCache *item_iface_cache = (PyGIInterfaceCache *) sequence_cache->item_cache;
            GIBaseInfo *base_info = (GIBaseInfo *) item_iface_cache->interface_info;
            GIInfoType info_type = g_base_info_get_type (base_info);

            switch (info_type) {
                case GI_INFO_TYPE_UNION:
                case GI_INFO_TYPE_STRUCT:
                {
                    PyGIArgCache *item_arg_cache = (PyGIArgCache *)item_iface_cache;
                    PyGIMarshalCleanupFunc from_py_cleanup = item_arg_cache->from_py_cleanup;
370 371 372

                    if (g_type_is_a (item_iface_cache->g_type, G_TYPE_VALUE)) {
                        /* Special case GValue flat arrays to properly init and copy the contents. */
373 374
                        GValue* dest = (GValue*) (array_->data + (i * item_size));
                        if (item.v_pointer != NULL) {
375
                            memset (dest, 0, item_size);
376 377 378
                            g_value_init (dest, G_VALUE_TYPE ((GValue*) item.v_pointer));
                            g_value_copy ((GValue*) item.v_pointer, dest);
                        }
379 380
                        /* Manually increment the length because we are manually setting the memory. */
                        array_->len++;
381

382
                    } else {
383 384
                        /* Handles flat arrays of boxed or struct types. */
                        g_array_insert_vals (array_, i, item.v_pointer, 1);
385
                    }
386 387 388 389 390 391

                    /* Cleanup any memory left by the per-item marshaler because
                     * _pygi_marshal_cleanup_from_py_array will not know about this
                     * due to "item" being a temporarily marshaled value done on the stack.
                     */
                    if (from_py_cleanup)
392
                        from_py_cleanup (state, item_arg_cache, py_item, item_cleanup_data, TRUE);
393

394 395 396 397 398 399
                    break;
                }
                default:
                    g_array_insert_val (array_, i, item);
            }
        } else {
400
            /* default value copy of a simple type */
401
            g_array_insert_val (array_, i, item);
402
        }
403

404
        success_count++;
405 406
        continue;
err:
407
        if (sequence_cache->item_cache->from_py_cleanup != NULL) {
408 409
            gsize j;
            PyGIMarshalCleanupFunc cleanup_func =
410
                sequence_cache->item_cache->from_py_cleanup;
411

412 413 414 415 416 417 418 419 420 421 422 423 424
            /* Only attempt per item cleanup on pointer items */
            if (sequence_cache->item_cache->is_pointer) {
                for(j = 0; j < success_count; j++) {
                    PyObject *py_item = PySequence_GetItem (py_arg, j);
                    cleanup_func (state,
                                  sequence_cache->item_cache,
                                  py_item,
                                  is_ptr_array ?
                                          g_ptr_array_index ((GPtrArray *)array_, j) :
                                          g_array_index (array_, gpointer, j),
                                  TRUE);
                    Py_DECREF (py_item);
                }
425
            }
426 427
        }

428
        if (is_ptr_array)
429
            g_ptr_array_free ( ( GPtrArray *)array_, TRUE);
430 431
        else
            g_array_free (array_, TRUE);
432 433 434 435 436
        _PyGI_ERROR_PREFIX ("Item %i: ", i);
        return FALSE;
    }

array_success:
437
    if (array_cache->len_arg_index >= 0) {
438 439
        /* we have an child arg to handle */
        PyGIArgCache *child_cache =
440
            _pygi_callable_cache_get_arg (callable_cache, array_cache->len_arg_index);
441

442
        if (child_cache->direction == PYGI_DIRECTION_BIDIRECTIONAL) {
443
            gint *len_arg = (gint *)state->in_args[child_cache->c_arg_index].v_pointer;
444
            /* if we are not setup yet just set the in arg */
David Malcolm's avatar
David Malcolm committed
445 446 447 448 449 450 451
            if (len_arg == NULL) {
                if (!gi_argument_from_py_ssize_t (&state->in_args[child_cache->c_arg_index],
                                                  length,
                                                  child_cache->type_tag)) {
                    goto err;
                }
            } else {
452
                *len_arg = length;
David Malcolm's avatar
David Malcolm committed
453
            }
454
        } else {
David Malcolm's avatar
David Malcolm committed
455 456 457 458 459
            if (!gi_argument_from_py_ssize_t (&state->in_args[child_cache->c_arg_index],
                                              length,
                                              child_cache->type_tag)) {
                goto err;
            }
460 461 462
        }
    }

463
    if (array_cache->array_type == GI_ARRAY_TYPE_C) {
464 465 466 467
        /* In the case of GI_ARRAY_C, we give the data directly as the argument
         * but keep the array_ wrapper as cleanup data so we don't have to find
         * it's length again.
         */
468
        arg->v_pointer = array_->data;
469 470 471 472 473 474 475

        if (arg_cache->transfer == GI_TRANSFER_EVERYTHING) {
            g_array_free (array_, FALSE);
            *cleanup_data = NULL;
        } else {
            *cleanup_data = array_;
        }
476 477 478
    } else {
        arg->v_pointer = array_;

479 480 481 482 483 484 485 486 487 488 489 490 491 492
        if (arg_cache->transfer == GI_TRANSFER_NOTHING) {
            /* Free everything in cleanup. */
            *cleanup_data = array_;
        } else if (arg_cache->transfer == GI_TRANSFER_CONTAINER) {
            /* Make a shallow copy so we can free the elements later in cleanup
             * because it is possible invoke will free the list before our cleanup. */
            *cleanup_data = is_ptr_array ?
                    (gpointer)g_ptr_array_ref ((GPtrArray *)array_) :
                    (gpointer)g_array_ref (array_);
        } else { /* GI_TRANSFER_EVERYTHING */
            /* No cleanup, everything is given to the callee. */
            *cleanup_data = NULL;
        }
    }
493

494 495 496 497
    return TRUE;
}

gboolean
498 499 500 501
_pygi_marshal_from_py_glist (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
502 503
                             GIArgument        *arg,
                             gpointer          *cleanup_data)
504
{
505
    PyGIMarshalFromPyFunc from_py_marshaller;
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    int i;
    Py_ssize_t length;
    GList *list_ = NULL;
    PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;


    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

    if (!PySequence_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

523
    length = PySequence_Length (py_arg);
524 525 526
    if (length < 0)
        return FALSE;

527
    from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
528
    for (i = 0; i < length; i++) {
529 530
        GIArgument item = {0};
        gpointer item_cleanup_data = NULL;
531 532 533 534
        PyObject *py_item = PySequence_GetItem (py_arg, i);
        if (py_item == NULL)
            goto err;

535 536 537 538
        if (!from_py_marshaller ( state,
                                  callable_cache,
                                  sequence_cache->item_cache,
                                  py_item,
539 540
                                 &item,
                                 &item_cleanup_data))
541 542
            goto err;

543
        Py_DECREF (py_item);
544
        list_ = g_list_prepend (list_, _pygi_arg_to_hash_pointer (&item, sequence_cache->item_cache->type_tag));
545 546
        continue;
err:
John (J5) Palmieri's avatar
John (J5) Palmieri committed
547
        /* FIXME: clean up list
548 549
        if (sequence_cache->item_cache->from_py_cleanup != NULL) {
            PyGIMarshalCleanupFunc cleanup = sequence_cache->item_cache->from_py_cleanup;
550
        }
John (J5) Palmieri's avatar
John (J5) Palmieri committed
551
        */
552
        Py_DECREF (py_item);
553
        g_list_free (list_);
554 555 556 557
        _PyGI_ERROR_PREFIX ("Item %i: ", i);
        return FALSE;
    }

558
    arg->v_pointer = g_list_reverse (list_);
559 560 561 562 563 564 565 566 567 568 569 570

    if (arg_cache->transfer == GI_TRANSFER_NOTHING) {
        /* Free everything in cleanup. */
        *cleanup_data = arg->v_pointer;
    } else if (arg_cache->transfer == GI_TRANSFER_CONTAINER) {
        /* Make a shallow copy so we can free the elements later in cleanup
         * because it is possible invoke will free the list before our cleanup. */
        *cleanup_data = g_list_copy (arg->v_pointer);
    } else { /* GI_TRANSFER_EVERYTHING */
        /* No cleanup, everything is given to the callee. */
        *cleanup_data = NULL;
    }
571 572 573 574
    return TRUE;
}

gboolean
575 576 577 578
_pygi_marshal_from_py_gslist (PyGIInvokeState   *state,
                              PyGICallableCache *callable_cache,
                              PyGIArgCache      *arg_cache,
                              PyObject          *py_arg,
579 580
                              GIArgument        *arg,
                              gpointer          *cleanup_data)
581
{
582
    PyGIMarshalFromPyFunc from_py_marshaller;
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
    int i;
    Py_ssize_t length;
    GSList *list_ = NULL;
    PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;

    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

    if (!PySequence_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

599
    length = PySequence_Length (py_arg);
600 601 602
    if (length < 0)
        return FALSE;

603
    from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
604
    for (i = 0; i < length; i++) {
605 606
        GIArgument item = {0};
        gpointer item_cleanup_data = NULL;
607 608 609 610
        PyObject *py_item = PySequence_GetItem (py_arg, i);
        if (py_item == NULL)
            goto err;

611
        if (!from_py_marshaller ( state,
612 613 614
                             callable_cache,
                             sequence_cache->item_cache,
                             py_item,
615 616
                            &item,
                            &item_cleanup_data))
617 618
            goto err;

619
        Py_DECREF (py_item);
620
        list_ = g_slist_prepend (list_, _pygi_arg_to_hash_pointer (&item, sequence_cache->item_cache->type_tag));
621 622
        continue;
err:
John (J5) Palmieri's avatar
John (J5) Palmieri committed
623
        /* FIXME: Clean up list
624 625
        if (sequence_cache->item_cache->from_py_cleanup != NULL) {
            PyGIMarshalCleanupFunc cleanup = sequence_cache->item_cache->from_py_cleanup;
626
        }
John (J5) Palmieri's avatar
John (J5) Palmieri committed
627
        */
628

629
        Py_DECREF (py_item);
630
        g_slist_free (list_);
631 632 633 634
        _PyGI_ERROR_PREFIX ("Item %i: ", i);
        return FALSE;
    }

635
    arg->v_pointer = g_slist_reverse (list_);
636 637 638 639 640 641 642 643 644 645 646 647 648

    if (arg_cache->transfer == GI_TRANSFER_NOTHING) {
        /* Free everything in cleanup. */
        *cleanup_data = arg->v_pointer;
    } else if (arg_cache->transfer == GI_TRANSFER_CONTAINER) {
        /* Make a shallow copy so we can free the elements later in cleanup
         * because it is possible invoke will free the list before our cleanup. */
        *cleanup_data = g_slist_copy (arg->v_pointer);
    } else { /* GI_TRANSFER_EVERYTHING */
        /* No cleanup, everything is given to the callee. */
        *cleanup_data = NULL;
    }

649 650 651 652 653
    return TRUE;
}


gboolean
654 655 656 657
_pygi_marshal_from_py_gerror (PyGIInvokeState   *state,
                              PyGICallableCache *callable_cache,
                              PyGIArgCache      *arg_cache,
                              PyObject          *py_arg,
658 659
                              GIArgument        *arg,
                              gpointer          *cleanup_data)
660
{
661 662
    PyErr_Format (PyExc_NotImplementedError,
                  "Marshalling for GErrors is not implemented");
663 664 665
    return FALSE;
}

666 667 668 669 670 671 672 673 674
/* _pygi_destroy_notify_dummy:
 *
 * Dummy method used in the occasion when a method has a GDestroyNotify
 * argument without user data.
 */
static void
_pygi_destroy_notify_dummy (gpointer data) {
}

675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
static PyGICClosure *global_destroy_notify;

static void
_pygi_destroy_notify_callback_closure (ffi_cif *cif,
                                       void *result,
                                       void **args,
                                       void *data)
{
    PyGICClosure *info = * (void**) (args[0]);

    g_assert (info);

    _pygi_invoke_closure_free (info);
}

/* _pygi_destroy_notify_create:
 *
 * Method used in the occasion when a method has a GDestroyNotify
 * argument with user data.
 */
static PyGICClosure*
_pygi_destroy_notify_create (void)
{
    if (!global_destroy_notify) {

        PyGICClosure *destroy_notify = g_slice_new0 (PyGICClosure);
701
        GIBaseInfo* glib_destroy_notify;
702 703 704

        g_assert (destroy_notify);

705
        glib_destroy_notify = g_irepository_find_by_name (NULL, "GLib", "DestroyNotify");
706 707 708 709 710 711 712 713 714 715 716 717 718 719
        g_assert (glib_destroy_notify != NULL);
        g_assert (g_base_info_get_type (glib_destroy_notify) == GI_INFO_TYPE_CALLBACK);

        destroy_notify->closure = g_callable_info_prepare_closure ( (GICallableInfo*) glib_destroy_notify,
                                                                    &destroy_notify->cif,
                                                                    _pygi_destroy_notify_callback_closure,
                                                                    NULL);

        global_destroy_notify = destroy_notify;
    }

    return global_destroy_notify;
}

720
gboolean
721 722 723 724
_pygi_marshal_from_py_interface_callback (PyGIInvokeState   *state,
                                          PyGICallableCache *callable_cache,
                                          PyGIArgCache      *arg_cache,
                                          PyObject          *py_arg,
725 726
                                          GIArgument        *arg,
                                          gpointer          *cleanup_data)
727 728 729 730 731 732 733 734 735 736 737
{
    GICallableInfo *callable_info;
    PyGICClosure *closure;
    PyGIArgCache *user_data_cache = NULL;
    PyGIArgCache *destroy_cache = NULL;
    PyGICallbackCache *callback_cache;
    PyObject *py_user_data = NULL;

    callback_cache = (PyGICallbackCache *)arg_cache;

    if (callback_cache->user_data_index > 0) {
738
        user_data_cache = _pygi_callable_cache_get_arg (callable_cache, callback_cache->user_data_index);
739
        if (user_data_cache->py_arg_index < state->n_py_in_args) {
740
            /* py_user_data is a borrowed reference. */
741
            py_user_data = PyTuple_GetItem (state->py_in_args, user_data_cache->py_arg_index);
742 743
            if (!py_user_data)
                return FALSE;
744 745 746
            /* NULL out user_data if it was not supplied and the default arg placeholder
             * was used instead.
             */
747
            if (py_user_data == _PyGIDefaultArgPlaceholder) {
748
                py_user_data = NULL;
749 750 751 752 753 754 755 756 757 758 759
            } else if (callable_cache->user_data_varargs_index < 0) {
                /* For non-variable length user data, place the user data in a
                 * single item tuple which is concatenated to the callbacks arguments.
                 * This allows callback input arg marshaling to always expect a
                 * tuple for user data. Note the
                 */
                py_user_data = Py_BuildValue("(O)", py_user_data, NULL);
            } else {
                /* increment the ref borrowed from PyTuple_GetItem above */
                Py_INCREF (py_user_data);
            }
760 761 762 763 764 765 766
        }
    }

    if (py_arg == Py_None) {
        return TRUE;
    }

767 768 769 770
    if (!PyCallable_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError,
                      "Callback needs to be a function or method not %s",
                      py_arg->ob_type->tp_name);
771 772 773 774 775 776 777 778

        return FALSE;
    }

    callable_info = (GICallableInfo *)callback_cache->interface_info;

    closure = _pygi_make_native_closure (callable_info, callback_cache->scope, py_arg, py_user_data);
    arg->v_pointer = closure->closure;
779

780 781 782
    /* always decref the user data as _pygi_make_native_closure adds its own ref */
    Py_XDECREF (py_user_data);

783 784 785
    /* The PyGICClosure instance is used as user data passed into the C function.
     * The return trip to python will marshal this back and pull the python user data out.
     */
786 787 788 789
    if (user_data_cache != NULL) {
        state->in_args[user_data_cache->c_arg_index].v_pointer = closure;
    }

790 791 792 793 794 795 796 797
    /* Setup a GDestroyNotify callback if this method supports it along with
     * a user data field. The user data field is a requirement in order
     * free resources and ref counts associated with this arguments closure.
     * In case a user data field is not available, show a warning giving
     * explicit information and setup a dummy notification to avoid a crash
     * later on in _pygi_destroy_notify_callback_closure.
     */
    if (callback_cache->destroy_notify_index > 0) {
798
        destroy_cache = _pygi_callable_cache_get_arg (callable_cache, callback_cache->destroy_notify_index);
799 800
    }

801
    if (destroy_cache) {
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
        if (user_data_cache != NULL) {
            PyGICClosure *destroy_notify = _pygi_destroy_notify_create ();
            state->in_args[destroy_cache->c_arg_index].v_pointer = destroy_notify->closure;
        } else {
            gchar *msg = g_strdup_printf("Callables passed to %s will leak references because "
                                         "the method does not support a user_data argument. "
                                         "See: https://bugzilla.gnome.org/show_bug.cgi?id=685598",
                                         callable_cache->name);
            if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 2)) {
                g_free(msg);
                _pygi_invoke_closure_free(closure);
                return FALSE;
            }
            g_free(msg);
            state->in_args[destroy_cache->c_arg_index].v_pointer = _pygi_destroy_notify_dummy;
        }
818 819
    }

820 821
    /* Use the PyGIClosure as data passed to cleanup for GI_SCOPE_TYPE_CALL. */
    *cleanup_data = closure;
822

823 824 825 826
    return TRUE;
}

gboolean
827 828 829 830
_pygi_marshal_from_py_interface_enum (PyGIInvokeState   *state,
                                      PyGICallableCache *callable_cache,
                                      PyGIArgCache      *arg_cache,
                                      PyObject          *py_arg,
831 832
                                      GIArgument        *arg,
                                      gpointer          *cleanup_data)
833
{
David Malcolm's avatar
David Malcolm committed
834 835
    PyObject *py_long;
    long c_long;
836 837
    gint is_instance;
    PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;
838
    GIBaseInfo *interface = NULL;
839

840
    is_instance = PyObject_IsInstance (py_arg, iface_cache->py_type);
841

David Malcolm's avatar
David Malcolm committed
842 843
    py_long = PYGLIB_PyNumber_Long (py_arg);
    if (py_long == NULL) {
844 845 846 847
        PyErr_Clear();
        goto err;
    }

David Malcolm's avatar
David Malcolm committed
848 849 850 851 852 853 854 855 856 857
    c_long = PYGLIB_PyLong_AsLong (py_long);
    Py_DECREF (py_long);

    /* Write c_long into arg */
    interface = g_type_info_get_interface (arg_cache->type_info);
    assert(g_base_info_get_type (interface) == GI_INFO_TYPE_ENUM);
    if (!gi_argument_from_c_long(arg,
                                 c_long,
                                 g_enum_info_get_storage_type ((GIEnumInfo *)interface))) {
          g_assert_not_reached();
858
          g_base_info_unref (interface);
David Malcolm's avatar
David Malcolm committed
859 860
          return FALSE;
    }
861 862 863 864 865 866 867 868

    /* If this is not an instance of the Enum type that we want
     * we need to check if the value is equivilant to one of the
     * Enum's memebers */
    if (!is_instance) {
        int i;
        gboolean is_found = FALSE;

869
        for (i = 0; i < g_enum_info_get_n_values (iface_cache->interface_info); i++) {
870
            GIValueInfo *value_info =
871 872 873
                g_enum_info_get_value (iface_cache->interface_info, i);
            glong enum_value = g_value_info_get_value (value_info);
            g_base_info_unref ( (GIBaseInfo *)value_info);
David Malcolm's avatar
David Malcolm committed
874
            if (c_long == enum_value) {
875 876 877 878 879 880 881 882 883
                is_found = TRUE;
                break;
            }
        }

        if (!is_found)
            goto err;
    }

884
    g_base_info_unref (interface);
885 886 887
    return TRUE;

err:
888 889
    if (interface)
        g_base_info_unref (interface);
890 891
    PyErr_Format (PyExc_TypeError, "Expected a %s, but got %s",
                  iface_cache->type_name, py_arg->ob_type->tp_name);
892 893 894 895
    return FALSE;
}

gboolean
896 897 898 899
_pygi_marshal_from_py_interface_flags (PyGIInvokeState   *state,
                                       PyGICallableCache *callable_cache,
                                       PyGIArgCache      *arg_cache,
                                       PyObject          *py_arg,
900 901
                                       GIArgument        *arg,
                                       gpointer          *cleanup_data)
902
{
David Malcolm's avatar
David Malcolm committed
903 904
    PyObject *py_long;
    long c_long;
905 906
    gint is_instance;
    PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;
David Malcolm's avatar
David Malcolm committed
907
    GIBaseInfo *interface;
908

909
    is_instance = PyObject_IsInstance (py_arg, iface_cache->py_type);
910

David Malcolm's avatar
David Malcolm committed
911 912
    py_long = PYGLIB_PyNumber_Long (py_arg);
    if (py_long == NULL) {
913
        PyErr_Clear ();
914 915 916
        goto err;
    }

David Malcolm's avatar
David Malcolm committed
917 918
    c_long = PYGLIB_PyLong_AsLong (py_long);
    Py_DECREF (py_long);
919 920

    /* only 0 or argument of type Flag is allowed */
David Malcolm's avatar
David Malcolm committed
921
    if (!is_instance && c_long != 0)
922 923
        goto err;

David Malcolm's avatar
David Malcolm committed
924 925 926 927 928
    /* Write c_long into arg */
    interface = g_type_info_get_interface (arg_cache->type_info);
    g_assert (g_base_info_get_type (interface) == GI_INFO_TYPE_FLAGS);
    if (!gi_argument_from_c_long(arg, c_long,
                                 g_enum_info_get_storage_type ((GIEnumInfo *)interface))) {
929
        g_base_info_unref (interface);
David Malcolm's avatar
David Malcolm committed
930 931 932
        return FALSE;
    }

933
    g_base_info_unref (interface);
934 935 936 937 938 939 940 941 942 943
    return TRUE;

err:
    PyErr_Format (PyExc_TypeError, "Expected a %s, but got %s",
                  iface_cache->type_name, py_arg->ob_type->tp_name);
    return FALSE;

}

gboolean
944 945 946 947
_pygi_marshal_from_py_interface_struct_cache_adapter (PyGIInvokeState   *state,
                                                      PyGICallableCache *callable_cache,
                                                      PyGIArgCache      *arg_cache,
                                                      PyObject          *py_arg,
948 949
                                                      GIArgument        *arg,
                                                      gpointer          *cleanup_data)
950 951 952
{
    PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;

953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
    gboolean res =  _pygi_marshal_from_py_interface_struct (py_arg,
                                                            arg,
                                                            arg_cache->arg_name,
                                                            iface_cache->interface_info,
                                                            iface_cache->g_type,
                                                            iface_cache->py_type,
                                                            arg_cache->transfer,
                                                            TRUE, /*copy_reference*/
                                                            iface_cache->is_foreign,
                                                            arg_cache->is_pointer);

    /* Assume struct marshaling is always a pointer and assign cleanup_data
     * here rather than passing it further down the chain.
     */
    *cleanup_data = arg->v_pointer;
    return res;
969 970 971
}

gboolean
972 973 974 975
_pygi_marshal_from_py_interface_boxed (PyGIInvokeState   *state,
                                       PyGICallableCache *callable_cache,
                                       PyGIArgCache      *arg_cache,
                                       PyObject          *py_arg,
976 977
                                       GIArgument        *arg,
                                       gpointer          *cleanup_data)
978
{
979 980
    PyErr_Format (PyExc_NotImplementedError,
                  "Marshalling for this type is not implemented yet");
981 982 983 984
    return FALSE;
}

gboolean
985 986 987 988
_pygi_marshal_from_py_interface_object (PyGIInvokeState   *state,
                                        PyGICallableCache *callable_cache,
                                        PyGIArgCache      *arg_cache,
                                        PyObject          *py_arg,
989 990
                                        GIArgument        *arg,
                                        gpointer          *cleanup_data)
991
{
992 993
    gboolean res = FALSE;

994 995 996 997 998
    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

999
    if (!PyObject_IsInstance (py_arg, ( (PyGIInterfaceCache *)arg_cache)->py_type)) {
1000 1001
        PyObject *module = PyObject_GetAttrString(py_arg, "__module__");

1002
        PyErr_Format (PyExc_TypeError, "argument %s: Expected %s, but got %s%s%s",
1003
                      arg_cache->arg_name ? arg_cache->arg_name : "self",
1004
                      ( (PyGIInterfaceCache *)arg_cache)->type_name,
1005 1006
                      module ? PYGLIB_PyUnicode_AsString(module) : "",
                      module ? "." : "",
1007 1008 1009
                      py_arg->ob_type->tp_name);
        if (module)
            Py_DECREF (module);
1010 1011 1012
        return FALSE;
    }

1013 1014 1015
    res = _pygi_marshal_from_py_gobject (py_arg, arg, arg_cache->transfer);
    *cleanup_data = arg->v_pointer;
    return res;
1016 1017 1018
}

gboolean
1019 1020 1021 1022
_pygi_marshal_from_py_interface_union (PyGIInvokeState   *state,
                                       PyGICallableCache *callable_cache,
                                       PyGIArgCache      *arg_cache,
                                       PyObject          *py_arg,
1023 1024
                                       GIArgument        *arg,
                                       gpointer          *cleanup_data)
1025 1026 1027 1028 1029 1030
{
    PyErr_Format(PyExc_NotImplementedError,
                 "Marshalling for this type is not implemented yet");
    return FALSE;
}

1031
/* _pygi_marshal_from_py_gobject:
1032 1033 1034
 * py_arg: (in):
 * arg: (out):
 */
1035
gboolean
1036 1037 1038
_pygi_marshal_from_py_gobject (PyObject *py_arg, /*in*/
                               GIArgument *arg,  /*out*/
                               GITransfer transfer) {
1039 1040
    GObject *gobj;

1041
    if (py_arg == Py_None) {
1042 1043 1044 1045
        arg->v_pointer = NULL;
        return TRUE;
    }

1046 1047 1048 1049 1050 1051 1052 1053
    if (!pygobject_check (py_arg, &PyGObject_Type)) {
        PyObject *repr = PyObject_Repr (py_arg);
        PyErr_Format(PyExc_TypeError, "expected GObject but got %s",
                     PYGLIB_PyUnicode_AsString (repr));
        Py_DECREF (repr);
        return FALSE;
    }

1054
    gobj = pygobject_get (py_arg);
1055
    if (transfer == GI_TRANSFER_EVERYTHING) {
1056 1057
        /* For transfer everything, add a new ref that the callee will take ownership of.
         * Pythons existing ref to the GObject will be managed with the PyGObject wrapper.
1058 1059
         */
        g_object_ref (gobj);
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    }

    arg->v_pointer = gobj;
    return TRUE;
}

/* _pygi_marshal_from_py_gobject_out_arg:
 * py_arg: (in):
 * arg: (out):
 *
 * A specialization for marshaling Python GObjects used for out/return values
 * from a Python implemented vfuncs, signals, or an assignment to a GObject property.
 */
gboolean
_pygi_marshal_from_py_gobject_out_arg (PyObject *py_arg, /*in*/
                                       GIArgument *arg,  /*out*/
                                       GITransfer transfer) {
    GObject *gobj;
    if (!_pygi_marshal_from_py_gobject (py_arg, arg, transfer)) {
        return FALSE;
    }
1081

1082 1083 1084 1085 1086 1087
    /* HACK: At this point the basic marshaling of the GObject was successful
     * but we add some special case hacks for vfunc returns due to buggy APIs:
     * https://bugzilla.gnome.org/show_bug.cgi?id=693393
     */
    gobj = arg->v_pointer;
    if (py_arg->ob_refcnt == 1 && gobj->ref_count == 1) {
1088 1089 1090 1091 1092 1093 1094
        /* If both object ref counts are only 1 at this point (the reference held
         * in a return tuple), we assume the GObject will be free'd before reaching
         * its target and become invalid. So instead of getting invalid object errors
         * we add a new GObject ref.
         */
        g_object_ref (gobj);

1095
        if (((PyGObject *)py_arg)->private_flags.flags & PYGOBJECT_GOBJECT_WAS_FLOATING) {
1096
            /*
1097