peas-plugin-loader-lua.c 14.2 KB
Newer Older
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
/*
 * peas-plugin-loader-lua.c
 * This file is part of libpeas
 *
 * Copyright (C) 2014 - Garrett Regier
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Library General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "peas-plugin-loader-lua.h"
27
#include "libpeas/peas-plugin-info-priv.h"
28 29 30 31 32 33 34 35 36 37

#include <string.h>

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

#include "peas-plugin-loader-lua-utils.h"


38 39 40
typedef void (* LgiLockFunc) (gpointer lgi_lock);


41
typedef struct {
42
  lua_State *L;
43 44 45 46

  gpointer lgi_lock;
  LgiLockFunc lgi_enter_func;
  LgiLockFunc lgi_leave_func;
47
} PeasPluginLoaderLuaPrivate;
48

49 50 51 52 53 54
G_DEFINE_TYPE_WITH_PRIVATE (PeasPluginLoaderLua,
                            peas_plugin_loader_lua,
                            PEAS_TYPE_PLUGIN_LOADER)

#define GET_PRIV(o) \
  (peas_plugin_loader_lua_get_instance_private (o))
55

56 57 58
static
G_DEFINE_QUARK (peas-extension-type, extension_type)

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
G_MODULE_EXPORT void
peas_register_types (PeasObjectModule *module)
{
  peas_object_module_register_extension_type (module,
                                              PEAS_TYPE_PLUGIN_LOADER,
                                              PEAS_TYPE_PLUGIN_LOADER_LUA);
}

static gboolean
_lua_add_package_path (lua_State   *L,
                       const gchar *package_path)
{
  luaL_checkstack (L, 3, "");

  lua_getglobal (L, "package");
  lua_getfield (L, -1, "path");

  if (!lua_isstring (L, -1))
    {
      g_warning ("Invalid Lua package.path: %s", lua_tostring (L, -1));

      /* Pop path and package */
      lua_pop (L, 2);
      return FALSE;
    }

  /* ";package_path/?.lua;package_path/?/init.lua" */
  lua_pushliteral (L, ";");
  lua_pushstring (L, package_path);
  lua_pushliteral (L, G_DIR_SEPARATOR_S "?.lua;");
  lua_pushstring (L, package_path);
  lua_pushliteral (L, G_DIR_SEPARATOR_S "?" G_DIR_SEPARATOR_S "init.lua");
  lua_concat (L, 5);

  if (strstr (lua_tostring (L, -2), lua_tostring (L, -1)) != NULL)
    {
      /* Pop new path and path */
      lua_pop (L, 2);
    }
  else
    {
      /* Update package.path */
      lua_concat (L, 2);
      lua_setfield (L, -2, "path");
    }

  /* Pop package */
  lua_pop (L, 1);
  return TRUE;
}

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
static gboolean
_lua_has_package (lua_State   *L,
                  const gchar *package_name)
{
  gboolean has_package;

  luaL_checkstack (L, 3, "");

  lua_getglobal (L, "package");
  lua_getfield (L, -1, "loaded");
  lua_getfield (L, -1, package_name);

  has_package = !lua_isnil (L, -1);

  /* Pop package, loaded and package's table */
  lua_pop (L, 3);
  return has_package;
}

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
static gboolean
_lua_pushinstance (lua_State   *L,
                   const gchar *namespace_,
                   const gchar *name,
                   GType        gtype,
                   gpointer     instance)
{
  luaL_checkstack (L, 3, "");

  if (!peas_lua_utils_require (L, "lgi"))
    return FALSE;

  lua_getfield (L, -1, namespace_);
  lua_getfield (L, -1, name);

  /* Remove the namespace and lgi's module table */
  lua_replace (L, -2);
  lua_replace (L, -2);

  lua_pushlightuserdata (L, instance);
  lua_pushboolean (L, FALSE);

  /* new(addr[, already_own[, no_sink]]) */
  if (lua_pcall (L, 2, 1, 0) != 0)
    {
      g_warning ("Failed to create Lua object of type '%s': %s",
                 g_type_name (gtype), lua_tostring (L, -1));

      /* Pop the error */
      lua_pop (L, 1);
      return FALSE;
    }

  /* Check that the Lua object was created correctly */
  lua_getfield (L, -1, "_native");
  g_assert (lua_islightuserdata (L, -1));
  g_assert (lua_touserdata (L, -1) == instance);
  lua_pop (L, 1);

  return TRUE;
}

static GType
_lua_get_gtype (lua_State *L,
                int        index)
{
  GType gtype = G_TYPE_INVALID;

  luaL_checkstack (L, 1, "");

  lua_getfield (L, index, "_gtype");

  if (lua_type (L, -1) == LUA_TLIGHTUSERDATA)
    gtype = (GType) lua_touserdata (L, -1);

  /* Pop _gtype */
  lua_pop (L, 1);
  return gtype;
}

static GType
_lua_find_extension_type (lua_State      *L,
                          PeasPluginInfo *info,
                          GType           exten_type)
{
  GType found_type = G_TYPE_INVALID;

  luaL_checkstack (L, 3, "");

  /* Get the module's table */
199
  lua_pushstring (L, info->filename);
200 201 202 203
  lua_rawget (L, LUA_REGISTRYINDEX);

  /* Must always have a valid key */
  lua_pushnil (L);
204
  while (lua_next (L, -2) != 0)
205 206 207 208 209
    {
      if (lua_istable (L, -1))
        {
          found_type = _lua_get_gtype (L, -1);

210
          if (found_type != G_TYPE_INVALID)
211
            {
212 213 214 215 216 217 218 219 220 221
              if (!g_type_is_a (found_type, exten_type))
                {
                  found_type = G_TYPE_INVALID;
                }
              else
                {
                  /* Pop value and key */
                  lua_pop (L, 2);
                  break;
                }
222 223 224 225 226 227 228 229 230 231 232 233
            }
        }

      /* Pop the value but keep the key for the next iteration */
      lua_pop (L, 1);
    }

  /* Pop the module's table */
  lua_pop (L, 1);
  return found_type;
}

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
static lua_State *
thread_enter (PeasPluginLoaderLua *lua_loader,
              PeasPluginInfo      *info)
{
  PeasPluginLoaderLuaPrivate *priv = GET_PRIV (lua_loader);
  lua_State *L = priv->L;
  lua_State *NL = info->loader_data;

  priv->lgi_enter_func (priv->lgi_lock);

  if (NL != NULL)
    {
      /* We should never have multiple values on the stack */
      g_assert_cmpint (lua_gettop (NL), ==, 0);
    }
  else
    {
      luaL_checkstack (L, 2, "");

      lua_pushlightuserdata (L, info);
      NL = lua_newthread (L);
      lua_rawset (L, LUA_REGISTRYINDEX);

      info->loader_data = NL;
    }

  return NL;
}

static void
thread_leave (PeasPluginLoaderLua  *lua_loader,
              PeasPluginInfo       *info,
              lua_State           **L_ptr)
{
  PeasPluginLoaderLuaPrivate *priv = GET_PRIV (lua_loader);
  lua_State *L = info->loader_data;

  g_assert (*L_ptr == L);
  *L_ptr = NULL;

  /* The stack should always be empty */
  g_assert_cmpint (lua_gettop (L), ==, 0);

  priv->lgi_leave_func (priv->lgi_lock);
}

280 281 282 283 284 285
static gboolean
peas_plugin_loader_lua_provides_extension (PeasPluginLoader *loader,
                                           PeasPluginInfo   *info,
                                           GType             exten_type)
{
  PeasPluginLoaderLua *lua_loader = PEAS_PLUGIN_LOADER_LUA (loader);
286
  lua_State *L;
287 288
  GType extension_type;

289 290
  L = thread_enter (lua_loader, info);

291 292
  extension_type = _lua_find_extension_type (L, info, exten_type);

293
  thread_leave (lua_loader, info, &L);
294 295 296 297 298 299 300 301 302 303 304
  return extension_type != G_TYPE_INVALID;
}

static PeasExtension *
peas_plugin_loader_lua_create_extension (PeasPluginLoader *loader,
                                         PeasPluginInfo   *info,
                                         GType             exten_type,
                                         guint             n_parameters,
                                         GParameter       *parameters)
{
  PeasPluginLoaderLua *lua_loader = PEAS_PLUGIN_LOADER_LUA (loader);
305
  lua_State *L;
306
  GType the_type;
307 308
  GObject *object = NULL;

309
  L = thread_enter (lua_loader, info);
310 311 312

  the_type = _lua_find_extension_type (L, info, exten_type);
  if (the_type == G_TYPE_INVALID)
313
    goto out;
314 315 316 317

  if (!g_type_is_a (the_type, exten_type))
    {
      g_warn_if_fail (g_type_is_a (the_type, exten_type));
318
      goto out;
319 320 321 322
    }

  object = g_object_newv (the_type, n_parameters, parameters);
  if (object == NULL)
323
    goto out;
324

325 326
  /* We have to remember which interface we are instantiating
   * for the deprecated peas_extension_get_extension_type().
327
   */
328 329
  g_object_set_qdata (object, extension_type_quark (),
                      GSIZE_TO_POINTER (exten_type));
330 331 332 333 334 335

  luaL_checkstack (L, 3, "");

  if (!_lua_pushinstance (L, "GObject", "Object", the_type, object))
    {
      g_clear_object (&object);
336
      goto out;
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    }

  lua_getfield (L, -1, "priv");

  if (!_lua_pushinstance (L, "Peas", "PluginInfo",
                          PEAS_TYPE_PLUGIN_INFO, info))
    {
      g_clear_object (&object);
    }
  else
    {
      /* Set the plugin info as self.priv.plugin_info */
      lua_setfield (L, -2, "plugin_info");
    }

  /* Pop priv and object */
  lua_pop (L, 2);

355 356
out:

357
  thread_leave (lua_loader, info, &L);
358 359 360 361 362 363 364 365
  return object;
}

static gboolean
peas_plugin_loader_lua_load (PeasPluginLoader *loader,
                             PeasPluginInfo   *info)
{
  PeasPluginLoaderLua *lua_loader = PEAS_PLUGIN_LOADER_LUA (loader);
366
  lua_State *L;
367 368
  gboolean success;

369
  L = thread_enter (lua_loader, info);
370

371 372 373
  luaL_checkstack (L, 2, "");

  /* Get the module's table */
374
  lua_pushstring (L, info->filename);
375 376 377 378 379 380 381 382 383 384 385 386 387 388
  lua_rawget (L, LUA_REGISTRYINDEX);

  if (!lua_isnil (L, -1))
    {
      success = lua_istable (L, -1);
    }
  else
    {
      const gchar *module_dir, *module_name;

      module_dir = peas_plugin_info_get_module_dir (info);
      module_name = peas_plugin_info_get_module_name (info);

      /* Must push the key back onto the stack */
389
      lua_pushstring (L, info->filename);
390

391 392 393 394 395 396 397 398 399 400 401
      /* Push something that isn't a table */
      lua_pushboolean (L, FALSE);

      if (_lua_has_package (L, module_name))
        {
          g_warning ("Error loading plugin '%s': "
                     "module name '%s' has already been used",
                     info->filename, module_name);
        }
      else if (_lua_add_package_path (L, module_dir) &&
               peas_lua_utils_require (L, module_name))
402
        {
403 404
          /* Remove the boolean */
          lua_replace (L, -2);
405 406 407 408 409 410 411 412 413
        }

      success = lua_istable (L, -1);
      lua_rawset (L, LUA_REGISTRYINDEX);
    }

  /* Pop the module's table */
  lua_pop (L, 1);

414
  thread_leave (lua_loader, info, &L);
415 416 417 418 419 420 421
  return success;
}

static void
peas_plugin_loader_lua_unload (PeasPluginLoader *loader,
                               PeasPluginInfo   *info)
{
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
  PeasPluginLoaderLua *lua_loader = PEAS_PLUGIN_LOADER_LUA (loader);
  PeasPluginLoaderLuaPrivate *priv = GET_PRIV (lua_loader);
  lua_State *L = priv->L;

  priv->lgi_enter_func (priv->lgi_lock);

  /* The stack should always be empty */
  g_assert_cmpint (lua_gettop (info->loader_data), ==, 0);

  /* Delete the thread's reference */
  lua_pushlightuserdata (L, info);
  lua_pushnil (L);
  lua_rawset (L, LUA_REGISTRYINDEX);

  priv->lgi_leave_func (priv->lgi_lock);

  info->loader_data = NULL;
439 440 441 442 443 444
}

static void
peas_plugin_loader_lua_garbage_collect (PeasPluginLoader *loader)
{
  PeasPluginLoaderLua *lua_loader = PEAS_PLUGIN_LOADER_LUA (loader);
445
  PeasPluginLoaderLuaPrivate *priv = GET_PRIV (lua_loader);
446
  lua_State *L = priv->L;
447

448
  priv->lgi_enter_func (priv->lgi_lock);
449 450 451

  lua_gc (L, LUA_GCCOLLECT, 0);

452
  priv->lgi_leave_func (priv->lgi_lock);
453 454 455 456 457 458 459 460 461 462 463 464 465
}

static int
atpanic_handler (lua_State *L)
{
  G_BREAKPOINT ();
  return 0;
}

static gboolean
peas_plugin_loader_lua_initialize (PeasPluginLoader *loader)
{
  PeasPluginLoaderLua *lua_loader = PEAS_PLUGIN_LOADER_LUA (loader);
466
  PeasPluginLoaderLuaPrivate *priv = GET_PRIV (lua_loader);
467 468
  lua_State *L;

469
  priv->L = L = luaL_newstate ();
470 471 472 473 474 475
  if (L == NULL)
    {
      g_critical ("Failed to allocate lua_State");
      return FALSE;
    }

476 477 478 479
  /* Set before any other code is run */
  if (g_getenv ("PEAS_LUA_DEBUG") != NULL)
    lua_atpanic (L, atpanic_handler);

480 481 482 483 484 485 486 487 488 489 490 491
  luaL_openlibs (L);

  if (!peas_lua_utils_require (L, "lgi") ||
      !peas_lua_utils_check_version (L,
                                     LGI_MAJOR_VERSION,
                                     LGI_MINOR_VERSION,
                                     LGI_MICRO_VERSION))
    {
      /* Already warned */
      return FALSE;
    }

492 493
  lua_pushliteral (L, "lock");
  lua_rawget (L, -2);
494
  priv->lgi_lock = lua_touserdata (L, -1);
495 496
  lua_pop (L, 1);

497 498
  lua_pushliteral (L, "enter");
  lua_rawget (L, -2);
499
  priv->lgi_enter_func = lua_touserdata (L, -1);
500 501
  lua_pop (L, 1);

502 503
  lua_pushliteral (L, "leave");
  lua_rawget (L, -2);
504
  priv->lgi_leave_func = lua_touserdata (L, -1);
505 506
  lua_pop (L, 1);

507 508 509
  if (priv->lgi_lock == NULL ||
      priv->lgi_enter_func == NULL ||
      priv->lgi_leave_func == NULL)
510 511 512 513 514
    {
      g_warning ("Failed to find 'lgi.lock', 'lgi.enter' and 'lgi.leave'");
      return FALSE;
    }

515 516 517
  /* Pop lgi's module table */
  lua_pop (L, 1);

518 519 520
  /* Initially the lock is taken by LGI,
   * release as we are not running Lua code
   */
521
  priv->lgi_leave_func (priv->lgi_lock);
522 523 524
  return TRUE;
}

525 526 527 528 529 530
static gboolean
peas_plugin_loader_lua_is_global (PeasPluginLoader *loader)
{
  return FALSE;
}

531 532 533 534 535 536 537 538 539
static void
peas_plugin_loader_lua_init (PeasPluginLoaderLua *lua_loader)
{
}

static void
peas_plugin_loader_lua_finalize (GObject *object)
{
  PeasPluginLoaderLua *lua_loader = PEAS_PLUGIN_LOADER_LUA (object);
540
  PeasPluginLoaderLuaPrivate *priv = GET_PRIV (lua_loader);
541

542 543 544
  /* Must take the lock as Lua code will run on lua_close
   * and another thread might be running Lua code already
   */
545 546
  if (priv->lgi_enter_func != NULL)
    priv->lgi_enter_func (priv->lgi_lock);
547

548
  g_clear_pointer (&priv->L, (GDestroyNotify) lua_close);
549 550 551 552 553 554 555 556 557 558 559 560 561

  G_OBJECT_CLASS (peas_plugin_loader_lua_parent_class)->finalize (object);
}

static void
peas_plugin_loader_lua_class_init (PeasPluginLoaderLuaClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);
  PeasPluginLoaderClass *loader_class = PEAS_PLUGIN_LOADER_CLASS (klass);

  object_class->finalize = peas_plugin_loader_lua_finalize;

  loader_class->initialize = peas_plugin_loader_lua_initialize;
562
  loader_class->is_global = peas_plugin_loader_lua_is_global;
563 564 565 566 567 568
  loader_class->load = peas_plugin_loader_lua_load;
  loader_class->unload = peas_plugin_loader_lua_unload;
  loader_class->create_extension = peas_plugin_loader_lua_create_extension;
  loader_class->provides_extension = peas_plugin_loader_lua_provides_extension;
  loader_class->garbage_collect = peas_plugin_loader_lua_garbage_collect;
}