sql_plugin.cc 111 KB
Newer Older
1
/*
2
   Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
3 4 5

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
6
   the Free Software Foundation; version 2 of the License.
7 8 9 10 11 12 13 14

   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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
15
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
16

17 18 19 20
#include "sql_priv.h"                         // SHOW_MY_BOOL
#include "unireg.h"
#include "my_global.h"                       // REQUIRED by m_string.h
#include "sql_class.h"                          // set_var.h: THD
21
#include "sys_vars_shared.h"
22 23 24
#include "sql_locale.h"
#include "sql_plugin.h"
#include "sql_parse.h"          // check_table_access
25
#include "sql_base.h"                           // close_mysql_tables
26 27 28 29 30
#include "key.h"                                // key_copy
#include "sql_show.h"           // remove_status_vars, add_status_vars
#include "strfunc.h"            // find_set
#include "sql_acl.h"                       // *_ACL
#include "records.h"          // init_read_record, end_read_record
31
#include <my_pthread.h>
unknown's avatar
unknown committed
32
#include <my_getopt.h>
33
#include "sql_audit.h"
34
#include <mysql/plugin_auth.h>
35
#include "lock.h"                               // MYSQL_LOCK_IGNORE_TIMEOUT
36 37 38
#define REPORT_TO_LOG  1
#define REPORT_TO_USER 2

39 40
extern struct st_mysql_plugin *mysql_optional_plugins[];
extern struct st_mysql_plugin *mysql_mandatory_plugins[];
unknown's avatar
unknown committed
41

42 43 44 45
/**
  @note The order of the enumeration is critical.
  @see construct_options
*/
Sergey Vojtovich's avatar
Sergey Vojtovich committed
46 47
const char *global_plugin_typelib_names[]=
  { "OFF", "ON", "FORCE", "FORCE_PLUS_PERMANENT", NULL };
48 49 50 51 52
static TYPELIB global_plugin_typelib=
  { array_elements(global_plugin_typelib_names)-1,
    "", global_plugin_typelib_names, NULL };


unknown's avatar
unknown committed
53
char *opt_plugin_load= NULL;
54 55
char *opt_plugin_dir_ptr;
char opt_plugin_dir[FN_REFLEN];
56
/*
unknown's avatar
unknown committed
57
  When you ad a new plugin type, add both a string and make sure that the
58 59
  init and deinit array are correctly updated.
*/
unknown's avatar
unknown committed
60
const LEX_STRING plugin_type_names[MYSQL_MAX_PLUGIN_TYPE_NUM]=
61
{
unknown's avatar
unknown committed
62 63
  { C_STRING_WITH_LEN("UDF") },
  { C_STRING_WITH_LEN("STORAGE ENGINE") },
64
  { C_STRING_WITH_LEN("FTPARSER") },
unknown's avatar
unknown committed
65
  { C_STRING_WITH_LEN("DAEMON") },
He Zhenxing's avatar
He Zhenxing committed
66
  { C_STRING_WITH_LEN("INFORMATION SCHEMA") },
67
  { C_STRING_WITH_LEN("AUDIT") },
He Zhenxing's avatar
He Zhenxing committed
68
  { C_STRING_WITH_LEN("REPLICATION") },
69
  { C_STRING_WITH_LEN("AUTHENTICATION") }
70
};
unknown's avatar
unknown committed
71

unknown's avatar
unknown committed
72 73 74
extern int initialize_schema_table(st_plugin_int *plugin);
extern int finalize_schema_table(st_plugin_int *plugin);

75 76 77
extern int initialize_audit_plugin(st_plugin_int *plugin);
extern int finalize_audit_plugin(st_plugin_int *plugin);

unknown's avatar
unknown committed
78
/*
unknown's avatar
unknown committed
79
  The number of elements in both plugin_type_initialize and
unknown's avatar
unknown committed
80 81
  plugin_type_deinitialize should equal to the number of plugins
  defined.
unknown's avatar
unknown committed
82
*/
unknown's avatar
unknown committed
83 84
plugin_type_init plugin_type_initialize[MYSQL_MAX_PLUGIN_TYPE_NUM]=
{
85
  0,ha_initialize_handlerton,0,0,initialize_schema_table,
86
  initialize_audit_plugin,0,0
unknown's avatar
unknown committed
87 88
};

unknown's avatar
unknown committed
89 90
plugin_type_init plugin_type_deinitialize[MYSQL_MAX_PLUGIN_TYPE_NUM]=
{
91
  0,ha_finalize_handlerton,0,0,finalize_schema_table,
92
  finalize_audit_plugin,0,0
unknown's avatar
unknown committed
93 94
};

unknown's avatar
unknown committed
95
#ifdef HAVE_DLOPEN
96 97
static const char *plugin_interface_version_sym=
                   "_mysql_plugin_interface_version_";
98 99
static const char *sizeof_st_plugin_sym=
                   "_mysql_sizeof_struct_st_plugin_";
100
static const char *plugin_declarations_sym= "_mysql_plugin_declarations_";
unknown's avatar
unknown committed
101
static int min_plugin_interface_version= MYSQL_PLUGIN_INTERFACE_VERSION & ~0xFF;
unknown's avatar
unknown committed
102 103
#endif

104 105 106 107 108 109
/* Note that 'int version' must be the first field of every plugin
   sub-structure (plugin->info).
*/
static int min_plugin_info_interface_version[MYSQL_MAX_PLUGIN_TYPE_NUM]=
{
  0x0000,
110
  MYSQL_HANDLERTON_INTERFACE_VERSION,
111
  MYSQL_FTPARSER_INTERFACE_VERSION,
unknown's avatar
unknown committed
112
  MYSQL_DAEMON_INTERFACE_VERSION,
He Zhenxing's avatar
He Zhenxing committed
113
  MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION,
114
  MYSQL_AUDIT_INTERFACE_VERSION,
115 116
  MYSQL_REPLICATION_INTERFACE_VERSION,
  MYSQL_AUTHENTICATION_INTERFACE_VERSION
117 118 119 120
};
static int cur_plugin_info_interface_version[MYSQL_MAX_PLUGIN_TYPE_NUM]=
{
  0x0000, /* UDF: not implemented */
unknown's avatar
unknown committed
121
  MYSQL_HANDLERTON_INTERFACE_VERSION,
122
  MYSQL_FTPARSER_INTERFACE_VERSION,
unknown's avatar
unknown committed
123
  MYSQL_DAEMON_INTERFACE_VERSION,
He Zhenxing's avatar
He Zhenxing committed
124
  MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION,
125
  MYSQL_AUDIT_INTERFACE_VERSION,
126 127
  MYSQL_REPLICATION_INTERFACE_VERSION,
  MYSQL_AUTHENTICATION_INTERFACE_VERSION
128
};
129

130 131 132
/* support for Services */

#include "sql_plugin_services.h"
unknown's avatar
unknown committed
133 134 135 136 137 138

/*
  A mutex LOCK_plugin must be acquired before accessing the
  following variables/structures.
  We are always manipulating ref count, so a rwlock here is unneccessary.
*/
Marc Alff's avatar
Marc Alff committed
139
mysql_mutex_t LOCK_plugin;
140 141 142
static DYNAMIC_ARRAY plugin_dl_array;
static DYNAMIC_ARRAY plugin_array;
static HASH plugin_hash[MYSQL_MAX_PLUGIN_TYPE_NUM];
unknown's avatar
unknown committed
143
static bool reap_needed= false;
144 145
static int plugin_array_version=0;

146 147
static bool initialized= 0;

unknown's avatar
unknown committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
/*
  write-lock on LOCK_system_variables_hash is required before modifying
  the following variables/structures
*/
static MEM_ROOT plugin_mem_root;
static uint global_variables_dynamic_size= 0;
static HASH bookmark_hash;


/*
  hidden part of opaque value passed to variable check functions.
  Used to provide a object-like structure to non C++ consumers.
*/
struct st_item_value_holder : public st_mysql_value
{
  Item *item;
};


/*
  stored in bookmark_hash, this structure is never removed from the
unknown's avatar
unknown committed
169
  hash and is used to mark a single offset for a thd local variable
unknown's avatar
unknown committed
170 171
  even if plugins have been uninstalled and reinstalled, repeatedly.
  This structure is allocated from plugin_mem_root.
unknown's avatar
unknown committed
172

unknown's avatar
unknown committed
173 174 175 176
  The key format is as follows:
    1 byte         - variable type code
    name_len bytes - variable name
    '\0'           - end of key
unknown's avatar
unknown committed
177 178 179 180 181 182
*/
struct st_bookmark
{
  uint name_len;
  int offset;
  uint version;
unknown's avatar
unknown committed
183
  char key[1];
unknown's avatar
unknown committed
184 185 186 187 188 189 190 191 192 193 194
};


/*
  skeleton of a plugin variable - portion of structure common to all.
*/
struct st_mysql_sys_var
{
  MYSQL_PLUGIN_VAR_HEADER;
};

195 196
static SHOW_TYPE pluginvar_show_type(st_mysql_sys_var *plugin_var);

unknown's avatar
unknown committed
197 198 199 200 201 202 203 204 205

/*
  sys_var class for access to all plugin variables visible to the user
*/
class sys_var_pluginvar: public sys_var
{
public:
  struct st_plugin_int *plugin;
  struct st_mysql_sys_var *plugin_var;
206 207 208 209 210 211 212 213
  /**
    variable name from whatever is hard-coded in the plugin source
    and doesn't have pluginname- prefix is replaced by an allocated name
    with a plugin prefix. When plugin is uninstalled we need to restore the
    pointer to point to the hard-coded value, because plugin may be
    installed/uninstalled many times without reloading the shared object.
  */
  const char *orig_pluginvar_name;
unknown's avatar
unknown committed
214 215

  static void *operator new(size_t size, MEM_ROOT *mem_root)
216
  { return (void*) alloc_root(mem_root, size); }
unknown's avatar
unknown committed
217 218 219
  static void operator delete(void *ptr_arg,size_t size)
  { TRASH(ptr_arg, size); }

220
  sys_var_pluginvar(sys_var_chain *chain, const char *name_arg,
unknown's avatar
unknown committed
221
                    struct st_mysql_sys_var *plugin_var_arg)
222 223 224 225
    :sys_var(chain, name_arg, plugin_var_arg->comment,
             (plugin_var_arg->flags & PLUGIN_VAR_THDLOCAL ? SESSION : GLOBAL) |
             (plugin_var_arg->flags & PLUGIN_VAR_READONLY ? READONLY : 0),
             0, -1, NO_ARG, pluginvar_show_type(plugin_var_arg), 0, 0,
226
             VARIABLE_NOT_IN_BINLOG, NULL, NULL, NULL, PARSE_NORMAL),
227 228
    plugin_var(plugin_var_arg), orig_pluginvar_name(plugin_var_arg->name)
  { plugin_var->name= name_arg; }
unknown's avatar
unknown committed
229 230 231
  sys_var_pluginvar *cast_pluginvar() { return this; }
  bool check_update_type(Item_result type);
  SHOW_TYPE show_type();
unknown's avatar
unknown committed
232
  uchar* real_value_ptr(THD *thd, enum_var_type type);
unknown's avatar
unknown committed
233
  TYPELIB* plugin_var_typelib(void);
234 235 236 237 238 239 240 241 242 243
  uchar* do_value_ptr(THD *thd, enum_var_type type, LEX_STRING *base);
  uchar* session_value_ptr(THD *thd, LEX_STRING *base)
  { return do_value_ptr(thd, OPT_SESSION, base); }
  uchar* global_value_ptr(THD *thd, LEX_STRING *base)
  { return do_value_ptr(thd, OPT_GLOBAL, base); }
  bool do_check(THD *thd, set_var *var);
  virtual void session_save_default(THD *thd, set_var *var) {}
  virtual void global_save_default(THD *thd, set_var *var) {}
  bool session_update(THD *thd, set_var *var);
  bool global_update(THD *thd, set_var *var);
unknown's avatar
unknown committed
244 245 246
};


247
/* prototypes */
unknown's avatar
unknown committed
248 249 250
static void plugin_load(MEM_ROOT *tmp_root, int *argc, char **argv);
static bool plugin_load_list(MEM_ROOT *tmp_root, int *argc, char **argv,
                             const char *list);
unknown's avatar
unknown committed
251
static int test_plugin_options(MEM_ROOT *, struct st_plugin_int *,
252
                               int *, char **);
unknown's avatar
unknown committed
253 254
static bool register_builtin(struct st_mysql_plugin *, struct st_plugin_int *,
                             struct st_plugin_int **);
unknown's avatar
unknown committed
255 256
static void unlock_variables(THD *thd, struct system_variables *vars);
static void cleanup_variables(THD *thd, struct system_variables *vars);
257
static void plugin_vars_free_values(sys_var *vars);
258 259 260 261 262 263 264
static bool plugin_var_memalloc_session_update(THD *thd,
                                               struct st_mysql_sys_var *var,
                                               char **dest, const char *value);
static bool plugin_var_memalloc_global_update(THD *thd,
                                              struct st_mysql_sys_var *var,
                                              char **dest, const char *value);
static void plugin_var_memalloc_free(struct system_variables *vars);
265 266 267
static void restore_pluginvar_names(sys_var *first);
static void plugin_opt_set_limits(struct my_option *,
                                  const struct st_mysql_sys_var *);
268 269 270
#define my_intern_plugin_lock(A,B) intern_plugin_lock(A,B)
#define my_intern_plugin_lock_ci(A,B) intern_plugin_lock(A,B)
static plugin_ref intern_plugin_lock(LEX *lex, plugin_ref plugin);
unknown's avatar
unknown committed
271 272 273
static void intern_plugin_unlock(LEX *lex, plugin_ref plugin);
static void reap_plugins(void);

274 275 276 277 278 279 280 281 282 283 284 285
static void report_error(int where_to, uint error, ...)
{
  va_list args;
  if (where_to & REPORT_TO_USER)
  {
    va_start(args, error);
    my_printv_error(error, ER(error), MYF(0), args);
    va_end(args);
  }
  if (where_to & REPORT_TO_LOG)
  {
    va_start(args, error);
286
    error_log_print(ERROR_LEVEL, ER_DEFAULT(error), args);
287 288 289
    va_end(args);
  }
}
unknown's avatar
unknown committed
290

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
/**
   Check if the provided path is valid in the sense that it does cause
   a relative reference outside the directory.

   @note Currently, this function only check if there are any
   characters in FN_DIRSEP in the string, but it might change in the
   future.

   @code
   check_valid_path("../foo.so") -> true
   check_valid_path("foo.so") -> false
   @endcode
 */
bool check_valid_path(const char *path, size_t len)
{
  size_t prefix= my_strcspn(files_charset_info, path, path + len, FN_DIRSEP);
  return  prefix < len;
}


unknown's avatar
unknown committed
311 312 313 314 315 316 317 318 319 320 321 322
/****************************************************************************
  Value type thunks, allows the C world to play in the C++ world
****************************************************************************/

static int item_value_type(struct st_mysql_value *value)
{
  switch (((st_item_value_holder*)value)->item->result_type()) {
  case INT_RESULT:
    return MYSQL_VALUE_TYPE_INT;
  case REAL_RESULT:
    return MYSQL_VALUE_TYPE_REAL;
  default:
unknown's avatar
unknown committed
323
    return MYSQL_VALUE_TYPE_STRING;
unknown's avatar
unknown committed
324 325 326
  }
}

unknown's avatar
unknown committed
327
static const char *item_val_str(struct st_mysql_value *value,
unknown's avatar
unknown committed
328 329 330 331 332 333 334 335
                                char *buffer, int *length)
{
  String str(buffer, *length, system_charset_info), *res;
  if (!(res= ((st_item_value_holder*)value)->item->val_str(&str)))
    return NULL;
  *length= res->length();
  if (res->c_ptr_quick() == buffer)
    return buffer;
unknown's avatar
unknown committed
336

unknown's avatar
unknown committed
337
  /*
unknown's avatar
unknown committed
338
    Lets be nice and create a temporary string since the
unknown's avatar
unknown committed
339 340 341 342 343 344
    buffer was too small
  */
  return current_thd->strmake(res->c_ptr_quick(), res->length());
}


unknown's avatar
unknown committed
345
static int item_val_int(struct st_mysql_value *value, long long *buf)
unknown's avatar
unknown committed
346 347
{
  Item *item= ((st_item_value_holder*)value)->item;
unknown's avatar
unknown committed
348
  *buf= item->val_int();
unknown's avatar
unknown committed
349 350 351 352 353
  if (item->is_null())
    return 1;
  return 0;
}

354 355 356 357 358
static int item_is_unsigned(struct st_mysql_value *value)
{
  Item *item= ((st_item_value_holder*)value)->item;
  return item->unsigned_flag;
}
unknown's avatar
unknown committed
359

unknown's avatar
unknown committed
360
static int item_val_real(struct st_mysql_value *value, double *buf)
unknown's avatar
unknown committed
361 362
{
  Item *item= ((st_item_value_holder*)value)->item;
unknown's avatar
unknown committed
363
  *buf= item->val_real();
unknown's avatar
unknown committed
364 365 366 367 368 369 370 371 372
  if (item->is_null())
    return 1;
  return 0;
}


/****************************************************************************
  Plugin support code
****************************************************************************/
373

unknown's avatar
unknown committed
374 375
#ifdef HAVE_DLOPEN

unknown's avatar
unknown committed
376
static struct st_plugin_dl *plugin_dl_find(const LEX_STRING *dl)
377 378
{
  uint i;
unknown's avatar
unknown committed
379
  struct st_plugin_dl *tmp;
380 381 382
  DBUG_ENTER("plugin_dl_find");
  for (i= 0; i < plugin_dl_array.elements; i++)
  {
unknown's avatar
unknown committed
383
    tmp= *dynamic_element(&plugin_dl_array, i, struct st_plugin_dl **);
384 385 386 387 388 389 390 391 392 393
    if (tmp->ref_count &&
        ! my_strnncoll(files_charset_info,
                       (const uchar *)dl->str, dl->length,
                       (const uchar *)tmp->dl.str, tmp->dl.length))
      DBUG_RETURN(tmp);
  }
  DBUG_RETURN(0);
}


394 395 396
static st_plugin_dl *plugin_dl_insert_or_reuse(struct st_plugin_dl *plugin_dl)
{
  uint i;
unknown's avatar
unknown committed
397
  struct st_plugin_dl *tmp;
398 399 400
  DBUG_ENTER("plugin_dl_insert_or_reuse");
  for (i= 0; i < plugin_dl_array.elements; i++)
  {
unknown's avatar
unknown committed
401
    tmp= *dynamic_element(&plugin_dl_array, i, struct st_plugin_dl **);
402 403 404 405 406 407
    if (! tmp->ref_count)
    {
      memcpy(tmp, plugin_dl, sizeof(struct st_plugin_dl));
      DBUG_RETURN(tmp);
    }
  }
408
  if (insert_dynamic(&plugin_dl_array, (uchar*)&plugin_dl))
409
    DBUG_RETURN(0);
unknown's avatar
unknown committed
410 411
  tmp= *dynamic_element(&plugin_dl_array, plugin_dl_array.elements - 1,
                        struct st_plugin_dl **)=
unknown's avatar
unknown committed
412
      (struct st_plugin_dl *) memdup_root(&plugin_mem_root, (uchar*)plugin_dl,
unknown's avatar
unknown committed
413 414
                                           sizeof(struct st_plugin_dl));
  DBUG_RETURN(tmp);
415
}
unknown's avatar
unknown committed
416 417
#endif /* HAVE_DLOPEN */

418

419 420
static inline void free_plugin_mem(struct st_plugin_dl *p)
{
421
#ifdef HAVE_DLOPEN
422 423
  if (p->handle)
    dlclose(p->handle);
424
#endif
425
  my_free(p->dl.str);
426
  if (p->version != MYSQL_PLUGIN_INTERFACE_VERSION)
427
    my_free(p->plugins);
428
}
429

unknown's avatar
unknown committed
430

unknown's avatar
unknown committed
431
static st_plugin_dl *plugin_dl_add(const LEX_STRING *dl, int report)
432 433 434
{
#ifdef HAVE_DLOPEN
  char dlpath[FN_REFLEN];
435
  uint plugin_dir_len, dummy_errors, dlpathlen, i;
436 437 438
  struct st_plugin_dl *tmp, plugin_dl;
  void *sym;
  DBUG_ENTER("plugin_dl_add");
439 440
  DBUG_PRINT("enter", ("dl->str: '%s', dl->length: %d",
                       dl->str, (int) dl->length));
441 442 443 444 445 446
  plugin_dir_len= strlen(opt_plugin_dir);
  /*
    Ensure that the dll doesn't have a path.
    This is done to ensure that only approved libraries from the
    plugin directory are used (to make this even remotely secure).
  */
447
  if (check_valid_path(dl->str, dl->length) ||
448 449
      check_string_char_length((LEX_STRING *) dl, "", NAME_CHAR_LEN,
                               system_charset_info, 1) ||
450 451
      plugin_dir_len + dl->length + 1 >= FN_REFLEN)
  {
452
    report_error(report, ER_UDF_NO_PATHS);
453 454 455 456 457 458 459 460
    DBUG_RETURN(0);
  }
  /* If this dll is already loaded just increase ref_count. */
  if ((tmp= plugin_dl_find(dl)))
  {
    tmp->ref_count++;
    DBUG_RETURN(tmp);
  }
461
  bzero(&plugin_dl, sizeof(plugin_dl));
462
  /* Compile dll path */
463 464 465
  dlpathlen=
    strxnmov(dlpath, sizeof(dlpath) - 1, opt_plugin_dir, "/", dl->str, NullS) -
    dlpath;
466
  (void) unpack_filename(dlpath, dlpath);
467 468 469 470
  plugin_dl.ref_count= 1;
  /* Open new dll handle */
  if (!(plugin_dl.handle= dlopen(dlpath, RTLD_NOW)))
  {
471 472 473 474
    const char *errmsg;
    int error_number= dlopen_errno;
    DLERROR_GENERATE(errmsg, error_number);

475 476 477 478 479 480
    if (!strncmp(dlpath, errmsg, dlpathlen))
    { // if errmsg starts from dlpath, trim this prefix.
      errmsg+=dlpathlen;
      if (*errmsg == ':') errmsg++;
      if (*errmsg == ' ') errmsg++;
    }
481
    report_error(report, ER_CANT_OPEN_LIBRARY, dlpath, error_number, errmsg);
482 483 484 485 486
    DBUG_RETURN(0);
  }
  /* Determine interface version */
  if (!(sym= dlsym(plugin_dl.handle, plugin_interface_version_sym)))
  {
487
    free_plugin_mem(&plugin_dl);
488
    report_error(report, ER_CANT_FIND_DL_ENTRY, plugin_interface_version_sym);
489 490 491 492 493 494 495
    DBUG_RETURN(0);
  }
  plugin_dl.version= *(int *)sym;
  /* Versioning */
  if (plugin_dl.version < min_plugin_interface_version ||
      (plugin_dl.version >> 8) > (MYSQL_PLUGIN_INTERFACE_VERSION >> 8))
  {
496
    free_plugin_mem(&plugin_dl);
Sergei Golubchik's avatar
Sergei Golubchik committed
497
    report_error(report, ER_CANT_OPEN_LIBRARY, dlpath, 0,
498
                 "plugin interface version mismatch");
499 500
    DBUG_RETURN(0);
  }
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

  /* link the services in */
  for (i= 0; i < array_elements(list_of_services); i++)
  {
    if ((sym= dlsym(plugin_dl.handle, list_of_services[i].name)))
    {
      uint ver= (uint)(intptr)*(void**)sym;
      if (ver > list_of_services[i].version ||
        (ver >> 8) < (list_of_services[i].version >> 8))
      {
        char buf[MYSQL_ERRMSG_SIZE];
        my_snprintf(buf, sizeof(buf),
                    "service '%s' interface version mismatch",
                    list_of_services[i].name);
        report_error(report, ER_CANT_OPEN_LIBRARY, dlpath, 0, buf);
        DBUG_RETURN(0);
      }
      *(void**)sym= list_of_services[i].service;
    }
  }

522 523 524
  /* Find plugin declarations */
  if (!(sym= dlsym(plugin_dl.handle, plugin_declarations_sym)))
  {
525
    free_plugin_mem(&plugin_dl);
Sergei Golubchik's avatar
Sergei Golubchik committed
526
    report_error(report, ER_CANT_FIND_DL_ENTRY, plugin_declarations_sym);
527 528
    DBUG_RETURN(0);
  }
529 530 531

  if (plugin_dl.version != MYSQL_PLUGIN_INTERFACE_VERSION)
  {
532
    uint sizeof_st_plugin;
533
    struct st_mysql_plugin *old, *cur;
534
    char *ptr= (char *)sym;
535 536 537 538 539 540

    if ((sym= dlsym(plugin_dl.handle, sizeof_st_plugin_sym)))
      sizeof_st_plugin= *(int *)sym;
    else
    {
#ifdef ERROR_ON_NO_SIZEOF_PLUGIN_SYMBOL
541
      report_error(report, ER_CANT_FIND_DL_ENTRY, sizeof_st_plugin_sym);
542 543
      DBUG_RETURN(0);
#else
544 545 546 547
      /*
        When the following assert starts failing, we'll have to switch
        to the upper branch of the #ifdef
      */
548
      DBUG_ASSERT(min_plugin_interface_version == 0);
549
      sizeof_st_plugin= (int)offsetof(struct st_mysql_plugin, version);
550 551 552
#endif
    }

553 554 555 556 557
    /*
      What's the purpose of this loop? If the goal is to catch a
      missing 0 record at the end of a list, it will fail miserably
      since the compiler is likely to optimize this away. /Matz
     */
558 559 560 561 562 563
    for (i= 0;
         ((struct st_mysql_plugin *)(ptr+i*sizeof_st_plugin))->info;
         i++)
      /* no op */;

    cur= (struct st_mysql_plugin*)
564
      my_malloc((i+1)*sizeof(struct st_mysql_plugin), MYF(MY_ZEROFILL|MY_WME));
565 566 567
    if (!cur)
    {
      free_plugin_mem(&plugin_dl);
Guilhem Bichot's avatar
Guilhem Bichot committed
568 569
      report_error(report, ER_OUTOFMEMORY,
                   static_cast<int>(plugin_dl.dl.length));
570 571
      DBUG_RETURN(0);
    }
572 573 574 575 576
    /*
      All st_plugin fields not initialized in the plugin explicitly, are
      set to 0. It matches C standard behaviour for struct initializers that
      have less values than the struct definition.
    */
577 578 579
    for (i=0;
         (old=(struct st_mysql_plugin *)(ptr+i*sizeof_st_plugin))->info;
         i++)
580
      memcpy(cur+i, old, min(sizeof(cur[i]), sizeof_st_plugin));
581

582
    sym= cur;
583
  }
584
  plugin_dl.plugins= (struct st_mysql_plugin *)sym;
585

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
  /*
    If report is REPORT_TO_USER, we were called from
    mysql_install_plugin. Otherwise, we are called directly or
    indirectly from plugin_init.
   */
  if (report == REPORT_TO_USER)
  {
    st_mysql_plugin *plugin= plugin_dl.plugins;
    for ( ; plugin->info ; ++plugin)
      if (plugin->flags & PLUGIN_OPT_NO_INSTALL)
      {
        report_error(report, ER_PLUGIN_NO_INSTALL, plugin->name);
        free_plugin_mem(&plugin_dl);
        DBUG_RETURN(0);
   }
  }

603 604
  /* Duplicate and convert dll name */
  plugin_dl.dl.length= dl->length * files_charset_info->mbmaxlen + 1;
605
  if (! (plugin_dl.dl.str= (char*) my_malloc(plugin_dl.dl.length, MYF(0))))
606
  {
607
    free_plugin_mem(&plugin_dl);
Guilhem Bichot's avatar
Guilhem Bichot committed
608 609
    report_error(report, ER_OUTOFMEMORY,
                 static_cast<int>(plugin_dl.dl.length));
610 611 612 613 614 615 616
    DBUG_RETURN(0);
  }
  plugin_dl.dl.length= copy_and_convert(plugin_dl.dl.str, plugin_dl.dl.length,
    files_charset_info, dl->str, dl->length, system_charset_info,
    &dummy_errors);
  plugin_dl.dl.str[plugin_dl.dl.length]= 0;
  /* Add this dll to array */
617
  if (! (tmp= plugin_dl_insert_or_reuse(&plugin_dl)))
618
  {
619
    free_plugin_mem(&plugin_dl);
Guilhem Bichot's avatar
Guilhem Bichot committed
620 621
    report_error(report, ER_OUTOFMEMORY,
                 static_cast<int>(sizeof(struct st_plugin_dl)));
622 623
    DBUG_RETURN(0);
  }
624
  DBUG_RETURN(tmp);
625 626
#else
  DBUG_ENTER("plugin_dl_add");
627
  report_error(report, ER_FEATURE_DISABLED, "plugin", "HAVE_DLOPEN");
628 629 630 631 632
  DBUG_RETURN(0);
#endif
}


unknown's avatar
unknown committed
633
static void plugin_dl_del(const LEX_STRING *dl)
634 635 636 637
{
#ifdef HAVE_DLOPEN
  uint i;
  DBUG_ENTER("plugin_dl_del");
unknown's avatar
unknown committed
638

Marc Alff's avatar
Marc Alff committed
639
  mysql_mutex_assert_owner(&LOCK_plugin);
unknown's avatar
unknown committed
640

641 642
  for (i= 0; i < plugin_dl_array.elements; i++)
  {
unknown's avatar
unknown committed
643 644
    struct st_plugin_dl *tmp= *dynamic_element(&plugin_dl_array, i,
                                               struct st_plugin_dl **);
645 646 647 648 649 650 651 652
    if (tmp->ref_count &&
        ! my_strnncoll(files_charset_info,
                       (const uchar *)dl->str, dl->length,
                       (const uchar *)tmp->dl.str, tmp->dl.length))
    {
      /* Do not remove this element, unless no other plugin uses this dll. */
      if (! --tmp->ref_count)
      {
653
        free_plugin_mem(tmp);
654 655 656 657 658 659 660 661 662 663
        bzero(tmp, sizeof(struct st_plugin_dl));
      }
      break;
    }
  }
  DBUG_VOID_RETURN;
#endif
}


unknown's avatar
unknown committed
664
static struct st_plugin_int *plugin_find_internal(const LEX_STRING *name, int type)
665 666 667 668 669
{
  uint i;
  DBUG_ENTER("plugin_find_internal");
  if (! initialized)
    DBUG_RETURN(0);
unknown's avatar
unknown committed
670

Marc Alff's avatar
Marc Alff committed
671
  mysql_mutex_assert_owner(&LOCK_plugin);
unknown's avatar
unknown committed
672

673 674 675 676 677
  if (type == MYSQL_ANY_PLUGIN)
  {
    for (i= 0; i < MYSQL_MAX_PLUGIN_TYPE_NUM; i++)
    {
      struct st_plugin_int *plugin= (st_plugin_int *)
Konstantin Osipov's avatar
Konstantin Osipov committed
678
        my_hash_search(&plugin_hash[i], (const uchar *)name->str, name->length);
679
      if (plugin)
680 681 682 683 684
        DBUG_RETURN(plugin);
    }
  }
  else
    DBUG_RETURN((st_plugin_int *)
Konstantin Osipov's avatar
Konstantin Osipov committed
685 686
        my_hash_search(&plugin_hash[type], (const uchar *)name->str,
                       name->length));
687 688 689 690
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
691
static SHOW_COMP_OPTION plugin_status(const LEX_STRING *name, int type)
692
{
unknown's avatar
unknown committed
693
  SHOW_COMP_OPTION rc= SHOW_OPTION_NO;
694 695
  struct st_plugin_int *plugin;
  DBUG_ENTER("plugin_is_ready");
Marc Alff's avatar
Marc Alff committed
696
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
697 698 699 700 701 702
  if ((plugin= plugin_find_internal(name, type)))
  {
    rc= SHOW_OPTION_DISABLED;
    if (plugin->state == PLUGIN_IS_READY)
      rc= SHOW_OPTION_YES;
  }
Marc Alff's avatar
Marc Alff committed
703
  mysql_mutex_unlock(&LOCK_plugin);
704 705 706 707
  DBUG_RETURN(rc);
}


unknown's avatar
unknown committed
708
bool plugin_is_ready(const LEX_STRING *name, int type)
709
{
unknown's avatar
unknown committed
710 711 712 713 714 715 716
  bool rc= FALSE;
  if (plugin_status(name, type) == SHOW_OPTION_YES)
    rc= TRUE;
  return rc;
}


717
SHOW_COMP_OPTION plugin_status(const char *name, size_t len, int type)
unknown's avatar
unknown committed
718
{
719 720
  LEX_STRING plugin_name= { (char *) name, len };
  return plugin_status(&plugin_name, type);
unknown's avatar
unknown committed
721 722 723
}


724
static plugin_ref intern_plugin_lock(LEX *lex, plugin_ref rc)
unknown's avatar
unknown committed
725 726 727
{
  st_plugin_int *pi= plugin_ref_to_int(rc);
  DBUG_ENTER("intern_plugin_lock");
unknown's avatar
unknown committed
728

Marc Alff's avatar
Marc Alff committed
729
  mysql_mutex_assert_owner(&LOCK_plugin);
unknown's avatar
unknown committed
730

unknown's avatar
unknown committed
731
  if (pi->state & (PLUGIN_IS_READY | PLUGIN_IS_UNINITIALIZED))
732
  {
unknown's avatar
unknown committed
733 734 735 736 737 738 739 740
    plugin_ref plugin;
#ifdef DBUG_OFF
    /* built-in plugins don't need ref counting */
    if (!pi->plugin_dl)
      DBUG_RETURN(pi);

    plugin= pi;
#else
unknown's avatar
unknown committed
741 742 743
    /*
      For debugging, we do an additional malloc which allows the
      memory manager and/or valgrind to track locked references and
744
      double unlocks to aid resolving reference counting problems.
unknown's avatar
unknown committed
745
    */
746
    if (!(plugin= (plugin_ref) my_malloc(sizeof(pi), MYF(MY_WME))))
unknown's avatar
unknown committed
747 748 749 750 751 752 753 754 755
      DBUG_RETURN(NULL);

    *plugin= pi;
#endif
    pi->ref_count++;
    DBUG_PRINT("info",("thd: 0x%lx, plugin: \"%s\", ref_count: %d",
                       (long) current_thd, pi->name.str, pi->ref_count));

    if (lex)
unknown's avatar
unknown committed
756
      insert_dynamic(&lex->plugins, (uchar*)&plugin);
unknown's avatar
unknown committed
757
    DBUG_RETURN(plugin);
758
  }
unknown's avatar
unknown committed
759 760 761 762
  DBUG_RETURN(NULL);
}


763
plugin_ref plugin_lock(THD *thd, plugin_ref *ptr)
unknown's avatar
unknown committed
764
{
unknown's avatar
unknown committed
765
  LEX *lex= thd ? thd->lex : 0;
unknown's avatar
unknown committed
766 767
  plugin_ref rc;
  DBUG_ENTER("plugin_lock");
Marc Alff's avatar
Marc Alff committed
768
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
769
  rc= my_intern_plugin_lock_ci(lex, *ptr);
Marc Alff's avatar
Marc Alff committed
770
  mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
771 772 773 774
  DBUG_RETURN(rc);
}


775
plugin_ref plugin_lock_by_name(THD *thd, const LEX_STRING *name, int type)
unknown's avatar
unknown committed
776
{
unknown's avatar
unknown committed
777
  LEX *lex= thd ? thd->lex : 0;
unknown's avatar
unknown committed
778 779
  plugin_ref rc= NULL;
  st_plugin_int *plugin;
780
  DBUG_ENTER("plugin_lock_by_name");
Marc Alff's avatar
Marc Alff committed
781
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
782 783
  if ((plugin= plugin_find_internal(name, type)))
    rc= my_intern_plugin_lock_ci(lex, plugin_int_to_ref(plugin));
Marc Alff's avatar
Marc Alff committed
784
  mysql_mutex_unlock(&LOCK_plugin);
785 786 787 788
  DBUG_RETURN(rc);
}


789 790 791
static st_plugin_int *plugin_insert_or_reuse(struct st_plugin_int *plugin)
{
  uint i;
unknown's avatar
unknown committed
792
  struct st_plugin_int *tmp;
793 794 795
  DBUG_ENTER("plugin_insert_or_reuse");
  for (i= 0; i < plugin_array.elements; i++)
  {
unknown's avatar
unknown committed
796
    tmp= *dynamic_element(&plugin_array, i, struct st_plugin_int **);
797 798 799 800 801 802
    if (tmp->state == PLUGIN_IS_FREED)
    {
      memcpy(tmp, plugin, sizeof(struct st_plugin_int));
      DBUG_RETURN(tmp);
    }
  }
803
  if (insert_dynamic(&plugin_array, (uchar*)&plugin))
804
    DBUG_RETURN(0);
unknown's avatar
unknown committed
805 806
  tmp= *dynamic_element(&plugin_array, plugin_array.elements - 1,
                        struct st_plugin_int **)=
unknown's avatar
unknown committed
807
       (struct st_plugin_int *) memdup_root(&plugin_mem_root, (uchar*)plugin,
unknown's avatar
unknown committed
808 809
                                            sizeof(struct st_plugin_int));
  DBUG_RETURN(tmp);
810 811
}

unknown's avatar
unknown committed
812 813 814 815 816 817

/*
  NOTE
    Requires that a write-lock is held on LOCK_system_variables_hash
*/
static bool plugin_add(MEM_ROOT *tmp_root,
unknown's avatar
unknown committed
818
                       const LEX_STRING *name, const LEX_STRING *dl,
unknown's avatar
unknown committed
819
                       int *argc, char **argv, int report)
820 821 822 823 824 825
{
  struct st_plugin_int tmp;
  struct st_mysql_plugin *plugin;
  DBUG_ENTER("plugin_add");
  if (plugin_find_internal(name, MYSQL_ANY_PLUGIN))
  {
826
    report_error(report, ER_UDF_EXISTS, name->str);
827 828
    DBUG_RETURN(TRUE);
  }
829 830
  /* Clear the whole struct to catch future extensions. */
  bzero((char*) &tmp, sizeof(tmp));
831 832 833 834 835 836 837 838 839 840 841 842
  if (! (tmp.plugin_dl= plugin_dl_add(dl, report)))
    DBUG_RETURN(TRUE);
  /* Find plugin by name */
  for (plugin= tmp.plugin_dl->plugins; plugin->info; plugin++)
  {
    uint name_len= strlen(plugin->name);
    if (plugin->type >= 0 && plugin->type < MYSQL_MAX_PLUGIN_TYPE_NUM &&
        ! my_strnncoll(system_charset_info,
                       (const uchar *)name->str, name->length,
                       (const uchar *)plugin->name,
                       name_len))
    {
843 844 845 846 847 848 849 850
      struct st_plugin_int *tmp_plugin_ptr;
      if (*(int*)plugin->info <
          min_plugin_info_interface_version[plugin->type] ||
          ((*(int*)plugin->info) >> 8) >
          (cur_plugin_info_interface_version[plugin->type] >> 8))
      {
        char buf[256];
        strxnmov(buf, sizeof(buf) - 1, "API version for ",
unknown's avatar
unknown committed
851 852
                 plugin_type_names[plugin->type].str,
                 " plugin is too different", NullS);
853
        report_error(report, ER_CANT_OPEN_LIBRARY, dl->str, 0, buf);
854 855
        goto err;
      }
856 857 858 859 860
      tmp.plugin= plugin;
      tmp.name.str= (char *)plugin->name;
      tmp.name.length= name_len;
      tmp.ref_count= 0;
      tmp.state= PLUGIN_IS_UNINITIALIZED;
Sergey Vojtovich's avatar
Sergey Vojtovich committed
861
      tmp.load_option= PLUGIN_ON;
862
      if (test_plugin_options(tmp_root, &tmp, argc, argv))
863 864 865
        tmp.state= PLUGIN_IS_DISABLED;

      if ((tmp_plugin_ptr= plugin_insert_or_reuse(&tmp)))
866
      {
867 868
        plugin_array_version++;
        if (!my_hash_insert(&plugin_hash[plugin->type], (uchar*)tmp_plugin_ptr))
unknown's avatar
unknown committed
869
        {
870 871
          init_alloc_root(&tmp_plugin_ptr->mem_root, 4096, 4096);
          DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
872
        }
873
        tmp_plugin_ptr->state= PLUGIN_IS_FREED;
874
      }
875
      mysql_del_sys_var_chain(tmp.system_vars);
876
      restore_pluginvar_names(tmp.system_vars);
877 878
      goto err;

unknown's avatar
unknown committed
879 880
      /* plugin was disabled */
      plugin_dl_del(dl);
881 882 883
      DBUG_RETURN(FALSE);
    }
  }
884
  report_error(report, ER_CANT_FIND_DL_ENTRY, name->str);
885 886 887 888 889 890
err:
  plugin_dl_del(dl);
  DBUG_RETURN(TRUE);
}


unknown's avatar
unknown committed
891
static void plugin_deinitialize(struct st_plugin_int *plugin, bool ref_check)
892
{
unknown's avatar
unknown committed
893 894 895 896 897
  /*
    we don't want to hold the LOCK_plugin mutex as it may cause
    deinitialization to deadlock if plugins have worker threads
    with plugin locks
  */
Marc Alff's avatar
Marc Alff committed
898
  mysql_mutex_assert_not_owner(&LOCK_plugin);
899

unknown's avatar
unknown committed
900 901 902
  if (plugin->plugin->status_vars)
  {
#ifdef FIX_LATER
903 904 905 906 907 908
    /**
      @todo
      unfortunately, status variables were introduced without a
      pluginname_ namespace, that is pluginname_ was not added automatically
      to status variable names. It should be fixed together with the next
      incompatible API change.
unknown's avatar
unknown committed
909 910 911 912 913 914 915 916 917 918 919
    */
    SHOW_VAR array[2]= {
      {plugin->plugin->name, (char*)plugin->plugin->status_vars, SHOW_ARRAY},
      {0, 0, SHOW_UNDEF}
    };
    remove_status_vars(array);
#else
    remove_status_vars(plugin->plugin->status_vars);
#endif /* FIX_LATER */
  }

920 921 922 923 924
  if (plugin_type_deinitialize[plugin->plugin->type])
  {
    if ((*plugin_type_deinitialize[plugin->plugin->type])(plugin))
    {
      sql_print_error("Plugin '%s' of type %s failed deinitialization",
925
                      plugin->name.str, plugin_type_names[plugin->plugin->type].str);
unknown's avatar
unknown committed
926
    }
927 928
  }
  else if (plugin->plugin->deinit)
unknown's avatar
unknown committed
929 930
  {
    DBUG_PRINT("info", ("Deinitializing plugin: '%s'", plugin->name.str));
931
    if (plugin->plugin->deinit(plugin))
932
    {
unknown's avatar
unknown committed
933 934
      DBUG_PRINT("warning", ("Plugin '%s' deinit function returned error.",
                             plugin->name.str));
935
    }
unknown's avatar
unknown committed
936 937
  }
  plugin->state= PLUGIN_IS_UNINITIALIZED;
unknown's avatar
unknown committed
938 939 940 941 942 943 944 945

  /*
    We do the check here because NDB has a worker THD which doesn't
    exit until NDB is shut down.
  */
  if (ref_check && plugin->ref_count)
    sql_print_error("Plugin '%s' has ref_count=%d after deinitialization.",
                    plugin->name.str, plugin->ref_count);
946 947
}

unknown's avatar
unknown committed
948 949 950
static void plugin_del(struct st_plugin_int *plugin)
{
  DBUG_ENTER("plugin_del(plugin)");
Marc Alff's avatar
Marc Alff committed
951
  mysql_mutex_assert_owner(&LOCK_plugin);
952
  /* Free allocated strings before deleting the plugin. */
Marc Alff's avatar
Marc Alff committed
953
  mysql_rwlock_wrlock(&LOCK_system_variables_hash);
954
  mysql_del_sys_var_chain(plugin->system_vars);
Marc Alff's avatar
Marc Alff committed
955
  mysql_rwlock_unlock(&LOCK_system_variables_hash);
956
  restore_pluginvar_names(plugin->system_vars);
957
  plugin_vars_free_values(plugin->system_vars);
Konstantin Osipov's avatar
Konstantin Osipov committed
958
  my_hash_delete(&plugin_hash[plugin->plugin->type], (uchar*)plugin);
959 960
  if (plugin->plugin_dl)
    plugin_dl_del(&plugin->plugin_dl->dl);
unknown's avatar
unknown committed
961 962
  plugin->state= PLUGIN_IS_FREED;
  plugin_array_version++;
unknown's avatar
unknown committed
963
  free_root(&plugin->mem_root, MYF(0));
unknown's avatar
unknown committed
964 965 966
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
967
static void reap_plugins(void)
968
{
unknown's avatar
unknown committed
969 970
  uint count, idx;
  struct st_plugin_int *plugin, **reap, **list;
unknown's avatar
unknown committed
971

Marc Alff's avatar
Marc Alff committed
972
  mysql_mutex_assert_owner(&LOCK_plugin);
unknown's avatar
unknown committed
973 974 975

  if (!reap_needed)
    return;
unknown's avatar
unknown committed
976

unknown's avatar
unknown committed
977 978 979 980
  reap_needed= false;
  count= plugin_array.elements;
  reap= (struct st_plugin_int **)my_alloca(sizeof(plugin)*(count+1));
  *(reap++)= NULL;
unknown's avatar
unknown committed
981

unknown's avatar
unknown committed
982
  for (idx= 0; idx < count; idx++)
983
  {
unknown's avatar
unknown committed
984
    plugin= *dynamic_element(&plugin_array, idx, struct st_plugin_int **);
unknown's avatar
unknown committed
985 986 987 988 989 990 991
    if (plugin->state == PLUGIN_IS_DELETED && !plugin->ref_count)
    {
      /* change the status flag to prevent reaping by another thread */
      plugin->state= PLUGIN_IS_DYING;
      *(reap++)= plugin;
    }
  }
unknown's avatar
unknown committed
992

Marc Alff's avatar
Marc Alff committed
993
  mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
994 995 996

  list= reap;
  while ((plugin= *(--list)))
unknown's avatar
unknown committed
997
    plugin_deinitialize(plugin, true);
unknown's avatar
unknown committed
998

Marc Alff's avatar
Marc Alff committed
999
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
1000

unknown's avatar
unknown committed
1001
  while ((plugin= *(--reap)))
unknown's avatar
unknown committed
1002
    plugin_del(plugin);
unknown's avatar
unknown committed
1003

unknown's avatar
unknown committed
1004 1005 1006 1007 1008 1009 1010 1011 1012
  my_afree(reap);
}

static void intern_plugin_unlock(LEX *lex, plugin_ref plugin)
{
  int i;
  st_plugin_int *pi;
  DBUG_ENTER("intern_plugin_unlock");

Marc Alff's avatar
Marc Alff committed
1013
  mysql_mutex_assert_owner(&LOCK_plugin);
unknown's avatar
unknown committed
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

  if (!plugin)
    DBUG_VOID_RETURN;

  pi= plugin_ref_to_int(plugin);

#ifdef DBUG_OFF
  if (!pi->plugin_dl)
    DBUG_VOID_RETURN;
#else
1024
  my_free(plugin);
unknown's avatar
unknown committed
1025 1026 1027 1028 1029 1030
#endif

  DBUG_PRINT("info",("unlocking plugin, name= %s, ref_count= %d",
                     pi->name.str, pi->ref_count));
  if (lex)
  {
unknown's avatar
unknown committed
1031 1032 1033 1034 1035
    /*
      Remove one instance of this plugin from the use list.
      We are searching backwards so that plugins locked last
      could be unlocked faster - optimizing for LIFO semantics.
    */
unknown's avatar
unknown committed
1036 1037 1038 1039 1040 1041
    for (i= lex->plugins.elements - 1; i >= 0; i--)
      if (plugin == *dynamic_element(&lex->plugins, i, plugin_ref*))
      {
        delete_dynamic_element(&lex->plugins, i);
        break;
      }
unknown's avatar
unknown committed
1042
    DBUG_ASSERT(i >= 0);
1043
  }
unknown's avatar
unknown committed
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

  DBUG_ASSERT(pi->ref_count);
  pi->ref_count--;

  if (pi->state == PLUGIN_IS_DELETED && !pi->ref_count)
    reap_needed= true;

  DBUG_VOID_RETURN;
}


void plugin_unlock(THD *thd, plugin_ref plugin)
{
unknown's avatar
unknown committed
1057
  LEX *lex= thd ? thd->lex : 0;
unknown's avatar
unknown committed
1058 1059 1060 1061 1062 1063 1064 1065
  DBUG_ENTER("plugin_unlock");
  if (!plugin)
    DBUG_VOID_RETURN;
#ifdef DBUG_OFF
  /* built-in plugins don't need ref counting */
  if (!plugin_dlib(plugin))
    DBUG_VOID_RETURN;
#endif
Marc Alff's avatar
Marc Alff committed
1066
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
1067 1068
  intern_plugin_unlock(lex, plugin);
  reap_plugins();
Marc Alff's avatar
Marc Alff committed
1069
  mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
1070 1071 1072 1073 1074 1075
  DBUG_VOID_RETURN;
}


void plugin_unlock_list(THD *thd, plugin_ref *list, uint count)
{
unknown's avatar
unknown committed
1076
  LEX *lex= thd ? thd->lex : 0;
unknown's avatar
unknown committed
1077 1078
  DBUG_ENTER("plugin_unlock_list");
  DBUG_ASSERT(list);
Marc Alff's avatar
Marc Alff committed
1079
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
1080 1081 1082
  while (count--)
    intern_plugin_unlock(lex, *list++);
  reap_plugins();
Marc Alff's avatar
Marc Alff committed
1083
  mysql_mutex_unlock(&LOCK_plugin);
1084 1085 1086 1087
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
1088 1089
static int plugin_initialize(struct st_plugin_int *plugin)
{
1090
  int ret= 1;
unknown's avatar
unknown committed
1091
  DBUG_ENTER("plugin_initialize");
1092

Marc Alff's avatar
Marc Alff committed
1093
  mysql_mutex_assert_owner(&LOCK_plugin);
1094 1095
  uint state= plugin->state;
  DBUG_ASSERT(state == PLUGIN_IS_UNINITIALIZED);
1096

1097
  mysql_mutex_unlock(&LOCK_plugin);
1098 1099 1100 1101 1102
  if (plugin_type_initialize[plugin->plugin->type])
  {
    if ((*plugin_type_initialize[plugin->plugin->type])(plugin))
    {
      sql_print_error("Plugin '%s' registration as a %s failed.",
1103
                      plugin->name.str, plugin_type_names[plugin->plugin->type].str);
1104 1105 1106 1107 1108
      goto err;
    }
  }
  else if (plugin->plugin->init)
  {
1109
    if (plugin->plugin->init(plugin))
1110 1111 1112 1113 1114 1115
    {
      sql_print_error("Plugin '%s' init function returned error.",
                      plugin->name.str);
      goto err;
    }
  }
1116
  state= PLUGIN_IS_READY; // plugin->init() succeeded
1117

1118 1119 1120
  if (plugin->plugin->status_vars)
  {
#ifdef FIX_LATER
unknown's avatar
unknown committed
1121
    /*
1122
      We have a problem right now where we can not prepend without
unknown's avatar
unknown committed
1123
      breaking backwards compatibility. We will fix this shortly so
1124 1125 1126 1127 1128
      that engines have "use names" and we wil use those for
      CREATE TABLE, and use the plugin name then for adding automatic
      variable names.
    */
    SHOW_VAR array[2]= {
unknown's avatar
unknown committed
1129
      {plugin->plugin->name, (char*)plugin->plugin->status_vars, SHOW_ARRAY},
1130 1131 1132 1133 1134
      {0, 0, SHOW_UNDEF}
    };
    if (add_status_vars(array)) // add_status_vars makes a copy
      goto err;
#else
1135
    if (add_status_vars(plugin->plugin->status_vars))
1136
      goto err;
1137 1138 1139
#endif /* FIX_LATER */
  }

unknown's avatar
unknown committed
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
  /*
    set the plugin attribute of plugin's sys vars so they are pointing
    to the active plugin
  */
  if (plugin->system_vars)
  {
    sys_var_pluginvar *var= plugin->system_vars->cast_pluginvar();
    for (;;)
    {
      var->plugin= plugin;
      if (!var->next)
        break;
      var= var->next->cast_pluginvar();
    }
  }
1155

1156 1157
  ret= 0;

unknown's avatar
unknown committed
1158
err:
1159 1160 1161
  mysql_mutex_lock(&LOCK_plugin);
  plugin->state= state;

1162 1163
  /* maintain the obsolete @@have_innodb variable */
  if (!my_strcasecmp(&my_charset_latin1, plugin->name.str, "InnoDB"))
1164 1165
    have_innodb= state & PLUGIN_IS_READY ? SHOW_OPTION_YES
                                         : SHOW_OPTION_DISABLED;
1166 1167

  DBUG_RETURN(ret);
unknown's avatar
unknown committed
1168 1169
}

unknown's avatar
unknown committed
1170

1171 1172 1173 1174 1175 1176
extern "C" uchar *get_plugin_hash_key(const uchar *, size_t *, my_bool);
extern "C" uchar *get_bookmark_hash_key(const uchar *, size_t *, my_bool);


uchar *get_plugin_hash_key(const uchar *buff, size_t *length,
                           my_bool not_used __attribute__((unused)))
1177 1178 1179
{
  struct st_plugin_int *plugin= (st_plugin_int *)buff;
  *length= (uint)plugin->name.length;
1180
  return((uchar *)plugin->name.str);
1181 1182 1183
}


1184 1185
uchar *get_bookmark_hash_key(const uchar *buff, size_t *length,
                             my_bool not_used __attribute__((unused)))
unknown's avatar
unknown committed
1186 1187 1188
{
  struct st_bookmark *var= (st_bookmark *)buff;
  *length= var->name_len + 1;
unknown's avatar
unknown committed
1189
  return (uchar*) var->key;
unknown's avatar
unknown committed
1190 1191
}

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
static inline void convert_dash_to_underscore(char *str, int len)
{
  for (char *p= str; p <= str+len; p++)
    if (*p == '-')
      *p= '_';
}

static inline void convert_underscore_to_dash(char *str, int len)
{
  for (char *p= str; p <= str+len; p++)
    if (*p == '_')
      *p= '-';
}

Marc Alff's avatar
Marc Alff committed
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
#ifdef HAVE_PSI_INTERFACE
static PSI_mutex_key key_LOCK_plugin;

static PSI_mutex_info all_plugin_mutexes[]=
{
  { &key_LOCK_plugin, "LOCK_plugin", PSI_FLAG_GLOBAL}
};

static void init_plugin_psi_keys(void)
{
  const char* category= "sql";
  int count;

  if (PSI_server == NULL)
    return;

  count= array_elements(all_plugin_mutexes);
  PSI_server->register_mutex(category, all_plugin_mutexes, count);
}
#endif /* HAVE_PSI_INTERFACE */
unknown's avatar
unknown committed
1226

1227 1228 1229
/*
  The logic is that we first load and initialize all compiled in plugins.
  From there we load up the dynamic types (assuming we have not been told to
unknown's avatar
unknown committed
1230
  skip this part).
1231

unknown's avatar
unknown committed
1232
  Finally we initialize everything, aka the dynamic that have yet to initialize.
1233
*/
unknown's avatar
unknown committed
1234
int plugin_init(int *argc, char **argv, int flags)
unknown's avatar
unknown committed
1235
{
1236
  uint i;
1237
  bool is_myisam;
unknown's avatar
unknown committed
1238 1239
  struct st_mysql_plugin **builtins;
  struct st_mysql_plugin *plugin;
unknown's avatar
unknown committed
1240 1241
  struct st_plugin_int tmp, *plugin_ptr, **reap;
  MEM_ROOT tmp_root;
1242 1243
  bool reaped_mandatory_plugin= false;
  bool mandatory= true;
unknown's avatar
unknown committed
1244 1245 1246 1247 1248
  DBUG_ENTER("plugin_init");

  if (initialized)
    DBUG_RETURN(0);

Marc Alff's avatar
Marc Alff committed
1249 1250 1251 1252
#ifdef HAVE_PSI_INTERFACE
  init_plugin_psi_keys();
#endif

unknown's avatar
unknown committed
1253 1254 1255
  init_alloc_root(&plugin_mem_root, 4096, 4096);
  init_alloc_root(&tmp_root, 4096, 4096);

Konstantin Osipov's avatar
Konstantin Osipov committed
1256 1257
  if (my_hash_init(&bookmark_hash, &my_charset_bin, 16, 0, 0,
                   get_bookmark_hash_key, NULL, HASH_UNIQUE))
unknown's avatar
unknown committed
1258
      goto err;
unknown's avatar
unknown committed
1259

unknown's avatar
unknown committed
1260

Marc Alff's avatar
Marc Alff committed
1261
  mysql_mutex_init(key_LOCK_plugin, &LOCK_plugin, MY_MUTEX_INIT_FAST);
unknown's avatar
unknown committed
1262 1263

  if (my_init_dynamic_array(&plugin_dl_array,
unknown's avatar
unknown committed
1264
                            sizeof(struct st_plugin_dl *),16,16) ||
unknown's avatar
unknown committed
1265
      my_init_dynamic_array(&plugin_array,
unknown's avatar
unknown committed
1266
                            sizeof(struct st_plugin_int *),16,16))
unknown's avatar
unknown committed
1267 1268 1269 1270
    goto err;

  for (i= 0; i < MYSQL_MAX_PLUGIN_TYPE_NUM; i++)
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
1271 1272
    if (my_hash_init(&plugin_hash[i], system_charset_info, 16, 0, 0,
                     get_plugin_hash_key, NULL, HASH_UNIQUE))
unknown's avatar
unknown committed
1273 1274
      goto err;
  }
unknown's avatar
unknown committed
1275

Marc Alff's avatar
Marc Alff committed
1276
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
1277 1278 1279

  initialized= 1;

unknown's avatar
unknown committed
1280
  /*
1281 1282
    First we register builtin plugins
  */
1283
  for (builtins= mysql_mandatory_plugins; *builtins || mandatory; builtins++)
unknown's avatar
unknown committed
1284
  {
1285 1286 1287 1288 1289 1290 1291
    if (!*builtins)
    {
      builtins= mysql_optional_plugins;
      mandatory= false;
      if (!*builtins)
        break;
    }
unknown's avatar
unknown committed
1292 1293
    for (plugin= *builtins; plugin->info; plugin++)
    {
1294
      if (opt_ignore_builtin_innodb &&
1295 1296 1297
          !my_strnncoll(&my_charset_latin1, (const uchar*) plugin->name,
                        6, (const uchar*) "InnoDB", 6))
        continue;
unknown's avatar
unknown committed
1298 1299
      bzero(&tmp, sizeof(tmp));
      tmp.plugin= plugin;
unknown's avatar
unknown committed
1300 1301
      tmp.name.str= (char *)plugin->name;
      tmp.name.length= strlen(plugin->name);
1302
      tmp.state= 0;
Sergey Vojtovich's avatar
Sergey Vojtovich committed
1303
      tmp.load_option= mandatory ? PLUGIN_FORCE : PLUGIN_ON;
Marc Alff's avatar
Marc Alff committed
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321

      /*
        If the performance schema is compiled in,
        treat the storage engine plugin as 'mandatory',
        to suppress any plugin-level options such as '--performance-schema'.
        This is specific to the performance schema, and is done on purpose:
        the server-level option '--performance-schema' controls the overall
        performance schema initialization, which consists of much more that
        the underlying storage engine initialization.
        See mysqld.cc, set_vars.cc.
        Suppressing ways to interfere directly with the storage engine alone
        prevents awkward situations where:
        - the user wants the performance schema functionality, by using
          '--enable-performance-schema' (the server option),
        - yet disable explicitly a component needed for the functionality
          to work, by using '--skip-performance-schema' (the plugin)
      */
      if (!my_strcasecmp(&my_charset_latin1, plugin->name, "PERFORMANCE_SCHEMA"))
Sergey Vojtovich's avatar
Sergey Vojtovich committed
1322
        tmp.load_option= PLUGIN_FORCE;
Marc Alff's avatar
Marc Alff committed
1323

unknown's avatar
unknown committed
1324
      free_root(&tmp_root, MYF(MY_MARK_BLOCKS_FREE));
1325
      if (test_plugin_options(&tmp_root, &tmp, argc, argv))
1326 1327 1328
        tmp.state= PLUGIN_IS_DISABLED;
      else
        tmp.state= PLUGIN_IS_UNINITIALIZED;
unknown's avatar
unknown committed
1329 1330 1331 1332
      if (register_builtin(plugin, &tmp, &plugin_ptr))
        goto err_unlock;

      /* only initialize MyISAM and CSV at this stage */
unknown's avatar
unknown committed
1333
      if (!(is_myisam=
unknown's avatar
unknown committed
1334 1335 1336 1337
            !my_strcasecmp(&my_charset_latin1, plugin->name, "MyISAM")) &&
          my_strcasecmp(&my_charset_latin1, plugin->name, "CSV"))
        continue;

1338
      if (plugin_ptr->state != PLUGIN_IS_UNINITIALIZED ||
1339
          plugin_initialize(plugin_ptr))
unknown's avatar
unknown committed
1340 1341 1342
        goto err_unlock;

      /*
unknown's avatar
unknown committed
1343
        initialize the global default storage engine so that it may
unknown's avatar
unknown committed
1344 1345 1346
        not be null in any child thread.
      */
      if (is_myisam)
1347
      {
unknown's avatar
unknown committed
1348
        DBUG_ASSERT(!global_system_variables.table_plugin);
unknown's avatar
unknown committed
1349 1350
        global_system_variables.table_plugin=
          my_intern_plugin_lock(NULL, plugin_int_to_ref(plugin_ptr));
unknown's avatar
unknown committed
1351
        DBUG_ASSERT(plugin_ptr->ref_count == 1);
1352
      }
unknown's avatar
unknown committed
1353 1354
    }
  }
1355

unknown's avatar
unknown committed
1356 1357
  /* should now be set to MyISAM storage engine */
  DBUG_ASSERT(global_system_variables.table_plugin);
unknown's avatar
unknown committed
1358

Marc Alff's avatar
Marc Alff committed
1359
  mysql_mutex_unlock(&LOCK_plugin);
1360

1361
  /* Register all dynamic plugins */
unknown's avatar
unknown committed
1362 1363
  if (!(flags & PLUGIN_INIT_SKIP_DYNAMIC_LOADING))
  {
1364 1365
    if (opt_plugin_load)
      plugin_load_list(&tmp_root, argc, argv, opt_plugin_load);
unknown's avatar
unknown committed
1366 1367 1368
    if (!(flags & PLUGIN_INIT_SKIP_PLUGIN_TABLE))
      plugin_load(&tmp_root, argc, argv);
  }
1369

unknown's avatar
unknown committed
1370 1371
  if (flags & PLUGIN_INIT_SKIP_INITIALIZATION)
    goto end;
unknown's avatar
unknown committed
1372

1373 1374 1375
  /*
    Now we initialize all remaining plugins
  */
1376

Marc Alff's avatar
Marc Alff committed
1377
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
1378 1379 1380
  reap= (st_plugin_int **) my_alloca((plugin_array.elements+1) * sizeof(void*));
  *(reap++)= NULL;

1381 1382
  for (i= 0; i < plugin_array.elements; i++)
  {
unknown's avatar
unknown committed
1383
    plugin_ptr= *dynamic_element(&plugin_array, i, struct st_plugin_int **);
unknown's avatar
unknown committed
1384
    if (plugin_ptr->state == PLUGIN_IS_UNINITIALIZED)
1385
    {
unknown's avatar
unknown committed
1386
      if (plugin_initialize(plugin_ptr))
unknown's avatar
unknown committed
1387
      {
unknown's avatar
unknown committed
1388 1389
        plugin_ptr->state= PLUGIN_IS_DYING;
        *(reap++)= plugin_ptr;
unknown's avatar
unknown committed
1390
      }
1391 1392 1393
    }
  }

unknown's avatar
unknown committed
1394 1395
  /*
    Check if any plugins have to be reaped
unknown's avatar
unknown committed
1396
  */
unknown's avatar
unknown committed
1397 1398
  while ((plugin_ptr= *(--reap)))
  {
Marc Alff's avatar
Marc Alff committed
1399
    mysql_mutex_unlock(&LOCK_plugin);
Sergey Vojtovich's avatar
Sergey Vojtovich committed
1400 1401
    if (plugin_ptr->load_option == PLUGIN_FORCE ||
        plugin_ptr->load_option == PLUGIN_FORCE_PLUS_PERMANENT)
1402
      reaped_mandatory_plugin= TRUE;
unknown's avatar
unknown committed
1403
    plugin_deinitialize(plugin_ptr, true);
Marc Alff's avatar
Marc Alff committed
1404
    mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
1405 1406 1407
    plugin_del(plugin_ptr);
  }

Marc Alff's avatar
Marc Alff committed
1408
  mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
1409
  my_afree(reap);
1410 1411
  if (reaped_mandatory_plugin)
    goto err;
unknown's avatar
unknown committed
1412 1413 1414

end:
  free_root(&tmp_root, MYF(0));
1415

unknown's avatar
unknown committed
1416
  DBUG_RETURN(0);
1417

unknown's avatar
unknown committed
1418
err_unlock:
Marc Alff's avatar
Marc Alff committed
1419
  mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
1420
err:
unknown's avatar
unknown committed
1421
  free_root(&tmp_root, MYF(0));
unknown's avatar
unknown committed
1422 1423 1424 1425
  DBUG_RETURN(1);
}


unknown's avatar
unknown committed
1426
static bool register_builtin(struct st_mysql_plugin *plugin,
unknown's avatar
unknown committed
1427 1428
                             struct st_plugin_int *tmp,
                             struct st_plugin_int **ptr)
unknown's avatar
unknown committed
1429
{
unknown's avatar
unknown committed
1430
  DBUG_ENTER("register_builtin");
unknown's avatar
unknown committed
1431 1432
  tmp->ref_count= 0;
  tmp->plugin_dl= 0;
unknown's avatar
unknown committed
1433

1434
  if (insert_dynamic(&plugin_array, (uchar*)&tmp))
unknown's avatar
unknown committed
1435 1436
    DBUG_RETURN(1);

unknown's avatar
unknown committed
1437 1438
  *ptr= *dynamic_element(&plugin_array, plugin_array.elements - 1,
                         struct st_plugin_int **)=
unknown's avatar
unknown committed
1439
        (struct st_plugin_int *) memdup_root(&plugin_mem_root, (uchar*)tmp,
unknown's avatar
unknown committed
1440
                                             sizeof(struct st_plugin_int));
unknown's avatar
unknown committed
1441

unknown's avatar
unknown committed
1442
  if (my_hash_insert(&plugin_hash[plugin->type],(uchar*) *ptr))
unknown's avatar
unknown committed
1443 1444 1445 1446 1447 1448
    DBUG_RETURN(1);

  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
1449 1450 1451 1452
/*
  called only by plugin_init()
*/
static void plugin_load(MEM_ROOT *tmp_root, int *argc, char **argv)
1453
{
1454
  THD thd;
1455 1456 1457
  TABLE_LIST tables;
  TABLE *table;
  READ_RECORD read_record_info;
1458
  int error;
1459
  THD *new_thd= &thd;
1460
  bool result;
unknown's avatar
unknown committed
1461
#ifdef EMBEDDED_LIBRARY
1462
  No_such_table_error_handler error_handler;
unknown's avatar
unknown committed
1463
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
1464
  DBUG_ENTER("plugin_load");
1465

unknown's avatar
unknown committed
1466
  new_thd->thread_stack= (char*) &tables;
1467 1468 1469
  new_thd->store_globals();
  new_thd->db= my_strdup("mysql", MYF(0));
  new_thd->db_length= 5;
1470
  bzero((char*) &thd.net, sizeof(thd.net));
Konstantin Osipov's avatar
Konstantin Osipov committed
1471
  tables.init_one_table("mysql", 5, "plugin", 6, "plugin", TL_READ);
unknown's avatar
unknown committed
1472 1473 1474 1475 1476 1477

#ifdef EMBEDDED_LIBRARY
  /*
    When building an embedded library, if the mysql.plugin table
    does not exist, we silently ignore the missing table
  */
1478 1479 1480 1481 1482 1483 1484 1485
  new_thd->push_internal_handler(&error_handler);
#endif /* EMBEDDED_LIBRARY */

  result= open_and_lock_tables(new_thd, &tables, FALSE, MYSQL_LOCK_IGNORE_TIMEOUT);

#ifdef EMBEDDED_LIBRARY
  new_thd->pop_internal_handler();
  if (error_handler.safely_trapped_errors())
unknown's avatar
unknown committed
1486 1487 1488
    goto end;
#endif /* EMBEDDED_LIBRARY */

1489
  if (result)
1490 1491
  {
    DBUG_PRINT("error",("Can't open plugin table"));
1492 1493
    sql_print_error("Can't open the mysql.plugin table. Please "
                    "run mysql_upgrade to create it.");
1494 1495 1496
    goto end;
  }
  table= tables.table;
1497
  init_read_record(&read_record_info, new_thd, table, NULL, 1, 0, FALSE);
1498
  table->use_all_columns();
1499 1500 1501
  /*
    there're no other threads running yet, so we don't need a mutex.
    but plugin_add() before is designed to work in multi-threaded
Marc Alff's avatar
Marc Alff committed
1502
    environment, and it uses mysql_mutex_assert_owner(), so we lock
1503 1504
    the mutex here to satisfy the assert
  */
Marc Alff's avatar
Marc Alff committed
1505
  mysql_mutex_lock(&LOCK_plugin);
1506 1507 1508
  while (!(error= read_record_info.read_record(&read_record_info)))
  {
    DBUG_PRINT("info", ("init plugin record"));
unknown's avatar
unknown committed
1509
    String str_name, str_dl;
unknown's avatar
unknown committed
1510 1511
    get_field(tmp_root, table->field[0], &str_name);
    get_field(tmp_root, table->field[1], &str_dl);
unknown's avatar
unknown committed
1512

unknown's avatar
unknown committed
1513 1514 1515
    LEX_STRING name= {(char *)str_name.ptr(), str_name.length()};
    LEX_STRING dl= {(char *)str_dl.ptr(), str_dl.length()};

unknown's avatar
unknown committed
1516
    if (plugin_add(tmp_root, &name, &dl, argc, argv, REPORT_TO_LOG))
unknown's avatar
unknown committed
1517 1518
      sql_print_warning("Couldn't load plugin named '%s' with soname '%s'.",
                        str_name.c_ptr(), str_dl.c_ptr());
1519
    free_root(tmp_root, MYF(MY_MARK_BLOCKS_FREE));
1520
  }
Marc Alff's avatar
Marc Alff committed
1521
  mysql_mutex_unlock(&LOCK_plugin);
1522 1523 1524
  if (error > 0)
    sql_print_error(ER(ER_GET_ERRNO), my_errno);
  end_read_record(&read_record_info);
1525
  table->m_needs_reopen= TRUE;                  // Force close to free memory
1526
  close_mysql_tables(new_thd);
1527 1528 1529 1530 1531 1532 1533
end:
  /* Remember that we don't have a THD */
  my_pthread_setspecific_ptr(THR_THD, 0);
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
1534 1535 1536 1537 1538
/*
  called only by plugin_init()
*/
static bool plugin_load_list(MEM_ROOT *tmp_root, int *argc, char **argv,
                             const char *list)
1539
{
unknown's avatar
unknown committed
1540 1541 1542 1543 1544 1545 1546
  char buffer[FN_REFLEN];
  LEX_STRING name= {buffer, 0}, dl= {NULL, 0}, *str= &name;
  struct st_plugin_dl *plugin_dl;
  struct st_mysql_plugin *plugin;
  char *p= buffer;
  DBUG_ENTER("plugin_load_list");
  while (list)
1547
  {
unknown's avatar
unknown committed
1548
    if (p == buffer + sizeof(buffer) - 1)
unknown's avatar
unknown committed
1549 1550 1551 1552 1553
    {
      sql_print_error("plugin-load parameter too long");
      DBUG_RETURN(TRUE);
    }

unknown's avatar
unknown committed
1554 1555 1556 1557 1558 1559 1560 1561
    switch ((*(p++)= *(list++))) {
    case '\0':
      list= NULL; /* terminate the loop */
      /* fall through */
#ifndef __WIN__
    case ':':     /* can't use this as delimiter as it may be drive letter */
#endif
    case ';':
unknown's avatar
unknown committed
1562 1563
      str->str[str->length]= '\0';
      if (str == &name)  // load all plugins in named module
unknown's avatar
unknown committed
1564
      {
unknown's avatar
unknown committed
1565 1566 1567 1568 1569 1570
        if (!name.length)
        {
          p--;    /* reset pointer */
          continue;
        }

unknown's avatar
unknown committed
1571
        dl= name;
Marc Alff's avatar
Marc Alff committed
1572
        mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
1573 1574 1575 1576 1577 1578
        if ((plugin_dl= plugin_dl_add(&dl, REPORT_TO_LOG)))
        {
          for (plugin= plugin_dl->plugins; plugin->info; plugin++)
          {
            name.str= (char *) plugin->name;
            name.length= strlen(name.str);
unknown's avatar
unknown committed
1579

unknown's avatar
unknown committed
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
            free_root(tmp_root, MYF(MY_MARK_BLOCKS_FREE));
            if (plugin_add(tmp_root, &name, &dl, argc, argv, REPORT_TO_LOG))
              goto error;
          }
          plugin_dl_del(&dl); // reduce ref count
        }
      }
      else
      {
        free_root(tmp_root, MYF(MY_MARK_BLOCKS_FREE));
Marc Alff's avatar
Marc Alff committed
1590
        mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
1591 1592 1593
        if (plugin_add(tmp_root, &name, &dl, argc, argv, REPORT_TO_LOG))
          goto error;
      }
Marc Alff's avatar
Marc Alff committed
1594
      mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
1595 1596 1597 1598 1599 1600 1601 1602
      name.length= dl.length= 0;
      dl.str= NULL; name.str= p= buffer;
      str= &name;
      continue;
    case '=':
    case '#':
      if (str == &name)
      {
unknown's avatar
unknown committed
1603
        name.str[name.length]= '\0';
unknown's avatar
unknown committed
1604 1605 1606 1607 1608 1609 1610 1611
        str= &dl;
        str->str= p;
        continue;
      }
    default:
      str->length++;
      continue;
    }
1612
  }
unknown's avatar
unknown committed
1613 1614
  DBUG_RETURN(FALSE);
error:
Marc Alff's avatar
Marc Alff committed
1615
  mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
1616 1617 1618 1619
  sql_print_error("Couldn't load plugin named '%s' with soname '%s'.",
                  name.str, dl.str);
  DBUG_RETURN(TRUE);
}
1620

unknown's avatar
unknown committed
1621

1622
void plugin_shutdown(void)
1623
{
1624
  uint i, count= plugin_array.elements;
unknown's avatar
unknown committed
1625 1626
  struct st_plugin_int **plugins, *plugin;
  struct st_plugin_dl **dl;
1627 1628
  DBUG_ENTER("plugin_shutdown");

1629
  if (initialized)
1630
  {
Marc Alff's avatar
Marc Alff committed
1631
    mysql_mutex_lock(&LOCK_plugin);
1632

unknown's avatar
unknown committed
1633
    reap_needed= true;
unknown's avatar
unknown committed
1634

unknown's avatar
unknown committed
1635 1636 1637 1638 1639 1640 1641 1642 1643
    /*
      We want to shut down plugins in a reasonable order, this will
      become important when we have plugins which depend upon each other.
      Circular references cannot be reaped so they are forced afterwards.
      TODO: Have an additional step here to notify all active plugins that
      shutdown is requested to allow plugins to deinitialize in parallel.
    */
    while (reap_needed && (count= plugin_array.elements))
    {
unknown's avatar
unknown committed
1644
      reap_plugins();
1645
      for (i= 0; i < count; i++)
unknown's avatar
unknown committed
1646
      {
unknown's avatar
unknown committed
1647
        plugin= *dynamic_element(&plugin_array, i, struct st_plugin_int **);
1648 1649
        if (plugin->state == PLUGIN_IS_READY)
        {
unknown's avatar
unknown committed
1650 1651 1652 1653
          plugin->state= PLUGIN_IS_DELETED;
          reap_needed= true;
        }
      }
unknown's avatar
unknown committed
1654 1655 1656 1657 1658 1659 1660 1661
      if (!reap_needed)
      {
        /*
          release any plugin references held.
        */
        unlock_variables(NULL, &global_system_variables);
        unlock_variables(NULL, &max_system_variables);
      }
unknown's avatar
unknown committed
1662
    }
unknown's avatar
unknown committed
1663

unknown's avatar
unknown committed
1664 1665 1666 1667 1668 1669 1670
    plugins= (struct st_plugin_int **) my_alloca(sizeof(void*) * (count+1));

    /*
      If we have any plugins which did not die cleanly, we force shutdown
    */
    for (i= 0; i < count; i++)
    {
unknown's avatar
unknown committed
1671
      plugins[i]= *dynamic_element(&plugin_array, i, struct st_plugin_int **);
unknown's avatar
unknown committed
1672 1673 1674 1675
      /* change the state to ensure no reaping races */
      if (plugins[i]->state == PLUGIN_IS_DELETED)
        plugins[i]->state= PLUGIN_IS_DYING;
    }
Marc Alff's avatar
Marc Alff committed
1676
    mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
1677

unknown's avatar
unknown committed
1678 1679 1680 1681
    /*
      We loop through all plugins and call deinit() if they have one.
    */
    for (i= 0; i < count; i++)
1682 1683
      if (!(plugins[i]->state & (PLUGIN_IS_UNINITIALIZED | PLUGIN_IS_FREED |
                                 PLUGIN_IS_DISABLED)))
unknown's avatar
unknown committed
1684
      {
1685 1686
        sql_print_warning("Plugin '%s' will be forced to shutdown",
                          plugins[i]->name.str);
unknown's avatar
unknown committed
1687 1688 1689 1690
        /*
          We are forcing deinit on plugins so we don't want to do a ref_count
          check until we have processed all the plugins.
        */
unknown's avatar
unknown committed
1691 1692 1693
        plugin_deinitialize(plugins[i], false);
      }

unknown's avatar
unknown committed
1694 1695 1696
    /*
      It's perfectly safe not to lock LOCK_plugin, as there're no
      concurrent threads anymore. But some functions called from here
Marc Alff's avatar
Marc Alff committed
1697
      use mysql_mutex_assert_owner(), so we lock the mutex to satisfy it
unknown's avatar
unknown committed
1698
    */
Marc Alff's avatar
Marc Alff committed
1699
    mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
1700

unknown's avatar
unknown committed
1701 1702 1703 1704 1705
    /*
      We defer checking ref_counts until after all plugins are deinitialized
      as some may have worker threads holding on to plugin references.
    */
    for (i= 0; i < count; i++)
unknown's avatar
unknown committed
1706
    {
unknown's avatar
unknown committed
1707 1708 1709 1710 1711
      if (plugins[i]->ref_count)
        sql_print_error("Plugin '%s' has ref_count=%d after shutdown.",
                        plugins[i]->name.str, plugins[i]->ref_count);
      if (plugins[i]->state & PLUGIN_IS_UNINITIALIZED)
        plugin_del(plugins[i]);
unknown's avatar
unknown committed
1712
    }
1713

unknown's avatar
unknown committed
1714 1715 1716
    /*
      Now we can deallocate all memory.
    */
unknown's avatar
unknown committed
1717

unknown's avatar
unknown committed
1718 1719
    cleanup_variables(NULL, &global_system_variables);
    cleanup_variables(NULL, &max_system_variables);
Marc Alff's avatar
Marc Alff committed
1720
    mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
1721 1722

    initialized= 0;
Marc Alff's avatar
Marc Alff committed
1723
    mysql_mutex_destroy(&LOCK_plugin);
1724

unknown's avatar
unknown committed
1725
    my_afree(plugins);
1726 1727
  }

unknown's avatar
unknown committed
1728
  /* Dispose of the memory */
unknown's avatar
unknown committed
1729

1730
  for (i= 0; i < MYSQL_MAX_PLUGIN_TYPE_NUM; i++)
Konstantin Osipov's avatar
Konstantin Osipov committed
1731
    my_hash_free(&plugin_hash[i]);
1732
  delete_dynamic(&plugin_array);
unknown's avatar
unknown committed
1733 1734 1735 1736

  count= plugin_dl_array.elements;
  dl= (struct st_plugin_dl **)my_alloca(sizeof(void*) * count);
  for (i= 0; i < count; i++)
unknown's avatar
unknown committed
1737
    dl[i]= *dynamic_element(&plugin_dl_array, i, struct st_plugin_dl **);
1738
  for (i= 0; i < plugin_dl_array.elements; i++)
unknown's avatar
unknown committed
1739 1740
    free_plugin_mem(dl[i]);
  my_afree(dl);
1741
  delete_dynamic(&plugin_dl_array);
unknown's avatar
unknown committed
1742

Konstantin Osipov's avatar
Konstantin Osipov committed
1743
  my_hash_free(&bookmark_hash);
unknown's avatar
unknown committed
1744
  free_root(&plugin_mem_root, MYF(0));
unknown's avatar
unknown committed
1745

unknown's avatar
unknown committed
1746 1747
  global_variables_dynamic_size= 0;

1748 1749 1750 1751
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
1752
bool mysql_install_plugin(THD *thd, const LEX_STRING *name, const LEX_STRING *dl)
1753 1754 1755
{
  TABLE_LIST tables;
  TABLE *table;
1756 1757
  int error, argc=orig_argc;
  char **argv=orig_argv;
1758 1759
  struct st_plugin_int *tmp;
  DBUG_ENTER("mysql_install_plugin");
unknown's avatar
unknown committed
1760

1761 1762 1763 1764 1765 1766
  if (opt_noacl)
  {
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
    DBUG_RETURN(TRUE);
  }

Konstantin Osipov's avatar
Konstantin Osipov committed
1767
  tables.init_one_table("mysql", 5, "plugin", 6, "plugin", TL_WRITE);
1768
  if (check_table_access(thd, INSERT_ACL, &tables, FALSE, 1, FALSE))
1769
    DBUG_RETURN(TRUE);
1770

unknown's avatar
unknown committed
1771
  /* need to open before acquiring LOCK_plugin or it will deadlock */
1772 1773
  if (! (table = open_ltable(thd, &tables, TL_WRITE,
                             MYSQL_LOCK_IGNORE_TIMEOUT)))
unknown's avatar
unknown committed
1774 1775
    DBUG_RETURN(TRUE);

1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
  /*
    Pre-acquire audit plugins for events that may potentially occur
    during [UN]INSTALL PLUGIN.

    When audit event is triggered, audit subsystem acquires interested
    plugins by walking through plugin list. Evidently plugin list
    iterator protects plugin list by acquiring LOCK_plugin, see
    plugin_foreach_with_mask().

    On the other hand [UN]INSTALL PLUGIN is acquiring LOCK_plugin
    rather for a long time.

    When audit event is triggered during [UN]INSTALL PLUGIN, plugin
    list iterator acquires the same lock (within the same thread)
    second time.

    This hack should be removed when LOCK_plugin is fixed so it
    protects only what it supposed to protect.
  */
  mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_GENERAL_CLASS);

Marc Alff's avatar
Marc Alff committed
1797 1798
  mysql_mutex_lock(&LOCK_plugin);
  mysql_rwlock_wrlock(&LOCK_system_variables_hash);
1799

1800 1801 1802 1803 1804
  if (my_load_defaults(MYSQL_CONFIG_NAME, load_default_groups, &argc, &argv, NULL))
  {
    report_error(REPORT_TO_USER, ER_PLUGIN_IS_NOT_LOADED, name->str);
    goto err;
  }
1805
  error= plugin_add(thd->mem_root, name, dl, &argc, argv, REPORT_TO_USER);
1806 1807
  if (argv)
    free_defaults(argv);
Marc Alff's avatar
Marc Alff committed
1808
  mysql_rwlock_unlock(&LOCK_system_variables_hash);
unknown's avatar
unknown committed
1809 1810

  if (error || !(tmp= plugin_find_internal(name, MYSQL_ANY_PLUGIN)))
1811
    goto err;
1812

1813
  if (tmp->state == PLUGIN_IS_DISABLED)
1814
  {
1815 1816 1817 1818 1819 1820 1821 1822
    push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_CANT_INITIALIZE_UDF, ER(ER_CANT_INITIALIZE_UDF),
                        name->str, "Plugin is disabled");
  }
  else
  {
    if (plugin_initialize(tmp))
    {
1823
      mysql_mutex_unlock(&LOCK_plugin);
1824 1825 1826 1827
      my_error(ER_CANT_INITIALIZE_UDF, MYF(0), name->str,
               "Plugin initialization function failed.");
      goto deinit;
    }
1828
  }
unknown's avatar
unknown committed
1829

1830 1831 1832 1833 1834
  /*
    We do not replicate the INSTALL PLUGIN statement. Disable binlogging
    of the insert into the plugin table, so that it is not replicated in
    row based mode.
  */
1835
  mysql_mutex_unlock(&LOCK_plugin);
1836
  tmp_disable_binlog(thd);
unknown's avatar
unknown committed
1837
  table->use_all_columns();
1838 1839 1840
  restore_record(table, s->default_values);
  table->field[0]->store(name->str, name->length, system_charset_info);
  table->field[1]->store(dl->str, dl->length, files_charset_info);
1841
  error= table->file->ha_write_row(table->record[0]);
1842
  reenable_binlog(thd);
1843 1844 1845 1846 1847 1848 1849
  if (error)
  {
    table->file->print_error(error, MYF(0));
    goto deinit;
  }
  DBUG_RETURN(FALSE);
deinit:
1850
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
1851 1852 1853
  tmp->state= PLUGIN_IS_DELETED;
  reap_needed= true;
  reap_plugins();
unknown's avatar
unknown committed
1854
err:
Marc Alff's avatar
Marc Alff committed
1855
  mysql_mutex_unlock(&LOCK_plugin);
1856 1857 1858 1859
  DBUG_RETURN(TRUE);
}


unknown's avatar
unknown committed
1860
bool mysql_uninstall_plugin(THD *thd, const LEX_STRING *name)
1861 1862 1863 1864 1865
{
  TABLE *table;
  TABLE_LIST tables;
  struct st_plugin_int *plugin;
  DBUG_ENTER("mysql_uninstall_plugin");
unknown's avatar
unknown committed
1866

1867 1868 1869 1870 1871 1872
  if (opt_noacl)
  {
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
    DBUG_RETURN(TRUE);
  }

Konstantin Osipov's avatar
Konstantin Osipov committed
1873
  tables.init_one_table("mysql", 5, "plugin", 6, "plugin", TL_WRITE);
unknown's avatar
unknown committed
1874

1875
  if (check_table_access(thd, DELETE_ACL, &tables, FALSE, 1, FALSE))
1876
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
1877

unknown's avatar
unknown committed
1878
  /* need to open before acquiring LOCK_plugin or it will deadlock */
1879
  if (! (table= open_ltable(thd, &tables, TL_WRITE, MYSQL_LOCK_IGNORE_TIMEOUT)))
unknown's avatar
unknown committed
1880 1881
    DBUG_RETURN(TRUE);

1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
  /*
    Pre-acquire audit plugins for events that may potentially occur
    during [UN]INSTALL PLUGIN.

    When audit event is triggered, audit subsystem acquires interested
    plugins by walking through plugin list. Evidently plugin list
    iterator protects plugin list by acquiring LOCK_plugin, see
    plugin_foreach_with_mask().

    On the other hand [UN]INSTALL PLUGIN is acquiring LOCK_plugin
    rather for a long time.

    When audit event is triggered during [UN]INSTALL PLUGIN, plugin
    list iterator acquires the same lock (within the same thread)
    second time.

    This hack should be removed when LOCK_plugin is fixed so it
    protects only what it supposed to protect.
  */
  mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_GENERAL_CLASS);

Marc Alff's avatar
Marc Alff committed
1903
  mysql_mutex_lock(&LOCK_plugin);
1904 1905
  if (!(plugin= plugin_find_internal(name, MYSQL_ANY_PLUGIN)) ||
      plugin->state & (PLUGIN_IS_UNINITIALIZED | PLUGIN_IS_DYING))
1906 1907 1908 1909
  {
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PLUGIN", name->str);
    goto err;
  }
unknown's avatar
unknown committed
1910 1911
  if (!plugin->plugin_dl)
  {
1912 1913
    push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                 WARN_PLUGIN_DELETE_BUILTIN, ER(WARN_PLUGIN_DELETE_BUILTIN));
unknown's avatar
unknown committed
1914 1915 1916
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PLUGIN", name->str);
    goto err;
  }
Sergey Vojtovich's avatar
Sergey Vojtovich committed
1917 1918 1919 1920 1921
  if (plugin->load_option == PLUGIN_FORCE_PLUS_PERMANENT)
  {
    my_error(ER_PLUGIN_IS_PERMANENT, MYF(0), name->str);
    goto err;
  }
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
  /*
    Error message for ER_PLUGIN_IS_PERMANENT is not suitable for
    plugins marked as not dynamically uninstallable, so we have a
    separate one instead of changing the old one.
   */
  if (plugin->plugin->flags & PLUGIN_OPT_NO_UNINSTALL)
  {
    my_error(ER_PLUGIN_NO_UNINSTALL, MYF(0), plugin->plugin->name);
    goto err;
  }
1932

unknown's avatar
unknown committed
1933
  plugin->state= PLUGIN_IS_DELETED;
unknown's avatar
unknown committed
1934
  if (plugin->ref_count)
1935 1936
    push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                 WARN_PLUGIN_BUSY, ER(WARN_PLUGIN_BUSY));
unknown's avatar
unknown committed
1937
  else
unknown's avatar
unknown committed
1938 1939
    reap_needed= true;
  reap_plugins();
Marc Alff's avatar
Marc Alff committed
1940
  mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
1941

1942
  uchar user_key[MAX_KEY_LENGTH];
1943
  table->use_all_columns();
1944
  table->field[0]->store(name->str, name->length, system_charset_info);
1945 1946 1947 1948
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);
  if (! table->file->index_read_idx_map(table->record[0], 0, user_key,
                                        HA_WHOLE_KEY, HA_READ_KEY_EXACT))
1949 1950
  {
    int error;
1951 1952 1953 1954 1955 1956 1957 1958 1959
    /*
      We do not replicate the UNINSTALL PLUGIN statement. Disable binlogging
      of the delete from the plugin table, so that it is not replicated in
      row based mode.
    */
    tmp_disable_binlog(thd);
    error= table->file->ha_delete_row(table->record[0]);
    reenable_binlog(thd);
    if (error)
1960 1961
    {
      table->file->print_error(error, MYF(0));
unknown's avatar
unknown committed
1962
      DBUG_RETURN(TRUE);
1963 1964 1965 1966
    }
  }
  DBUG_RETURN(FALSE);
err:
Marc Alff's avatar
Marc Alff committed
1967
  mysql_mutex_unlock(&LOCK_plugin);
1968 1969
  DBUG_RETURN(TRUE);
}
unknown's avatar
unknown committed
1970

unknown's avatar
unknown committed
1971 1972

bool plugin_foreach_with_mask(THD *thd, plugin_foreach_func *func,
1973
                       int type, uint state_mask, void *arg)
unknown's avatar
unknown committed
1974
{
1975 1976 1977
  uint idx, total;
  struct st_plugin_int *plugin, **plugins;
  int version=plugin_array_version;
1978 1979
  DBUG_ENTER("plugin_foreach_with_mask");

unknown's avatar
unknown committed
1980 1981 1982
  if (!initialized)
    DBUG_RETURN(FALSE);

1983
  state_mask= ~state_mask; // do it only once
1984

Marc Alff's avatar
Marc Alff committed
1985
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
1986
  total= type == MYSQL_ANY_PLUGIN ? plugin_array.elements
unknown's avatar
unknown committed
1987 1988 1989
                                  : plugin_hash[type].records;
  /*
    Do the alloca out here in case we do have a working alloca:
unknown's avatar
unknown committed
1990
        leaving the nested stack frame invalidates alloca allocation.
unknown's avatar
unknown committed
1991
  */
unknown's avatar
unknown committed
1992
  plugins=(struct st_plugin_int **)my_alloca(total*sizeof(plugin));
unknown's avatar
unknown committed
1993 1994
  if (type == MYSQL_ANY_PLUGIN)
  {
1995
    for (idx= 0; idx < total; idx++)
unknown's avatar
unknown committed
1996
    {
unknown's avatar
unknown committed
1997
      plugin= *dynamic_element(&plugin_array, idx, struct st_plugin_int **);
unknown's avatar
unknown committed
1998
      plugins[idx]= !(plugin->state & state_mask) ? plugin : NULL;
unknown's avatar
unknown committed
1999 2000 2001 2002
    }
  }
  else
  {
unknown's avatar
unknown committed
2003
    HASH *hash= plugin_hash + type;
2004
    for (idx= 0; idx < total; idx++)
unknown's avatar
unknown committed
2005
    {
Konstantin Osipov's avatar
Konstantin Osipov committed
2006
      plugin= (struct st_plugin_int *) my_hash_element(hash, idx);
unknown's avatar
unknown committed
2007
      plugins[idx]= !(plugin->state & state_mask) ? plugin : NULL;
unknown's avatar
unknown committed
2008 2009
    }
  }
Marc Alff's avatar
Marc Alff committed
2010
  mysql_mutex_unlock(&LOCK_plugin);
2011 2012 2013 2014 2015

  for (idx= 0; idx < total; idx++)
  {
    if (unlikely(version != plugin_array_version))
    {
Marc Alff's avatar
Marc Alff committed
2016
      mysql_mutex_lock(&LOCK_plugin);
2017
      for (uint i=idx; i < total; i++)
2018
        if (plugins[i] && plugins[i]->state & state_mask)
2019
          plugins[i]=0;
Marc Alff's avatar
Marc Alff committed
2020
      mysql_mutex_unlock(&LOCK_plugin);
2021
    }
unknown's avatar
unknown committed
2022
    plugin= plugins[idx];
2023
    /* It will stop iterating on first engine error when "func" returns TRUE */
unknown's avatar
unknown committed
2024
    if (plugin && func(thd, plugin_int_to_ref(plugin), arg))
2025 2026 2027 2028
        goto err;
  }

  my_afree(plugins);
unknown's avatar
unknown committed
2029 2030
  DBUG_RETURN(FALSE);
err:
2031
  my_afree(plugins);
unknown's avatar
unknown committed
2032 2033
  DBUG_RETURN(TRUE);
}
2034

unknown's avatar
unknown committed
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050

/****************************************************************************
  Internal type declarations for variables support
****************************************************************************/

#undef MYSQL_SYSVAR_NAME
#define MYSQL_SYSVAR_NAME(name) name
#define PLUGIN_VAR_TYPEMASK 0x007f

#define EXTRA_OPTIONS 3 /* options for: 'foo', 'plugin-foo' and NULL */

typedef DECLARE_MYSQL_SYSVAR_BASIC(sysvar_bool_t, my_bool);
typedef DECLARE_MYSQL_THDVAR_BASIC(thdvar_bool_t, my_bool);
typedef DECLARE_MYSQL_SYSVAR_BASIC(sysvar_str_t, char *);
typedef DECLARE_MYSQL_THDVAR_BASIC(thdvar_str_t, char *);

unknown's avatar
unknown committed
2051 2052 2053 2054
typedef DECLARE_MYSQL_SYSVAR_TYPELIB(sysvar_enum_t, unsigned long);
typedef DECLARE_MYSQL_THDVAR_TYPELIB(thdvar_enum_t, unsigned long);
typedef DECLARE_MYSQL_SYSVAR_TYPELIB(sysvar_set_t, ulonglong);
typedef DECLARE_MYSQL_THDVAR_TYPELIB(thdvar_set_t, ulonglong);
unknown's avatar
unknown committed
2055 2056 2057 2058 2059 2060 2061

typedef DECLARE_MYSQL_SYSVAR_SIMPLE(sysvar_int_t, int);
typedef DECLARE_MYSQL_SYSVAR_SIMPLE(sysvar_long_t, long);
typedef DECLARE_MYSQL_SYSVAR_SIMPLE(sysvar_longlong_t, longlong);
typedef DECLARE_MYSQL_SYSVAR_SIMPLE(sysvar_uint_t, uint);
typedef DECLARE_MYSQL_SYSVAR_SIMPLE(sysvar_ulong_t, ulong);
typedef DECLARE_MYSQL_SYSVAR_SIMPLE(sysvar_ulonglong_t, ulonglong);
2062
typedef DECLARE_MYSQL_SYSVAR_SIMPLE(sysvar_double_t, double);
unknown's avatar
unknown committed
2063 2064 2065 2066 2067 2068 2069

typedef DECLARE_MYSQL_THDVAR_SIMPLE(thdvar_int_t, int);
typedef DECLARE_MYSQL_THDVAR_SIMPLE(thdvar_long_t, long);
typedef DECLARE_MYSQL_THDVAR_SIMPLE(thdvar_longlong_t, longlong);
typedef DECLARE_MYSQL_THDVAR_SIMPLE(thdvar_uint_t, uint);
typedef DECLARE_MYSQL_THDVAR_SIMPLE(thdvar_ulong_t, ulong);
typedef DECLARE_MYSQL_THDVAR_SIMPLE(thdvar_ulonglong_t, ulonglong);
2070
typedef DECLARE_MYSQL_THDVAR_SIMPLE(thdvar_double_t, double);
unknown's avatar
unknown committed
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080


/****************************************************************************
  default variable data check and update functions
****************************************************************************/

static int check_func_bool(THD *thd, struct st_mysql_sys_var *var,
                           void *save, st_mysql_value *value)
{
  char buff[STRING_BUFFER_USUAL_SIZE];
2081
  const char *str;
unknown's avatar
unknown committed
2082
  int result, length;
unknown's avatar
unknown committed
2083
  long long tmp;
unknown's avatar
unknown committed
2084

unknown's avatar
unknown committed
2085 2086 2087 2088 2089 2090 2091 2092 2093
  if (value->value_type(value) == MYSQL_VALUE_TYPE_STRING)
  {
    length= sizeof(buff);
    if (!(str= value->val_str(value, buff, &length)) ||
        (result= find_type(&bool_typelib, str, length, 1)-1) < 0)
      goto err;
  }
  else
  {
unknown's avatar
unknown committed
2094
    if (value->val_int(value, &tmp) < 0)
unknown's avatar
unknown committed
2095 2096 2097 2098 2099
      goto err;
    if (tmp > 1)
      goto err;
    result= (int) tmp;
  }
2100
  *(my_bool *) save= -result;
unknown's avatar
unknown committed
2101 2102 2103 2104 2105 2106 2107 2108 2109
  return 0;
err:
  return 1;
}


static int check_func_int(THD *thd, struct st_mysql_sys_var *var,
                          void *save, st_mysql_value *value)
{
2110 2111
  my_bool fixed1, fixed2;
  long long orig, val;
unknown's avatar
unknown committed
2112
  struct my_option options;
2113 2114
  value->val_int(value, &orig);
  val= orig;
unknown's avatar
unknown committed
2115
  plugin_opt_set_limits(&options, var);
2116 2117

  if (var->flags & PLUGIN_VAR_UNSIGNED)
2118 2119 2120 2121 2122 2123
  {
    if ((fixed1= (!value->is_unsigned(value) && val < 0)))
      val=0;
    *(uint *)save= (uint) getopt_ull_limit_value((ulonglong) val, &options,
                                                   &fixed2);
  }
2124
  else
2125 2126 2127 2128 2129
  {
    if ((fixed1= (value->is_unsigned(value) && val < 0)))
      val=LONGLONG_MAX;
    *(int *)save= (int) getopt_ll_limit_value(val, &options, &fixed2);
  }
2130

2131 2132
  return throw_bounds_warning(thd, var->name, fixed1 || fixed2,
                              value->is_unsigned(value), (longlong) orig);
unknown's avatar
unknown committed
2133 2134 2135 2136 2137 2138
}


static int check_func_long(THD *thd, struct st_mysql_sys_var *var,
                          void *save, st_mysql_value *value)
{
2139 2140
  my_bool fixed1, fixed2;
  long long orig, val;
unknown's avatar
unknown committed
2141
  struct my_option options;
2142 2143
  value->val_int(value, &orig);
  val= orig;
unknown's avatar
unknown committed
2144
  plugin_opt_set_limits(&options, var);
2145 2146

  if (var->flags & PLUGIN_VAR_UNSIGNED)
2147 2148 2149 2150 2151 2152
  {
    if ((fixed1= (!value->is_unsigned(value) && val < 0)))
      val=0;
    *(ulong *)save= (ulong) getopt_ull_limit_value((ulonglong) val, &options,
                                                   &fixed2);
  }
2153
  else
2154 2155 2156 2157 2158
  {
    if ((fixed1= (value->is_unsigned(value) && val < 0)))
      val=LONGLONG_MAX;
    *(long *)save= (long) getopt_ll_limit_value(val, &options, &fixed2);
  }
2159

2160 2161
  return throw_bounds_warning(thd, var->name, fixed1 || fixed2,
                              value->is_unsigned(value), (longlong) orig);
unknown's avatar
unknown committed
2162 2163 2164 2165
}


static int check_func_longlong(THD *thd, struct st_mysql_sys_var *var,
2166
                               void *save, st_mysql_value *value)
unknown's avatar
unknown committed
2167
{
2168 2169
  my_bool fixed1, fixed2;
  long long orig, val;
unknown's avatar
unknown committed
2170
  struct my_option options;
2171 2172
  value->val_int(value, &orig);
  val= orig;
unknown's avatar
unknown committed
2173
  plugin_opt_set_limits(&options, var);
2174 2175

  if (var->flags & PLUGIN_VAR_UNSIGNED)
2176 2177 2178 2179 2180 2181
  {
    if ((fixed1= (!value->is_unsigned(value) && val < 0)))
      val=0;
    *(ulonglong *)save= getopt_ull_limit_value((ulonglong) val, &options,
                                               &fixed2);
  }
2182
  else
2183 2184 2185 2186 2187
  {
    if ((fixed1= (value->is_unsigned(value) && val < 0)))
      val=LONGLONG_MAX;
    *(longlong *)save= getopt_ll_limit_value(val, &options, &fixed2);
  }
2188

2189 2190
  return throw_bounds_warning(thd, var->name, fixed1 || fixed2,
                              value->is_unsigned(value), (longlong) orig);
unknown's avatar
unknown committed
2191 2192 2193 2194 2195 2196 2197 2198
}

static int check_func_str(THD *thd, struct st_mysql_sys_var *var,
                          void *save, st_mysql_value *value)
{
  char buff[STRING_BUFFER_USUAL_SIZE];
  const char *str;
  int length;
unknown's avatar
unknown committed
2199

unknown's avatar
unknown committed
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
  length= sizeof(buff);
  if ((str= value->val_str(value, buff, &length)))
    str= thd->strmake(str, length);
  *(const char**)save= str;
  return 0;
}


static int check_func_enum(THD *thd, struct st_mysql_sys_var *var,
                           void *save, st_mysql_value *value)
{
  char buff[STRING_BUFFER_USUAL_SIZE];
2212
  const char *str;
unknown's avatar
unknown committed
2213
  TYPELIB *typelib;
unknown's avatar
unknown committed
2214
  long long tmp;
unknown's avatar
unknown committed
2215 2216
  long result;
  int length;
unknown's avatar
unknown committed
2217

unknown's avatar
unknown committed
2218
  if (var->flags & PLUGIN_VAR_THDLOCAL)
unknown's avatar
unknown committed
2219
    typelib= ((thdvar_enum_t*) var)->typelib;
unknown's avatar
unknown committed
2220
  else
unknown's avatar
unknown committed
2221
    typelib= ((sysvar_enum_t*) var)->typelib;
unknown's avatar
unknown committed
2222

unknown's avatar
unknown committed
2223 2224 2225 2226 2227
  if (value->value_type(value) == MYSQL_VALUE_TYPE_STRING)
  {
    length= sizeof(buff);
    if (!(str= value->val_str(value, buff, &length)))
      goto err;
2228
    if ((result= (long)find_type(typelib, str, length, 0) - 1) < 0)
unknown's avatar
unknown committed
2229 2230 2231 2232
      goto err;
  }
  else
  {
unknown's avatar
unknown committed
2233
    if (value->val_int(value, &tmp))
unknown's avatar
unknown committed
2234
      goto err;
2235
    if (tmp < 0 || tmp >= typelib->count)
unknown's avatar
unknown committed
2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
      goto err;
    result= (long) tmp;
  }
  *(long*)save= result;
  return 0;
err:
  return 1;
}


static int check_func_set(THD *thd, struct st_mysql_sys_var *var,
                          void *save, st_mysql_value *value)
{
  char buff[STRING_BUFFER_USUAL_SIZE], *error= 0;
2250
  const char *str;
unknown's avatar
unknown committed
2251
  TYPELIB *typelib;
unknown's avatar
unknown committed
2252
  ulonglong result;
2253
  uint error_len= 0;                            // init as only set on error
unknown's avatar
unknown committed
2254 2255
  bool not_used;
  int length;
unknown's avatar
unknown committed
2256

unknown's avatar
unknown committed
2257
  if (var->flags & PLUGIN_VAR_THDLOCAL)
unknown's avatar
unknown committed
2258
    typelib= ((thdvar_set_t*) var)->typelib;
unknown's avatar
unknown committed
2259
  else
unknown's avatar
unknown committed
2260
    typelib= ((sysvar_set_t*)var)->typelib;
unknown's avatar
unknown committed
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273

  if (value->value_type(value) == MYSQL_VALUE_TYPE_STRING)
  {
    length= sizeof(buff);
    if (!(str= value->val_str(value, buff, &length)))
      goto err;
    result= find_set(typelib, str, length, NULL,
                     &error, &error_len, &not_used);
    if (error_len)
      goto err;
  }
  else
  {
unknown's avatar
unknown committed
2274
    if (value->val_int(value, (long long *)&result))
unknown's avatar
unknown committed
2275
      goto err;
2276
    if (unlikely((result >= (1ULL << typelib->count)) &&
unknown's avatar
unknown committed
2277 2278 2279
                 (typelib->count < sizeof(long)*8)))
      goto err;
  }
unknown's avatar
unknown committed
2280
  *(ulonglong*)save= result;
unknown's avatar
unknown committed
2281 2282 2283 2284 2285
  return 0;
err:
  return 1;
}

2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299
static int check_func_double(THD *thd, struct st_mysql_sys_var *var,
                             void *save, st_mysql_value *value)
{
  double v;
  my_bool fixed;
  struct my_option option;

  value->val_real(value, &v);
  plugin_opt_set_limits(&option, var);
  *(double *) save= getopt_double_limit_value(v, &option, &fixed);

  return throw_bounds_warning(thd, var->name, fixed, v);
}

unknown's avatar
unknown committed
2300 2301

static void update_func_bool(THD *thd, struct st_mysql_sys_var *var,
unknown's avatar
unknown committed
2302
                             void *tgt, const void *save)
unknown's avatar
unknown committed
2303
{
2304
  *(my_bool *) tgt= *(my_bool *) save ? TRUE : FALSE;
unknown's avatar
unknown committed
2305 2306 2307 2308
}


static void update_func_int(THD *thd, struct st_mysql_sys_var *var,
unknown's avatar
unknown committed
2309
                             void *tgt, const void *save)
unknown's avatar
unknown committed
2310 2311 2312 2313 2314 2315
{
  *(int *)tgt= *(int *) save;
}


static void update_func_long(THD *thd, struct st_mysql_sys_var *var,
unknown's avatar
unknown committed
2316
                             void *tgt, const void *save)
unknown's avatar
unknown committed
2317 2318 2319 2320 2321 2322
{
  *(long *)tgt= *(long *) save;
}


static void update_func_longlong(THD *thd, struct st_mysql_sys_var *var,
unknown's avatar
unknown committed
2323
                             void *tgt, const void *save)
unknown's avatar
unknown committed
2324 2325 2326 2327 2328 2329
{
  *(longlong *)tgt= *(ulonglong *) save;
}


static void update_func_str(THD *thd, struct st_mysql_sys_var *var,
unknown's avatar
unknown committed
2330
                             void *tgt, const void *save)
unknown's avatar
unknown committed
2331
{
2332
  *(char **) tgt= *(char **) save;
unknown's avatar
unknown committed
2333 2334
}

2335 2336 2337 2338 2339
static void update_func_double(THD *thd, struct st_mysql_sys_var *var,
                               void *tgt, const void *save)
{
  *(double *) tgt= *(double *) save;
}
unknown's avatar
unknown committed
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351

/****************************************************************************
  System Variables support
****************************************************************************/


sys_var *find_sys_var(THD *thd, const char *str, uint length)
{
  sys_var *var;
  sys_var_pluginvar *pi= NULL;
  plugin_ref plugin;
  DBUG_ENTER("find_sys_var");
unknown's avatar
unknown committed
2352

Marc Alff's avatar
Marc Alff committed
2353 2354
  mysql_mutex_lock(&LOCK_plugin);
  mysql_rwlock_rdlock(&LOCK_system_variables_hash);
2355
  if ((var= intern_find_sys_var(str, length)) &&
unknown's avatar
unknown committed
2356 2357
      (pi= var->cast_pluginvar()))
  {
Marc Alff's avatar
Marc Alff committed
2358
    mysql_rwlock_unlock(&LOCK_system_variables_hash);
unknown's avatar
unknown committed
2359
    LEX *lex= thd ? thd->lex : 0;
unknown's avatar
unknown committed
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
    if (!(plugin= my_intern_plugin_lock(lex, plugin_int_to_ref(pi->plugin))))
      var= NULL; /* failed to lock it, it must be uninstalling */
    else
    if (!(plugin_state(plugin) & PLUGIN_IS_READY))
    {
      /* initialization not completed */
      var= NULL;
      intern_plugin_unlock(lex, plugin);
    }
  }
unknown's avatar
unknown committed
2370
  else
Marc Alff's avatar
Marc Alff committed
2371 2372
    mysql_rwlock_unlock(&LOCK_system_variables_hash);
  mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
2373

2374
  if (!var)
unknown's avatar
unknown committed
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390
    my_error(ER_UNKNOWN_SYSTEM_VARIABLE, MYF(0), (char*) str);
  DBUG_RETURN(var);
}


/*
  called by register_var, construct_options and test_plugin_options.
  Returns the 'bookmark' for the named variable.
  LOCK_system_variables_hash should be at least read locked
*/
static st_bookmark *find_bookmark(const char *plugin, const char *name,
                                  int flags)
{
  st_bookmark *result= NULL;
  uint namelen, length, pluginlen= 0;
  char *varname, *p;
unknown's avatar
unknown committed
2391

unknown's avatar
unknown committed
2392 2393
  if (!(flags & PLUGIN_VAR_THDLOCAL))
    return NULL;
unknown's avatar
unknown committed
2394

unknown's avatar
unknown committed
2395 2396 2397 2398 2399
  namelen= strlen(name);
  if (plugin)
    pluginlen= strlen(plugin) + 1;
  length= namelen + pluginlen + 2;
  varname= (char*) my_alloca(length);
unknown's avatar
unknown committed
2400

unknown's avatar
unknown committed
2401 2402 2403 2404 2405
  if (plugin)
  {
    strxmov(varname + 1, plugin, "_", name, NullS);
    for (p= varname + 1; *p; p++)
      if (*p == '-')
unknown's avatar
unknown committed
2406
        *p= '_';
unknown's avatar
unknown committed
2407 2408 2409 2410 2411
  }
  else
    memcpy(varname + 1, name, namelen + 1);

  varname[0]= flags & PLUGIN_VAR_TYPEMASK;
unknown's avatar
unknown committed
2412

Konstantin Osipov's avatar
Konstantin Osipov committed
2413 2414
  result= (st_bookmark*) my_hash_search(&bookmark_hash,
                                        (const uchar*) varname, length - 1);
unknown's avatar
unknown committed
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434

  my_afree(varname);
  return result;
}


/*
  returns a bookmark for thd-local variables, creating if neccessary.
  returns null for non thd-local variables.
  Requires that a write lock is obtained on LOCK_system_variables_hash
*/
static st_bookmark *register_var(const char *plugin, const char *name,
                                 int flags)
{
  uint length= strlen(plugin) + strlen(name) + 3, size= 0, offset, new_size;
  st_bookmark *result;
  char *varname, *p;

  if (!(flags & PLUGIN_VAR_THDLOCAL))
    return NULL;
unknown's avatar
unknown committed
2435

unknown's avatar
unknown committed
2436 2437 2438 2439 2440 2441 2442 2443
  switch (flags & PLUGIN_VAR_TYPEMASK) {
  case PLUGIN_VAR_BOOL:
    size= sizeof(my_bool);
    break;
  case PLUGIN_VAR_INT:
    size= sizeof(int);
    break;
  case PLUGIN_VAR_LONG:
unknown's avatar
unknown committed
2444
  case PLUGIN_VAR_ENUM:
unknown's avatar
unknown committed
2445 2446 2447
    size= sizeof(long);
    break;
  case PLUGIN_VAR_LONGLONG:
unknown's avatar
unknown committed
2448
  case PLUGIN_VAR_SET:
unknown's avatar
unknown committed
2449 2450 2451 2452 2453
    size= sizeof(ulonglong);
    break;
  case PLUGIN_VAR_STR:
    size= sizeof(char*);
    break;
2454 2455 2456
  case PLUGIN_VAR_DOUBLE:
    size= sizeof(double);
    break;
unknown's avatar
unknown committed
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
  default:
    DBUG_ASSERT(0);
    return NULL;
  };

  varname= ((char*) my_alloca(length));
  strxmov(varname + 1, plugin, "_", name, NullS);
  for (p= varname + 1; *p; p++)
    if (*p == '-')
      *p= '_';

  if (!(result= find_bookmark(NULL, varname + 1, flags)))
  {
unknown's avatar
unknown committed
2470
    result= (st_bookmark*) alloc_root(&plugin_mem_root,
unknown's avatar
unknown committed
2471
                                      sizeof(struct st_bookmark) + length-1);
unknown's avatar
unknown committed
2472
    varname[0]= flags & PLUGIN_VAR_TYPEMASK;
unknown's avatar
unknown committed
2473
    memcpy(result->key, varname, length);
unknown's avatar
unknown committed
2474 2475
    result->name_len= length - 2;
    result->offset= -1;
unknown's avatar
unknown committed
2476

unknown's avatar
unknown committed
2477 2478 2479 2480 2481
    DBUG_ASSERT(size && !(size & (size-1))); /* must be power of 2 */

    offset= global_system_variables.dynamic_variables_size;
    offset= (offset + size - 1) & ~(size - 1);
    result->offset= (int) offset;
unknown's avatar
unknown committed
2482

unknown's avatar
unknown committed
2483 2484 2485 2486
    new_size= (offset + size + 63) & ~63;

    if (new_size > global_variables_dynamic_size)
    {
unknown's avatar
unknown committed
2487
      global_system_variables.dynamic_variables_ptr= (char*)
unknown's avatar
unknown committed
2488 2489
        my_realloc(global_system_variables.dynamic_variables_ptr, new_size,
                   MYF(MY_WME | MY_FAE | MY_ALLOW_ZERO_PTR));
unknown's avatar
unknown committed
2490
      max_system_variables.dynamic_variables_ptr= (char*)
unknown's avatar
unknown committed
2491 2492
        my_realloc(max_system_variables.dynamic_variables_ptr, new_size,
                   MYF(MY_WME | MY_FAE | MY_ALLOW_ZERO_PTR));
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
      /*
        Clear the new variable value space. This is required for string
        variables. If their value is non-NULL, it must point to a valid
        string.
      */
      bzero(global_system_variables.dynamic_variables_ptr +
            global_variables_dynamic_size,
            new_size - global_variables_dynamic_size);
      bzero(max_system_variables.dynamic_variables_ptr +
            global_variables_dynamic_size,
            new_size - global_variables_dynamic_size);
unknown's avatar
unknown committed
2504 2505
      global_variables_dynamic_size= new_size;
    }
unknown's avatar
unknown committed
2506

unknown's avatar
unknown committed
2507 2508 2509 2510 2511 2512
    global_system_variables.dynamic_variables_head= offset;
    max_system_variables.dynamic_variables_head= offset;
    global_system_variables.dynamic_variables_size= offset + size;
    max_system_variables.dynamic_variables_size= offset + size;
    global_system_variables.dynamic_variables_version++;
    max_system_variables.dynamic_variables_version++;
unknown's avatar
unknown committed
2513

unknown's avatar
unknown committed
2514 2515 2516
    result->version= global_system_variables.dynamic_variables_version;

    /* this should succeed because we have already checked if a dup exists */
unknown's avatar
unknown committed
2517
    if (my_hash_insert(&bookmark_hash, (uchar*) result))
unknown's avatar
unknown committed
2518 2519 2520 2521 2522 2523 2524 2525 2526
    {
      fprintf(stderr, "failed to add placeholder to hash");
      DBUG_ASSERT(0);
    }
  }
  my_afree(varname);
  return result;
}

2527 2528 2529 2530 2531 2532 2533 2534 2535
static void restore_pluginvar_names(sys_var *first)
{
  for (sys_var *var= first; var; var= var->next)
  {
    sys_var_pluginvar *pv= var->cast_pluginvar();
    pv->plugin_var->name= pv->orig_pluginvar_name;
  }
}

unknown's avatar
unknown committed
2536 2537 2538 2539 2540 2541 2542

/*
  returns a pointer to the memory which holds the thd-local variable or
  a pointer to the global variable if thd==null.
  If required, will sync with global variables if the requested variable
  has not yet been allocated in the current thread.
*/
unknown's avatar
unknown committed
2543
static uchar *intern_sys_var_ptr(THD* thd, int offset, bool global_lock)
unknown's avatar
unknown committed
2544 2545 2546
{
  DBUG_ASSERT(offset >= 0);
  DBUG_ASSERT((uint)offset <= global_system_variables.dynamic_variables_head);
unknown's avatar
unknown committed
2547

unknown's avatar
unknown committed
2548
  if (!thd)
unknown's avatar
unknown committed
2549
    return (uchar*) global_system_variables.dynamic_variables_ptr + offset;
unknown's avatar
unknown committed
2550

unknown's avatar
unknown committed
2551
  /*
unknown's avatar
unknown committed
2552
    dynamic_variables_head points to the largest valid offset
unknown's avatar
unknown committed
2553 2554 2555 2556 2557
  */
  if (!thd->variables.dynamic_variables_ptr ||
      (uint)offset > thd->variables.dynamic_variables_head)
  {
    uint idx;
unknown's avatar
unknown committed
2558

Marc Alff's avatar
Marc Alff committed
2559
    mysql_rwlock_rdlock(&LOCK_system_variables_hash);
unknown's avatar
unknown committed
2560

unknown's avatar
unknown committed
2561
    thd->variables.dynamic_variables_ptr= (char*)
unknown's avatar
unknown committed
2562 2563 2564 2565 2566
      my_realloc(thd->variables.dynamic_variables_ptr,
                 global_variables_dynamic_size,
                 MYF(MY_WME | MY_FAE | MY_ALLOW_ZERO_PTR));

    if (global_lock)
Marc Alff's avatar
Marc Alff committed
2567
      mysql_mutex_lock(&LOCK_global_system_variables);
unknown's avatar
unknown committed
2568

Marc Alff's avatar
Marc Alff committed
2569
    mysql_mutex_assert_owner(&LOCK_global_system_variables);
unknown's avatar
unknown committed
2570

unknown's avatar
unknown committed
2571
    memcpy(thd->variables.dynamic_variables_ptr +
unknown's avatar
unknown committed
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585
             thd->variables.dynamic_variables_size,
           global_system_variables.dynamic_variables_ptr +
             thd->variables.dynamic_variables_size,
           global_system_variables.dynamic_variables_size -
             thd->variables.dynamic_variables_size);

    /*
      now we need to iterate through any newly copied 'defaults'
      and if it is a string type with MEMALLOC flag, we need to strdup
    */
    for (idx= 0; idx < bookmark_hash.records; idx++)
    {
      sys_var_pluginvar *pi;
      sys_var *var;
Konstantin Osipov's avatar
Konstantin Osipov committed
2586
      st_bookmark *v= (st_bookmark*) my_hash_element(&bookmark_hash,idx);
unknown's avatar
unknown committed
2587

unknown's avatar
unknown committed
2588
      if (v->version <= thd->variables.dynamic_variables_version ||
2589
          !(var= intern_find_sys_var(v->key + 1, v->name_len)) ||
unknown's avatar
unknown committed
2590
          !(pi= var->cast_pluginvar()) ||
unknown's avatar
unknown committed
2591
          v->key[0] != (pi->plugin_var->flags & PLUGIN_VAR_TYPEMASK))
unknown's avatar
unknown committed
2592 2593 2594
        continue;

      /* Here we do anything special that may be required of the data types */
unknown's avatar
unknown committed
2595

unknown's avatar
unknown committed
2596 2597 2598
      if ((pi->plugin_var->flags & PLUGIN_VAR_TYPEMASK) == PLUGIN_VAR_STR &&
          pi->plugin_var->flags & PLUGIN_VAR_MEMALLOC)
      {
2599 2600 2601 2602 2603 2604 2605
         int varoff= *(int *) (pi->plugin_var + 1);
         char **thdvar= (char **) (thd->variables.
                                   dynamic_variables_ptr + varoff);
         char **sysvar= (char **) (global_system_variables.
                                   dynamic_variables_ptr + varoff);
         *thdvar= NULL;
         plugin_var_memalloc_session_update(thd, NULL, thdvar, *sysvar);
unknown's avatar
unknown committed
2606
      }
unknown's avatar
unknown committed
2607
    }
unknown's avatar
unknown committed
2608

unknown's avatar
unknown committed
2609
    if (global_lock)
Marc Alff's avatar
Marc Alff committed
2610
      mysql_mutex_unlock(&LOCK_global_system_variables);
unknown's avatar
unknown committed
2611

unknown's avatar
unknown committed
2612
    thd->variables.dynamic_variables_version=
unknown's avatar
unknown committed
2613
           global_system_variables.dynamic_variables_version;
unknown's avatar
unknown committed
2614
    thd->variables.dynamic_variables_head=
unknown's avatar
unknown committed
2615
           global_system_variables.dynamic_variables_head;
unknown's avatar
unknown committed
2616
    thd->variables.dynamic_variables_size=
unknown's avatar
unknown committed
2617 2618
           global_system_variables.dynamic_variables_size;

Marc Alff's avatar
Marc Alff committed
2619
    mysql_rwlock_unlock(&LOCK_system_variables_hash);
unknown's avatar
unknown committed
2620
  }
unknown's avatar
unknown committed
2621
  return (uchar*)thd->variables.dynamic_variables_ptr + offset;
unknown's avatar
unknown committed
2622 2623
}

2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643

/**
  For correctness and simplicity's sake, a pointer to a function
  must be compatible with pointed-to type, that is, the return and
  parameters types must be the same. Thus, a callback function is
  defined for each scalar type. The functions are assigned in
  construct_options to their respective types.
*/

static char *mysql_sys_var_char(THD* thd, int offset)
{
  return (char *) intern_sys_var_ptr(thd, offset, true);
}

static int *mysql_sys_var_int(THD* thd, int offset)
{
  return (int *) intern_sys_var_ptr(thd, offset, true);
}

static long *mysql_sys_var_long(THD* thd, int offset)
unknown's avatar
unknown committed
2644
{
2645
  return (long *) intern_sys_var_ptr(thd, offset, true);
unknown's avatar
unknown committed
2646 2647
}

2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
static unsigned long *mysql_sys_var_ulong(THD* thd, int offset)
{
  return (unsigned long *) intern_sys_var_ptr(thd, offset, true);
}

static long long *mysql_sys_var_longlong(THD* thd, int offset)
{
  return (long long *) intern_sys_var_ptr(thd, offset, true);
}

static unsigned long long *mysql_sys_var_ulonglong(THD* thd, int offset)
{
  return (unsigned long long *) intern_sys_var_ptr(thd, offset, true);
}

static char **mysql_sys_var_str(THD* thd, int offset)
{
  return (char **) intern_sys_var_ptr(thd, offset, true);
}
unknown's avatar
unknown committed
2667

2668 2669 2670 2671 2672
static double *mysql_sys_var_double(THD* thd, int offset)
{
  return (double *) intern_sys_var_ptr(thd, offset, true);
}

unknown's avatar
unknown committed
2673
void plugin_thdvar_init(THD *thd)
unknown's avatar
unknown committed
2674
{
unknown's avatar
unknown committed
2675 2676 2677 2678 2679 2680 2681 2682 2683
  plugin_ref old_table_plugin= thd->variables.table_plugin;
  DBUG_ENTER("plugin_thdvar_init");
  
  thd->variables.table_plugin= NULL;
  cleanup_variables(thd, &thd->variables);
  
  thd->variables= global_system_variables;
  thd->variables.table_plugin= NULL;

unknown's avatar
unknown committed
2684 2685 2686 2687 2688
  /* we are going to allocate these lazily */
  thd->variables.dynamic_variables_version= 0;
  thd->variables.dynamic_variables_size= 0;
  thd->variables.dynamic_variables_ptr= 0;

Marc Alff's avatar
Marc Alff committed
2689
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
2690
  thd->variables.table_plugin=
unknown's avatar
unknown committed
2691 2692
        my_intern_plugin_lock(NULL, global_system_variables.table_plugin);
  intern_plugin_unlock(NULL, old_table_plugin);
Marc Alff's avatar
Marc Alff committed
2693
  mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
2694
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
2695 2696
}

unknown's avatar
unknown committed
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709

/*
  Unlocks all system variables which hold a reference
*/
static void unlock_variables(THD *thd, struct system_variables *vars)
{
  intern_plugin_unlock(NULL, vars->table_plugin);
  vars->table_plugin= NULL;
}


/*
  Frees memory used by system variables
2710 2711 2712

  Unlike plugin_vars_free_values() it frees all variables of all plugins,
  it's used on shutdown.
unknown's avatar
unknown committed
2713 2714
*/
static void cleanup_variables(THD *thd, struct system_variables *vars)
unknown's avatar
unknown committed
2715
{
2716 2717
  if (thd)
    plugin_var_memalloc_free(&thd->variables);
unknown's avatar
unknown committed
2718

unknown's avatar
unknown committed
2719 2720
  DBUG_ASSERT(vars->table_plugin == NULL);

2721
  my_free(vars->dynamic_variables_ptr);
unknown's avatar
unknown committed
2722 2723 2724
  vars->dynamic_variables_ptr= NULL;
  vars->dynamic_variables_size= 0;
  vars->dynamic_variables_version= 0;
unknown's avatar
unknown committed
2725 2726 2727 2728 2729 2730 2731 2732 2733
}


void plugin_thdvar_cleanup(THD *thd)
{
  uint idx;
  plugin_ref *list;
  DBUG_ENTER("plugin_thdvar_cleanup");

Marc Alff's avatar
Marc Alff committed
2734
  mysql_mutex_lock(&LOCK_plugin);
unknown's avatar
unknown committed
2735

unknown's avatar
unknown committed
2736 2737
  unlock_variables(thd, &thd->variables);
  cleanup_variables(thd, &thd->variables);
unknown's avatar
unknown committed
2738

unknown's avatar
unknown committed
2739
  if ((idx= thd->lex->plugins.elements))
unknown's avatar
unknown committed
2740
  {
unknown's avatar
unknown committed
2741
    list= ((plugin_ref*) thd->lex->plugins.buffer) + idx - 1;
unknown's avatar
unknown committed
2742
    DBUG_PRINT("info",("unlocking %d plugins", idx));
unknown's avatar
unknown committed
2743
    while ((uchar*) list >= thd->lex->plugins.buffer)
unknown's avatar
unknown committed
2744 2745 2746 2747
      intern_plugin_unlock(NULL, *list--);
  }

  reap_plugins();
Marc Alff's avatar
Marc Alff committed
2748
  mysql_mutex_unlock(&LOCK_plugin);
unknown's avatar
unknown committed
2749

unknown's avatar
unknown committed
2750
  reset_dynamic(&thd->lex->plugins);
unknown's avatar
unknown committed
2751 2752 2753 2754 2755

  DBUG_VOID_RETURN;
}


2756 2757 2758
/**
  @brief Free values of thread variables of a plugin.

unknown's avatar
unknown committed
2759
  This must be called before a plugin is deleted. Otherwise its
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
  variables are no longer accessible and the value space is lost. Note
  that only string values with PLUGIN_VAR_MEMALLOC are allocated and
  must be freed.

  @param[in]        vars        Chain of system variables of a plugin
*/

static void plugin_vars_free_values(sys_var *vars)
{
  DBUG_ENTER("plugin_vars_free_values");

  for (sys_var *var= vars; var; var= var->next)
  {
    sys_var_pluginvar *piv= var->cast_pluginvar();
    if (piv &&
        ((piv->plugin_var->flags & PLUGIN_VAR_TYPEMASK) == PLUGIN_VAR_STR) &&
        (piv->plugin_var->flags & PLUGIN_VAR_MEMALLOC))
    {
      /* Free the string from global_system_variables. */
      char **valptr= (char**) piv->real_value_ptr(NULL, OPT_GLOBAL);
      DBUG_PRINT("plugin", ("freeing value for: '%s'  addr: 0x%lx",
2781
                            var->name.str, (long) valptr));
2782
      my_free(*valptr);
2783 2784 2785 2786 2787 2788
      *valptr= NULL;
    }
  }
  DBUG_VOID_RETURN;
}

2789
static SHOW_TYPE pluginvar_show_type(st_mysql_sys_var *plugin_var)
unknown's avatar
unknown committed
2790 2791
{
  switch (plugin_var->flags & PLUGIN_VAR_TYPEMASK) {
2792 2793
  case PLUGIN_VAR_BOOL:
    return SHOW_MY_BOOL;
unknown's avatar
unknown committed
2794
  case PLUGIN_VAR_INT:
2795
    return SHOW_INT;
unknown's avatar
unknown committed
2796
  case PLUGIN_VAR_LONG:
2797
    return SHOW_LONG;
unknown's avatar
unknown committed
2798
  case PLUGIN_VAR_LONGLONG:
2799
    return SHOW_LONGLONG;
unknown's avatar
unknown committed
2800
  case PLUGIN_VAR_STR:
2801 2802 2803 2804
    return SHOW_CHAR_PTR;
  case PLUGIN_VAR_ENUM:
  case PLUGIN_VAR_SET:
    return SHOW_CHAR;
2805 2806
  case PLUGIN_VAR_DOUBLE:
    return SHOW_DOUBLE;
unknown's avatar
unknown committed
2807
  default:
2808 2809
    DBUG_ASSERT(0);
    return SHOW_UNDEF;
unknown's avatar
unknown committed
2810 2811
  }
}
unknown's avatar
unknown committed
2812

unknown's avatar
unknown committed
2813

2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943
/**
  Set value for thread local variable with PLUGIN_VAR_MEMALLOC flag.

  @param[in]     thd   Thread context.
  @param[in]     var   Plugin variable.
  @param[in,out] dest  Destination memory pointer.
  @param[in]     value '\0'-terminated new value.

  Most plugin variable values are stored on dynamic_variables_ptr.
  Releasing memory occupied by these values is as simple as freeing
  dynamic_variables_ptr.

  An exception to the rule are PLUGIN_VAR_MEMALLOC variables, which
  are stored on individual memory hunks. All of these hunks has to
  be freed when it comes to cleanup.

  It may happen that a plugin was uninstalled and descriptors of
  it's variables are lost. In this case it is impossible to locate
  corresponding values.

  In addition to allocating and setting variable value, new element
  is added to dynamic_variables_allocs list. When thread is done, it
  has to call plugin_var_memalloc_free() to release memory used by
  PLUGIN_VAR_MEMALLOC variables.

  If var is NULL, variable update function is not called. This is
  needed when we take snapshot of system variables during thread
  initialization.

  @note List element and variable value are stored on the same memory
  hunk. List element is followed by variable value.

  @return Completion status
  @retval false Success
  @retval true  Failure
*/

static bool plugin_var_memalloc_session_update(THD *thd,
                                               struct st_mysql_sys_var *var,
                                               char **dest, const char *value)

{
  LIST *old_element= NULL;
  struct system_variables *vars= &thd->variables;
  DBUG_ENTER("plugin_var_memalloc_session_update");

  if (value)
  {
    size_t length= strlen(value) + 1;
    LIST *element;
    if (!(element= (LIST *) my_malloc(sizeof(LIST) + length, MYF(MY_WME))))
      DBUG_RETURN(true);
    memcpy(element + 1, value, length);
    value= (const char *) (element + 1);
    vars->dynamic_variables_allocs= list_add(vars->dynamic_variables_allocs,
                                             element);
  }

  if (*dest)
    old_element= (LIST *) (*dest - sizeof(LIST));

  if (var)
    var->update(thd, var, (void **) dest, (const void *) &value);
  else
    *dest= (char *) value;

  if (old_element)
  {
    vars->dynamic_variables_allocs= list_delete(vars->dynamic_variables_allocs,
                                                old_element);
    my_free(old_element);
  }
  DBUG_RETURN(false);
}


/**
  Free all elements allocated by plugin_var_memalloc_session_update().

  @param[in]     vars  system variables structure

  @see plugin_var_memalloc_session_update
*/

static void plugin_var_memalloc_free(struct system_variables *vars)
{
  LIST *next, *root;
  DBUG_ENTER("plugin_var_memalloc_free");
  for (root= vars->dynamic_variables_allocs; root; root= next)
  {
    next= root->next;
    my_free(root);
  }
  vars->dynamic_variables_allocs= NULL;
  DBUG_VOID_RETURN;
}


/**
  Set value for global variable with PLUGIN_VAR_MEMALLOC flag.

  @param[in]     thd   Thread context.
  @param[in]     var   Plugin variable.
  @param[in,out] dest  Destination memory pointer.
  @param[in]     value '\0'-terminated new value.

  @return Completion status
  @retval false Success
  @retval true  Failure
*/

static bool plugin_var_memalloc_global_update(THD *thd,
                                              struct st_mysql_sys_var *var,
                                              char **dest, const char *value)
{
  char *old_value= *dest;
  DBUG_ENTER("plugin_var_memalloc_global_update");

  if (value && !(value= my_strdup(value, MYF(MY_WME))))
    DBUG_RETURN(true);

  var->update(thd, var, (void **) dest, (const void *) &value);

  if (old_value)
    my_free(old_value);

  DBUG_RETURN(false);
}


2944
bool sys_var_pluginvar::check_update_type(Item_result type)
unknown's avatar
unknown committed
2945 2946 2947 2948 2949
{
  switch (plugin_var->flags & PLUGIN_VAR_TYPEMASK) {
  case PLUGIN_VAR_INT:
  case PLUGIN_VAR_LONG:
  case PLUGIN_VAR_LONGLONG:
2950
    return type != INT_RESULT;
unknown's avatar
unknown committed
2951
  case PLUGIN_VAR_STR:
2952
    return type != STRING_RESULT;
unknown's avatar
unknown committed
2953
  case PLUGIN_VAR_ENUM:
2954
  case PLUGIN_VAR_BOOL:
unknown's avatar
unknown committed
2955
  case PLUGIN_VAR_SET:
2956
    return type != STRING_RESULT && type != INT_RESULT;
2957 2958
  case PLUGIN_VAR_DOUBLE:
    return type != INT_RESULT && type != REAL_RESULT && type != DECIMAL_RESULT;
unknown's avatar
unknown committed
2959
  default:
2960
    return true;
unknown's avatar
unknown committed
2961 2962
  }
}
unknown's avatar
unknown committed
2963

unknown's avatar
unknown committed
2964

unknown's avatar
unknown committed
2965
uchar* sys_var_pluginvar::real_value_ptr(THD *thd, enum_var_type type)
unknown's avatar
unknown committed
2966
{
2967
  DBUG_ASSERT(thd || (type == OPT_GLOBAL));
unknown's avatar
unknown committed
2968 2969
  if (plugin_var->flags & PLUGIN_VAR_THDLOCAL)
  {
2970
    if (type == OPT_GLOBAL)
unknown's avatar
unknown committed
2971
      thd= NULL;
unknown's avatar
unknown committed
2972

unknown's avatar
unknown committed
2973 2974
    return intern_sys_var_ptr(thd, *(int*) (plugin_var+1), false);
  }
unknown's avatar
unknown committed
2975
  return *(uchar**) (plugin_var+1);
unknown's avatar
unknown committed
2976
}
unknown's avatar
unknown committed
2977

unknown's avatar
unknown committed
2978 2979 2980

TYPELIB* sys_var_pluginvar::plugin_var_typelib(void)
{
unknown's avatar
unknown committed
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
  switch (plugin_var->flags & (PLUGIN_VAR_TYPEMASK | PLUGIN_VAR_THDLOCAL)) {
  case PLUGIN_VAR_ENUM:
    return ((sysvar_enum_t *)plugin_var)->typelib;
  case PLUGIN_VAR_SET:
    return ((sysvar_set_t *)plugin_var)->typelib;
  case PLUGIN_VAR_ENUM | PLUGIN_VAR_THDLOCAL:
    return ((thdvar_enum_t *)plugin_var)->typelib;
  case PLUGIN_VAR_SET | PLUGIN_VAR_THDLOCAL:
    return ((thdvar_set_t *)plugin_var)->typelib;
  default:
    return NULL;
unknown's avatar
unknown committed
2992
  }
2993
  return NULL;	/* Keep compiler happy */
unknown's avatar
unknown committed
2994
}
unknown's avatar
unknown committed
2995

unknown's avatar
unknown committed
2996

2997 2998
uchar* sys_var_pluginvar::do_value_ptr(THD *thd, enum_var_type type,
                                       LEX_STRING *base)
unknown's avatar
unknown committed
2999
{
unknown's avatar
unknown committed
3000
  uchar* result;
unknown's avatar
unknown committed
3001 3002 3003

  result= real_value_ptr(thd, type);

3004
  if ((plugin_var->flags & PLUGIN_VAR_TYPEMASK) == PLUGIN_VAR_ENUM)
unknown's avatar
unknown committed
3005
    result= (uchar*) get_type(plugin_var_typelib(), *(ulong*)result);
3006
  else if ((plugin_var->flags & PLUGIN_VAR_TYPEMASK) == PLUGIN_VAR_SET)
3007 3008
    result= (uchar*) set_to_string(thd, 0, *(ulonglong*) result,
                                   plugin_var_typelib()->type_names);
unknown's avatar
unknown committed
3009 3010 3011
  return result;
}

3012
bool sys_var_pluginvar::do_check(THD *thd, set_var *var)
unknown's avatar
unknown committed
3013 3014
{
  st_item_value_holder value;
3015 3016
  DBUG_ASSERT(!is_readonly());
  DBUG_ASSERT(plugin_var->check);
unknown's avatar
unknown committed
3017

unknown's avatar
unknown committed
3018 3019 3020 3021
  value.value_type= item_value_type;
  value.val_str= item_val_str;
  value.val_int= item_val_int;
  value.val_real= item_val_real;
3022
  value.is_unsigned= item_is_unsigned;
unknown's avatar
unknown committed
3023
  value.item= var->value;
unknown's avatar
unknown committed
3024

3025
  return plugin_var->check(thd, plugin_var, &var->save_result, &value);
unknown's avatar
unknown committed
3026 3027
}

3028
bool sys_var_pluginvar::session_update(THD *thd, set_var *var)
unknown's avatar
unknown committed
3029
{
3030
  bool rc= false;
3031 3032 3033
  DBUG_ASSERT(!is_readonly());
  DBUG_ASSERT(plugin_var->flags & PLUGIN_VAR_THDLOCAL);
  DBUG_ASSERT(thd == current_thd);
unknown's avatar
unknown committed
3034

Marc Alff's avatar
Marc Alff committed
3035
  mysql_mutex_lock(&LOCK_global_system_variables);
3036 3037 3038
  void *tgt= real_value_ptr(thd, var->type);
  const void *src= var->value ? (void*)&var->save_result
                              : (void*)real_value_ptr(thd, OPT_GLOBAL);
Marc Alff's avatar
Marc Alff committed
3039
  mysql_mutex_unlock(&LOCK_global_system_variables);
unknown's avatar
unknown committed
3040

3041 3042 3043 3044 3045 3046 3047 3048
  if ((plugin_var->flags & PLUGIN_VAR_TYPEMASK) == PLUGIN_VAR_STR &&
      plugin_var->flags & PLUGIN_VAR_MEMALLOC)
    rc= plugin_var_memalloc_session_update(thd, plugin_var, (char **) tgt,
                                           *(const char **) src);
  else 
    plugin_var->update(thd, plugin_var, tgt, src);

  return rc;
unknown's avatar
unknown committed
3049
}
unknown's avatar
unknown committed
3050

3051
bool sys_var_pluginvar::global_update(THD *thd, set_var *var)
unknown's avatar
unknown committed
3052
{
3053
  bool rc= false;
3054
  DBUG_ASSERT(!is_readonly());
Marc Alff's avatar
Marc Alff committed
3055
  mysql_mutex_assert_owner(&LOCK_global_system_variables);
unknown's avatar
unknown committed
3056

3057 3058
  void *tgt= real_value_ptr(thd, var->type);
  const void *src= &var->save_result;
unknown's avatar
unknown committed
3059

3060
  if (!var->value)
unknown's avatar
unknown committed
3061
  {
3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083
    switch (plugin_var->flags & (PLUGIN_VAR_TYPEMASK | PLUGIN_VAR_THDLOCAL)) {
    case PLUGIN_VAR_INT:
      src= &((sysvar_uint_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_LONG:
      src= &((sysvar_ulong_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_LONGLONG:
      src= &((sysvar_ulonglong_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_ENUM:
      src= &((sysvar_enum_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_SET:
      src= &((sysvar_set_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_BOOL:
      src= &((sysvar_bool_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_STR:
      src= &((sysvar_str_t*) plugin_var)->def_val;
      break;
3084 3085 3086
    case PLUGIN_VAR_DOUBLE:
      src= &((sysvar_double_t*) plugin_var)->def_val;
      break;
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
    case PLUGIN_VAR_INT | PLUGIN_VAR_THDLOCAL:
      src= &((thdvar_uint_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_LONG | PLUGIN_VAR_THDLOCAL:
      src= &((thdvar_ulong_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_LONGLONG | PLUGIN_VAR_THDLOCAL:
      src= &((thdvar_ulonglong_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_ENUM | PLUGIN_VAR_THDLOCAL:
      src= &((thdvar_enum_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_SET | PLUGIN_VAR_THDLOCAL:
      src= &((thdvar_set_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_BOOL | PLUGIN_VAR_THDLOCAL:
      src= &((thdvar_bool_t*) plugin_var)->def_val;
      break;
    case PLUGIN_VAR_STR | PLUGIN_VAR_THDLOCAL:
      src= &((thdvar_str_t*) plugin_var)->def_val;
      break;
3108 3109 3110
    case PLUGIN_VAR_DOUBLE | PLUGIN_VAR_THDLOCAL:
      src= &((thdvar_double_t*) plugin_var)->def_val;
      break;
3111 3112 3113
    default:
      DBUG_ASSERT(0);
    }
unknown's avatar
unknown committed
3114
  }
3115

3116 3117 3118 3119 3120 3121
  if ((plugin_var->flags & PLUGIN_VAR_TYPEMASK) == PLUGIN_VAR_STR &&
      plugin_var->flags & PLUGIN_VAR_MEMALLOC)
    rc= plugin_var_memalloc_global_update(thd, plugin_var, (char **) tgt,
                                          *(const char **) src);
  else 
    plugin_var->update(thd, plugin_var, tgt, src);
3122

3123
  return rc;
unknown's avatar
unknown committed
3124 3125 3126 3127 3128 3129 3130 3131
}


#define OPTION_SET_LIMITS(type, options, opt) \
  options->var_type= type; \
  options->def_value= (opt)->def_val; \
  options->min_value= (opt)->min_val; \
  options->max_value= (opt)->max_val; \
3132
  options->block_size= (long) (opt)->blk_sz
unknown's avatar
unknown committed
3133

3134 3135 3136 3137 3138 3139 3140
#define OPTION_SET_LIMITS_DOUBLE(options, opt) \
  options->var_type= GET_DOUBLE; \
  options->def_value= (longlong) getopt_double2ulonglong((opt)->def_val); \
  options->min_value= (longlong) getopt_double2ulonglong((opt)->min_val); \
  options->max_value= getopt_double2ulonglong((opt)->max_val); \
  options->block_size= (long) (opt)->blk_sz;

unknown's avatar
unknown committed
3141 3142 3143 3144

static void plugin_opt_set_limits(struct my_option *options,
                                  const struct st_mysql_sys_var *opt)
{
3145 3146
  options->sub_size= 0;

unknown's avatar
unknown committed
3147
  switch (opt->flags & (PLUGIN_VAR_TYPEMASK |
unknown's avatar
unknown committed
3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169
                        PLUGIN_VAR_UNSIGNED | PLUGIN_VAR_THDLOCAL)) {
  /* global system variables */
  case PLUGIN_VAR_INT:
    OPTION_SET_LIMITS(GET_INT, options, (sysvar_int_t*) opt);
    break;
  case PLUGIN_VAR_INT | PLUGIN_VAR_UNSIGNED:
    OPTION_SET_LIMITS(GET_UINT, options, (sysvar_uint_t*) opt);
    break;
  case PLUGIN_VAR_LONG:
    OPTION_SET_LIMITS(GET_LONG, options, (sysvar_long_t*) opt);
    break;
  case PLUGIN_VAR_LONG | PLUGIN_VAR_UNSIGNED:
    OPTION_SET_LIMITS(GET_ULONG, options, (sysvar_ulong_t*) opt);
    break;
  case PLUGIN_VAR_LONGLONG:
    OPTION_SET_LIMITS(GET_LL, options, (sysvar_longlong_t*) opt);
    break;
  case PLUGIN_VAR_LONGLONG | PLUGIN_VAR_UNSIGNED:
    OPTION_SET_LIMITS(GET_ULL, options, (sysvar_ulonglong_t*) opt);
    break;
  case PLUGIN_VAR_ENUM:
    options->var_type= GET_ENUM;
unknown's avatar
unknown committed
3170
    options->typelib= ((sysvar_enum_t*) opt)->typelib;
unknown's avatar
unknown committed
3171
    options->def_value= ((sysvar_enum_t*) opt)->def_val;
unknown's avatar
unknown committed
3172 3173 3174 3175 3176
    options->min_value= options->block_size= 0;
    options->max_value= options->typelib->count - 1;
    break;
  case PLUGIN_VAR_SET:
    options->var_type= GET_SET;
unknown's avatar
unknown committed
3177
    options->typelib= ((sysvar_set_t*) opt)->typelib;
unknown's avatar
unknown committed
3178
    options->def_value= ((sysvar_set_t*) opt)->def_val;
unknown's avatar
unknown committed
3179
    options->min_value= options->block_size= 0;
3180
    options->max_value= (1ULL << options->typelib->count) - 1;
unknown's avatar
unknown committed
3181 3182 3183
    break;
  case PLUGIN_VAR_BOOL:
    options->var_type= GET_BOOL;
unknown's avatar
unknown committed
3184
    options->def_value= ((sysvar_bool_t*) opt)->def_val;
unknown's avatar
unknown committed
3185 3186
    break;
  case PLUGIN_VAR_STR:
3187 3188
    options->var_type= ((opt->flags & PLUGIN_VAR_MEMALLOC) ?
                        GET_STR_ALLOC : GET_STR);
unknown's avatar
unknown committed
3189
    options->def_value= (intptr) ((sysvar_str_t*) opt)->def_val;
unknown's avatar
unknown committed
3190
    break;
3191 3192 3193
  case PLUGIN_VAR_DOUBLE:
    OPTION_SET_LIMITS_DOUBLE(options, (sysvar_double_t*) opt);
    break;
unknown's avatar
unknown committed
3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
  /* threadlocal variables */
  case PLUGIN_VAR_INT | PLUGIN_VAR_THDLOCAL:
    OPTION_SET_LIMITS(GET_INT, options, (thdvar_int_t*) opt);
    break;
  case PLUGIN_VAR_INT | PLUGIN_VAR_UNSIGNED | PLUGIN_VAR_THDLOCAL:
    OPTION_SET_LIMITS(GET_UINT, options, (thdvar_uint_t*) opt);
    break;
  case PLUGIN_VAR_LONG | PLUGIN_VAR_THDLOCAL:
    OPTION_SET_LIMITS(GET_LONG, options, (thdvar_long_t*) opt);
    break;
  case PLUGIN_VAR_LONG | PLUGIN_VAR_UNSIGNED | PLUGIN_VAR_THDLOCAL:
    OPTION_SET_LIMITS(GET_ULONG, options, (thdvar_ulong_t*) opt);
    break;
  case PLUGIN_VAR_LONGLONG | PLUGIN_VAR_THDLOCAL:
    OPTION_SET_LIMITS(GET_LL, options, (thdvar_longlong_t*) opt);
    break;
  case PLUGIN_VAR_LONGLONG | PLUGIN_VAR_UNSIGNED | PLUGIN_VAR_THDLOCAL:
    OPTION_SET_LIMITS(GET_ULL, options, (thdvar_ulonglong_t*) opt);
    break;
3213 3214 3215
  case PLUGIN_VAR_DOUBLE | PLUGIN_VAR_THDLOCAL:
    OPTION_SET_LIMITS_DOUBLE(options, (thdvar_double_t*) opt);
    break;
unknown's avatar
unknown committed
3216 3217
  case PLUGIN_VAR_ENUM | PLUGIN_VAR_THDLOCAL:
    options->var_type= GET_ENUM;
unknown's avatar
unknown committed
3218
    options->typelib= ((thdvar_enum_t*) opt)->typelib;
unknown's avatar
unknown committed
3219
    options->def_value= ((thdvar_enum_t*) opt)->def_val;
unknown's avatar
unknown committed
3220 3221 3222 3223 3224
    options->min_value= options->block_size= 0;
    options->max_value= options->typelib->count - 1;
    break;
  case PLUGIN_VAR_SET | PLUGIN_VAR_THDLOCAL:
    options->var_type= GET_SET;
unknown's avatar
unknown committed
3225
    options->typelib= ((thdvar_set_t*) opt)->typelib;
unknown's avatar
unknown committed
3226
    options->def_value= ((thdvar_set_t*) opt)->def_val;
unknown's avatar
unknown committed
3227
    options->min_value= options->block_size= 0;
3228
    options->max_value= (1ULL << options->typelib->count) - 1;
unknown's avatar
unknown committed
3229 3230 3231
    break;
  case PLUGIN_VAR_BOOL | PLUGIN_VAR_THDLOCAL:
    options->var_type= GET_BOOL;
unknown's avatar
unknown committed
3232
    options->def_value= ((thdvar_bool_t*) opt)->def_val;
unknown's avatar
unknown committed
3233 3234
    break;
  case PLUGIN_VAR_STR | PLUGIN_VAR_THDLOCAL:
3235 3236
    options->var_type= ((opt->flags & PLUGIN_VAR_MEMALLOC) ?
                        GET_STR_ALLOC : GET_STR);
unknown's avatar
unknown committed
3237
    options->def_value= (intptr) ((thdvar_str_t*) opt)->def_val;
unknown's avatar
unknown committed
3238 3239 3240 3241 3242 3243 3244 3245
    break;
  default:
    DBUG_ASSERT(0);
  }
  options->arg_type= REQUIRED_ARG;
  if (opt->flags & PLUGIN_VAR_NOCMDARG)
    options->arg_type= NO_ARG;
  if (opt->flags & PLUGIN_VAR_OPCMDARG)
unknown's avatar
unknown committed
3246
    options->arg_type= OPT_ARG;
unknown's avatar
unknown committed
3247 3248
}

3249 3250
extern "C" my_bool get_one_plugin_option(int optid, const struct my_option *,
                                         char *);
unknown's avatar
unknown committed
3251

3252
my_bool get_one_plugin_option(int optid __attribute__((unused)),
unknown's avatar
unknown committed
3253 3254 3255 3256 3257 3258 3259
                              const struct my_option *opt,
                              char *argument)
{
  return 0;
}


3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278
/**
  Creates a set of my_option objects associated with a specified plugin-
  handle.

  @param mem_root Memory allocator to be used.
  @param tmp A pointer to a plugin handle
  @param[out] options A pointer to a pre-allocated static array

  The set is stored in the pre-allocated static array supplied to the function.
  The size of the array is calculated as (number_of_plugin_varaibles*2+3). The
  reason is that each option can have a prefix '--plugin-' in addtion to the
  shorter form '--&lt;plugin-name&gt;'. There is also space allocated for
  terminating NULL pointers.

  @return
    @retval -1 An error occurred
    @retval 0 Success
*/

unknown's avatar
unknown committed
3279
static int construct_options(MEM_ROOT *mem_root, struct st_plugin_int *tmp,
3280
                             my_option *options)
unknown's avatar
unknown committed
3281 3282
{
  const char *plugin_name= tmp->plugin->name;
3283 3284 3285 3286 3287 3288 3289
  const LEX_STRING plugin_dash = { C_STRING_WITH_LEN("plugin-") };
  uint plugin_name_len= strlen(plugin_name);
  uint optnamelen;
  const int max_comment_len= 180;
  char *comment= (char *) alloc_root(mem_root, max_comment_len + 1);
  char *optname;

unknown's avatar
unknown committed
3290 3291 3292
  int index= 0, offset= 0;
  st_mysql_sys_var *opt, **plugin_option;
  st_bookmark *v;
3293 3294 3295 3296

  /** Used to circumvent the const attribute on my_option::name */
  char *plugin_name_ptr, *plugin_name_with_prefix_ptr;

unknown's avatar
unknown committed
3297
  DBUG_ENTER("construct_options");
unknown's avatar
unknown committed
3298

3299
  plugin_name_ptr= (char*) alloc_root(mem_root, plugin_name_len + 1);
3300 3301 3302
  strcpy(plugin_name_ptr, plugin_name);
  my_casedn_str(&my_charset_latin1, plugin_name_ptr);
  convert_underscore_to_dash(plugin_name_ptr, plugin_name_len);
3303 3304 3305 3306 3307
  plugin_name_with_prefix_ptr= (char*) alloc_root(mem_root,
                                                  plugin_name_len +
                                                  plugin_dash.length + 1);
  strxmov(plugin_name_with_prefix_ptr, plugin_dash.str, plugin_name_ptr, NullS);

Sergey Vojtovich's avatar
Sergey Vojtovich committed
3308 3309
  if (tmp->load_option != PLUGIN_FORCE &&
      tmp->load_option != PLUGIN_FORCE_PLUS_PERMANENT)
3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327
  {
    /* support --skip-plugin-foo syntax */
    options[0].name= plugin_name_ptr;
    options[1].name= plugin_name_with_prefix_ptr;
    options[0].id= options[1].id= 0;
    options[0].var_type= options[1].var_type= GET_ENUM;
    options[0].arg_type= options[1].arg_type= OPT_ARG;
    options[0].def_value= options[1].def_value= 1; /* ON */
    options[0].typelib= options[1].typelib= &global_plugin_typelib;

    strxnmov(comment, max_comment_len, "Enable or disable ", plugin_name,
            " plugin. Possible values are ON, OFF, FORCE (don't start "
            "if the plugin fails to load).", NullS);
    options[0].comment= comment;
    /*
      Allocate temporary space for the value of the tristate.
      This option will have a limited lifetime and is not used beyond
      server initialization.
Georgi Kodinov's avatar
merge  
Georgi Kodinov committed
3328
      GET_ENUM value is an unsigned long integer.
3329 3330
    */
    options[0].value= options[1].value=
Georgi Kodinov's avatar
merge  
Georgi Kodinov committed
3331 3332
                      (uchar **)alloc_root(mem_root, sizeof(ulong));
    *((ulong*) options[0].value)= (ulong) options[0].def_value;
unknown's avatar
unknown committed
3333

3334 3335
    options+= 2;
  }
unknown's avatar
unknown committed
3336

3337 3338 3339 3340 3341
  if (!my_strcasecmp(&my_charset_latin1, plugin_name_ptr, "NDBCLUSTER"))
  {
    plugin_name_ptr= const_cast<char*>("ndb"); // Use legacy "ndb" prefix
    plugin_name_len= 3;
  }
unknown's avatar
unknown committed
3342 3343 3344 3345 3346 3347

  /*
    Two passes as the 2nd pass will take pointer addresses for use
    by my_getopt and register_var() in the first pass uses realloc
  */

unknown's avatar
unknown committed
3348
  for (plugin_option= tmp->plugin->system_vars;
unknown's avatar
unknown committed
3349 3350
       plugin_option && *plugin_option; plugin_option++, index++)
  {
unknown's avatar
unknown committed
3351
    opt= *plugin_option;
unknown's avatar
unknown committed
3352 3353
    if (!(opt->flags & PLUGIN_VAR_THDLOCAL))
      continue;
3354
    if (!(register_var(plugin_name_ptr, opt->name, opt->flags)))
unknown's avatar
unknown committed
3355 3356 3357
      continue;
    switch (opt->flags & PLUGIN_VAR_TYPEMASK) {
    case PLUGIN_VAR_BOOL:
3358
      ((thdvar_bool_t *) opt)->resolve= mysql_sys_var_char;
unknown's avatar
unknown committed
3359 3360
      break;
    case PLUGIN_VAR_INT:
3361
      ((thdvar_int_t *) opt)->resolve= mysql_sys_var_int;
unknown's avatar
unknown committed
3362 3363
      break;
    case PLUGIN_VAR_LONG:
3364
      ((thdvar_long_t *) opt)->resolve= mysql_sys_var_long;
unknown's avatar
unknown committed
3365 3366
      break;
    case PLUGIN_VAR_LONGLONG:
3367
      ((thdvar_longlong_t *) opt)->resolve= mysql_sys_var_longlong;
unknown's avatar
unknown committed
3368 3369
      break;
    case PLUGIN_VAR_STR:
3370
      ((thdvar_str_t *) opt)->resolve= mysql_sys_var_str;
unknown's avatar
unknown committed
3371 3372
      break;
    case PLUGIN_VAR_ENUM:
3373
      ((thdvar_enum_t *) opt)->resolve= mysql_sys_var_ulong;
unknown's avatar
unknown committed
3374
      break;
unknown's avatar
unknown committed
3375
    case PLUGIN_VAR_SET:
3376
      ((thdvar_set_t *) opt)->resolve= mysql_sys_var_ulonglong;
unknown's avatar
unknown committed
3377
      break;
3378 3379 3380
    case PLUGIN_VAR_DOUBLE:
      ((thdvar_double_t *) opt)->resolve= mysql_sys_var_double;
      break;
unknown's avatar
unknown committed
3381 3382
    default:
      sql_print_error("Unknown variable type code 0x%x in plugin '%s'.",
unknown's avatar
unknown committed
3383
                      opt->flags, plugin_name);
unknown's avatar
unknown committed
3384 3385 3386 3387
      DBUG_RETURN(-1);
    };
  }

unknown's avatar
unknown committed
3388
  for (plugin_option= tmp->plugin->system_vars;
unknown's avatar
unknown committed
3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421
       plugin_option && *plugin_option; plugin_option++, index++)
  {
    switch ((opt= *plugin_option)->flags & PLUGIN_VAR_TYPEMASK) {
    case PLUGIN_VAR_BOOL:
      if (!opt->check)
        opt->check= check_func_bool;
      if (!opt->update)
        opt->update= update_func_bool;
      break;
    case PLUGIN_VAR_INT:
      if (!opt->check)
        opt->check= check_func_int;
      if (!opt->update)
        opt->update= update_func_int;
      break;
    case PLUGIN_VAR_LONG:
      if (!opt->check)
        opt->check= check_func_long;
      if (!opt->update)
        opt->update= update_func_long;
      break;
    case PLUGIN_VAR_LONGLONG:
      if (!opt->check)
        opt->check= check_func_longlong;
      if (!opt->update)
        opt->update= update_func_longlong;
      break;
    case PLUGIN_VAR_STR:
      if (!opt->check)
        opt->check= check_func_str;
      if (!opt->update)
      {
        opt->update= update_func_str;
3422
        if (!(opt->flags & (PLUGIN_VAR_MEMALLOC | PLUGIN_VAR_READONLY)))
unknown's avatar
unknown committed
3423
        {
3424
          opt->flags|= PLUGIN_VAR_READONLY;
unknown's avatar
unknown committed
3425 3426 3427 3428 3429
          sql_print_warning("Server variable %s of plugin %s was forced "
                            "to be read-only: string variable without "
                            "update_func and PLUGIN_VAR_MEMALLOC flag",
                            opt->name, plugin_name);
        }
unknown's avatar
unknown committed
3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441
      }
      break;
    case PLUGIN_VAR_ENUM:
      if (!opt->check)
        opt->check= check_func_enum;
      if (!opt->update)
        opt->update= update_func_long;
      break;
    case PLUGIN_VAR_SET:
      if (!opt->check)
        opt->check= check_func_set;
      if (!opt->update)
unknown's avatar
unknown committed
3442
        opt->update= update_func_longlong;
unknown's avatar
unknown committed
3443
      break;
3444 3445 3446 3447 3448 3449
    case PLUGIN_VAR_DOUBLE:
      if (!opt->check)
        opt->check= check_func_double;
      if (!opt->update)
        opt->update= update_func_double;
      break;
unknown's avatar
unknown committed
3450 3451
    default:
      sql_print_error("Unknown variable type code 0x%x in plugin '%s'.",
unknown's avatar
unknown committed
3452
                      opt->flags, plugin_name);
unknown's avatar
unknown committed
3453 3454
      DBUG_RETURN(-1);
    }
unknown's avatar
unknown committed
3455

unknown's avatar
unknown committed
3456 3457
    if ((opt->flags & (PLUGIN_VAR_NOCMDOPT | PLUGIN_VAR_THDLOCAL))
                    == PLUGIN_VAR_NOCMDOPT)
unknown's avatar
unknown committed
3458 3459 3460 3461 3462
      continue;

    if (!opt->name)
    {
      sql_print_error("Missing variable name in plugin '%s'.",
unknown's avatar
unknown committed
3463
                      plugin_name);
unknown's avatar
unknown committed
3464 3465 3466
      DBUG_RETURN(-1);
    }

unknown's avatar
unknown committed
3467
    if (!(opt->flags & PLUGIN_VAR_THDLOCAL))
unknown's avatar
unknown committed
3468 3469
    {
      optnamelen= strlen(opt->name);
3470 3471 3472
      optname= (char*) alloc_root(mem_root, plugin_name_len + optnamelen + 2);
      strxmov(optname, plugin_name_ptr, "-", opt->name, NullS);
      optnamelen= plugin_name_len + optnamelen + 1;
unknown's avatar
unknown committed
3473 3474
    }
    else
unknown's avatar
unknown committed
3475 3476
    {
      /* this should not fail because register_var should create entry */
3477
      if (!(v= find_bookmark(plugin_name_ptr, opt->name, opt->flags)))
unknown's avatar
unknown committed
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491
      {
        sql_print_error("Thread local variable '%s' not allocated "
                        "in plugin '%s'.", opt->name, plugin_name);
        DBUG_RETURN(-1);
      }

      *(int*)(opt + 1)= offset= v->offset;

      if (opt->flags & PLUGIN_VAR_NOCMDOPT)
        continue;

      optname= (char*) memdup_root(mem_root, v->key + 1, 
                                   (optnamelen= v->name_len) + 1);
    }
unknown's avatar
unknown committed
3492

3493
    convert_underscore_to_dash(optname, optnamelen);
unknown's avatar
unknown committed
3494 3495 3496

    options->name= optname;
    options->comment= opt->comment;
unknown's avatar
unknown committed
3497
    options->app_type= opt;
3498
    options->id= 0;
unknown's avatar
unknown committed
3499

unknown's avatar
unknown committed
3500
    plugin_opt_set_limits(options, opt);
unknown's avatar
unknown committed
3501

unknown's avatar
unknown committed
3502 3503 3504 3505 3506
    if (opt->flags & PLUGIN_VAR_THDLOCAL)
      options->value= options->u_max_value= (uchar**)
        (global_system_variables.dynamic_variables_ptr + offset);
    else
      options->value= options->u_max_value= *(uchar***) (opt + 1);
unknown's avatar
unknown committed
3507

3508
    char *option_name_ptr;
unknown's avatar
unknown committed
3509
    options[1]= options[0];
3510 3511 3512 3513 3514
    options[1].name= option_name_ptr= (char*) alloc_root(mem_root,
                                                        plugin_dash.length +
                                                        optnamelen + 1);
    options[1].comment= 0; /* Hidden from the help text */
    strxmov(option_name_ptr, plugin_dash.str, optname, NullS);
unknown's avatar
unknown committed
3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530

    options+= 2;
  }

  DBUG_RETURN(0);
}


static my_option *construct_help_options(MEM_ROOT *mem_root,
                                         struct st_plugin_int *p)
{
  st_mysql_sys_var **opt;
  my_option *opts;
  uint count= EXTRA_OPTIONS;
  DBUG_ENTER("construct_help_options");

3531 3532
  for (opt= p->plugin->system_vars; opt && *opt; opt++, count+= 2)
    ;
unknown's avatar
unknown committed
3533 3534 3535 3536 3537 3538

  if (!(opts= (my_option*) alloc_root(mem_root, sizeof(my_option) * count)))
    DBUG_RETURN(NULL);

  bzero(opts, sizeof(my_option) * count);

3539 3540 3541 3542 3543 3544 3545 3546
  /**
    some plugin variables (those that don't have PLUGIN_VAR_NOSYSVAR flag)
    have their names prefixed with the plugin name. Restore the names here
    to get the correct (not double-prefixed) help text.
    We won't need @@sysvars anymore and don't care about their proper names.
  */
  restore_pluginvar_names(p->system_vars);

3547
  if (construct_options(mem_root, p, opts))
unknown's avatar
unknown committed
3548 3549 3550 3551 3552
    DBUG_RETURN(NULL);

  DBUG_RETURN(opts);
}

3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570
/**
  Create and register system variables supplied from the plugin and
  assigns initial values from corresponding command line arguments.

  @param tmp_root Temporary scratch space
  @param[out] plugin Internal plugin structure
  @param argc Number of command line arguments
  @param argv Command line argument vector

  The plugin will be updated with a policy on how to handle errors during
  initialization.

  @note Requires that a write-lock is held on LOCK_system_variables_hash

  @return How initialization of the plugin should be handled.
    @retval  0 Initialization should proceed.
    @retval  1 Plugin is disabled.
    @retval -1 An error has occurred.
unknown's avatar
unknown committed
3571
*/
3572

unknown's avatar
unknown committed
3573
static int test_plugin_options(MEM_ROOT *tmp_root, struct st_plugin_int *tmp,
3574
                               int *argc, char **argv)
unknown's avatar
unknown committed
3575 3576
{
  struct sys_var_chain chain= { NULL, NULL };
3577
  bool disable_plugin;
Sergey Vojtovich's avatar
Sergey Vojtovich committed
3578
  enum_plugin_load_option plugin_load_option= tmp->load_option;
3579

unknown's avatar
unknown committed
3580
  MEM_ROOT *mem_root= alloc_root_inited(&tmp->mem_root) ?
unknown's avatar
unknown committed
3581 3582
                      &tmp->mem_root : &plugin_mem_root;
  st_mysql_sys_var **opt;
3583
  my_option *opts= NULL;
3584
  LEX_STRING plugin_name;
3585
  char *varname;
unknown's avatar
unknown committed
3586
  int error;
3587
  sys_var *v __attribute__((unused));
unknown's avatar
unknown committed
3588 3589 3590
  struct st_bookmark *var;
  uint len, count= EXTRA_OPTIONS;
  DBUG_ENTER("test_plugin_options");
unknown's avatar
unknown committed
3591
  DBUG_ASSERT(tmp->plugin && tmp->name.str);
unknown's avatar
unknown committed
3592

3593 3594 3595 3596 3597 3598
  /*
    The 'federated' and 'ndbcluster' storage engines are always disabled by
    default.
  */
  if (!(my_strcasecmp(&my_charset_latin1, tmp->name.str, "federated") &&
      my_strcasecmp(&my_charset_latin1, tmp->name.str, "ndbcluster")))
Sergey Vojtovich's avatar
Sergey Vojtovich committed
3599
    plugin_load_option= PLUGIN_OFF;
3600

unknown's avatar
unknown committed
3601 3602 3603 3604
  for (opt= tmp->plugin->system_vars; opt && *opt; opt++)
    count+= 2; /* --{plugin}-{optname} and --plugin-{plugin}-{optname} */

  if (count > EXTRA_OPTIONS || (*argc > 1))
unknown's avatar
unknown committed
3605
  {
unknown's avatar
unknown committed
3606 3607
    if (!(opts= (my_option*) alloc_root(tmp_root, sizeof(my_option) * count)))
    {
unknown's avatar
unknown committed
3608
      sql_print_error("Out of memory for plugin '%s'.", tmp->name.str);
unknown's avatar
unknown committed
3609 3610 3611
      DBUG_RETURN(-1);
    }
    bzero(opts, sizeof(my_option) * count);
unknown's avatar
unknown committed
3612

3613
    if (construct_options(tmp_root, tmp, opts))
unknown's avatar
unknown committed
3614
    {
unknown's avatar
unknown committed
3615
      sql_print_error("Bad options for plugin '%s'.", tmp->name.str);
unknown's avatar
unknown committed
3616 3617 3618
      DBUG_RETURN(-1);
    }

3619 3620 3621 3622
    /*
      We adjust the default value to account for the hardcoded exceptions
      we have set for the federated and ndbcluster storage engines.
    */
Sergey Vojtovich's avatar
Sergey Vojtovich committed
3623 3624 3625
    if (tmp->load_option != PLUGIN_FORCE &&
        tmp->load_option != PLUGIN_FORCE_PLUS_PERMANENT)
      opts[0].def_value= opts[1].def_value= plugin_load_option;
3626

Marc Alff's avatar
Marc Alff committed
3627
    error= handle_options(argc, &argv, opts, NULL);
unknown's avatar
unknown committed
3628
    (*argc)++; /* add back one for the program name */
unknown's avatar
unknown committed
3629

unknown's avatar
unknown committed
3630 3631
    if (error)
    {
unknown's avatar
unknown committed
3632
       sql_print_error("Parsing options for plugin '%s' failed.",
unknown's avatar
unknown committed
3633
                       tmp->name.str);
unknown's avatar
unknown committed
3634
       goto err;
unknown's avatar
unknown committed
3635
    }
3636 3637 3638 3639
    /*
     Set plugin loading policy from option value. First element in the option
     list is always the <plugin name> option value.
    */
Sergey Vojtovich's avatar
Sergey Vojtovich committed
3640 3641 3642
    if (tmp->load_option != PLUGIN_FORCE &&
        tmp->load_option != PLUGIN_FORCE_PLUS_PERMANENT)
      plugin_load_option= (enum_plugin_load_option) *(ulong*) opts[0].value;
unknown's avatar
unknown committed
3643 3644
  }

Sergey Vojtovich's avatar
Sergey Vojtovich committed
3645 3646
  disable_plugin= (plugin_load_option == PLUGIN_OFF);
  tmp->load_option= plugin_load_option;
unknown's avatar
unknown committed
3647

3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659
  /*
    If the plugin is disabled it should not be initialized.
  */
  if (disable_plugin)
  {
    if (global_system_variables.log_warnings)
      sql_print_information("Plugin '%s' is disabled.",
                            tmp->name.str);
    if (opts)
      my_cleanup_options(opts);
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
3660

3661 3662 3663 3664 3665 3666 3667 3668
  if (!my_strcasecmp(&my_charset_latin1, tmp->name.str, "NDBCLUSTER"))
  {
    plugin_name.str= const_cast<char*>("ndb"); // Use legacy "ndb" prefix
    plugin_name.length= 3;
  }
  else
    plugin_name= tmp->name;

3669 3670
  error= 1;
  for (opt= tmp->plugin->system_vars; opt && *opt; opt++)
unknown's avatar
unknown committed
3671
  {
3672
    st_mysql_sys_var *o;
3673 3674
    if (((o= *opt)->flags & PLUGIN_VAR_NOSYSVAR))
      continue;
3675 3676
    if ((var= find_bookmark(plugin_name.str, o->name, o->flags)))
      v= new (mem_root) sys_var_pluginvar(&chain, var->key + 1, o);
3677
    else
unknown's avatar
unknown committed
3678
    {
3679
      len= plugin_name.length + strlen(o->name) + 2;
3680
      varname= (char*) alloc_root(mem_root, len);
3681
      strxmov(varname, plugin_name.str, "-", o->name, NullS);
3682
      my_casedn_str(&my_charset_latin1, varname);
3683
      convert_dash_to_underscore(varname, len-1);
3684
      v= new (mem_root) sys_var_pluginvar(&chain, varname, o);
unknown's avatar
unknown committed
3685
    }
3686 3687 3688 3689 3690
    DBUG_ASSERT(v); /* check that an object was actually constructed */
  } /* end for */
  if (chain.first)
  {
    chain.last->next = NULL;
3691
    if (mysql_add_sys_var_chain(chain.first))
unknown's avatar
unknown committed
3692
    {
3693 3694 3695
      sql_print_error("Plugin '%s' has conflicting system variables",
                      tmp->name.str);
      goto err;
unknown's avatar
unknown committed
3696
    }
3697
    tmp->system_vars= chain.first;
unknown's avatar
unknown committed
3698
  }
3699 3700
  DBUG_RETURN(0);
  
unknown's avatar
unknown committed
3701
err:
3702 3703
  if (opts)
    my_cleanup_options(opts);
unknown's avatar
unknown committed
3704
  DBUG_RETURN(error);
unknown's avatar
unknown committed
3705 3706 3707 3708 3709 3710 3711 3712
}


/****************************************************************************
  Help Verbose text with Plugin System Variables
****************************************************************************/


3713
void add_plugin_options(DYNAMIC_ARRAY *options, MEM_ROOT *mem_root)
unknown's avatar
unknown committed
3714 3715 3716 3717
{
  struct st_plugin_int *p;
  my_option *opt;

3718 3719
  if (!initialized)
    return;
unknown's avatar
unknown committed
3720

3721 3722 3723
  for (uint idx= 0; idx < plugin_array.elements; idx++)
  {
    p= *dynamic_element(&plugin_array, idx, struct st_plugin_int **);
unknown's avatar
unknown committed
3724

3725 3726
    if (!(opt= construct_help_options(mem_root, p)))
      continue;
unknown's avatar
unknown committed
3727

3728 3729 3730 3731 3732
    /* Only options with a non-NULL comment are displayed in help text */
    for (;opt->name; opt++)
      if (opt->comment)
        insert_dynamic(options, (uchar*) opt);
  }
unknown's avatar
unknown committed
3733 3734
}