MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
sp_head.cc
1 /*
2  Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; version 2 of the License.
7 
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12 
13  You should have received a copy of the GNU General Public License
14  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 #include "my_global.h" // NO_EMBEDDED_ACCESS_CHECKS
18 #include "sql_priv.h"
19 #include "unireg.h"
20 #include "sql_prepare.h"
21 #include "sql_cache.h" // query_cache_*
22 #include "probes_mysql.h"
23 #include "sql_show.h" // append_identifier
24 #include "sql_db.h" // mysql_opt_change_db, mysql_change_db
25 #include "sql_table.h" // prepare_create_field
26 #include "sql_acl.h" // *_ACL
27 #include "sql_array.h" // Dynamic_array
28 #include "log_event.h" // append_query_string, Query_log_event
29 
30 #include "sp_head.h"
31 #include "sp_instr.h"
32 #include "sp.h"
33 #include "sp_pcontext.h"
34 #include "sp_rcontext.h"
35 #include "sp_cache.h"
36 #include "set_var.h"
37 #include "sql_parse.h" // cleanup_items
38 #include "sql_base.h" // close_thread_tables
39 #include "transaction.h" // trans_commit_stmt
40 #include "opt_trace.h" // opt_trace_disable_etc
41 #include "global_threads.h"
42 
43 #include <my_user.h> // parse_user
44 
49 struct SP_TABLE
50 {
51  /*
52  Multi-set key:
53  db_name\0table_name\0alias\0 - for normal tables
54  db_name\0table_name\0 - for temporary tables
55  Note that in both cases we don't take last '\0' into account when
56  we count length of key.
57  */
58  LEX_STRING qname;
59  uint db_length, table_name_length;
60  bool temp; /* true if corresponds to a temporary table */
61  thr_lock_type lock_type; /* lock type used for prelocking */
62  uint lock_count;
63  uint query_lock_count;
64  uint8 trg_event_map;
65 };
66 
67 
69 // Static function implementations.
71 
72 
73 uchar *sp_table_key(const uchar *ptr, size_t *plen, my_bool first)
74 {
75  SP_TABLE *tab= (SP_TABLE *)ptr;
76  *plen= tab->qname.length;
77  return (uchar *)tab->qname.str;
78 }
79 
80 
87 static void reset_start_time_for_sp(THD *thd)
88 {
89  if (thd->in_sub_stmt)
90  return;
91 
92  /*
93  First investigate if there is a cached time stamp
94  */
95  if (thd->user_time.tv_sec || thd->user_time.tv_usec)
96  thd->start_time= thd->user_time;
97  else
98  my_micro_time_to_timeval(my_micro_time(), &thd->start_time);
99 }
100 
101 
120 static bool sp_update_sp_used_routines(HASH *dst, HASH *src)
121 {
122  for (uint i= 0 ; i < src->records ; i++)
123  {
124  Sroutine_hash_entry *rt= (Sroutine_hash_entry *)my_hash_element(src, i);
125  if (!my_hash_search(dst, (uchar *)rt->mdl_request.key.ptr(),
126  rt->mdl_request.key.length()))
127  {
128  if (my_hash_insert(dst, (uchar *)rt))
129  return true;
130  }
131  }
132  return false;
133 }
134 
136 // sp_name implementation.
138 
151 sp_name::sp_name(const MDL_key *key, char *qname_buff)
152 {
153  m_db.str= (char*)key->db_name();
154  m_db.length= key->db_name_length();
155  m_name.str= (char*)key->name();
156  m_name.length= key->name_length();
157  m_qname.str= qname_buff;
158  if (m_db.length)
159  {
160  strxmov(qname_buff, m_db.str, ".", m_name.str, NullS);
161  m_qname.length= m_db.length + 1 + m_name.length;
162  }
163  else
164  {
165  strmov(qname_buff, m_name.str);
166  m_qname.length= m_name.length;
167  }
168  m_explicit_name= false;
169 }
170 
171 
175 void sp_name::init_qname(THD *thd)
176 {
177  const uint dot= !!m_db.length;
178  /* m_qname format: [database + dot] + name + '\0' */
179  m_qname.length= m_db.length + dot + m_name.length;
180  if (!(m_qname.str= (char*) thd->alloc(m_qname.length + 1)))
181  return;
182  sprintf(m_qname.str, "%.*s%.*s%.*s",
183  (int) m_db.length, (m_db.length ? m_db.str : ""),
184  dot, ".",
185  (int) m_name.length, m_name.str);
186 }
187 
189 // sp_head implementation.
191 
192 void *sp_head::operator new(size_t size) throw()
193 {
194  MEM_ROOT own_root;
195 
196  init_sql_alloc(&own_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC);
197 
198  sp_head *sp= (sp_head *) alloc_root(&own_root, size);
199  if (!sp)
200  return NULL;
201 
202  sp->main_mem_root= own_root;
203  DBUG_PRINT("info", ("mem_root 0x%lx", (ulong) &sp->mem_root));
204  return sp;
205 }
206 
207 void sp_head::operator delete(void *ptr, size_t size) throw()
208 {
209  if (!ptr)
210  return;
211 
212  sp_head *sp= (sp_head *) ptr;
213 
214  /* Make a copy of main_mem_root as free_root will free the sp */
215  MEM_ROOT own_root= sp->main_mem_root;
216  DBUG_PRINT("info", ("mem_root 0x%lx moved to 0x%lx",
217  (ulong) &sp->mem_root, (ulong) &own_root));
218  free_root(&own_root, MYF(0));
219 }
220 
221 
222 sp_head::sp_head(enum_sp_type type)
223  :Query_arena(&main_mem_root, STMT_INITIALIZED_FOR_SP),
224  m_type(type),
225  m_flags(0),
226  m_chistics(NULL),
227  m_sql_mode(0),
228  m_explicit_name(false),
229  m_created(0),
230  m_modified(0),
231  m_recursion_level(0),
232  m_next_cached_sp(NULL),
233  m_first_instance(NULL),
234  m_first_free_instance(NULL),
235  m_last_cached_sp(NULL),
236  m_trg_list(NULL),
237  m_root_parsing_ctx(NULL),
238  m_sp_cache_version(0),
239  m_creation_ctx(NULL),
240  unsafe_flags(0)
241 {
242  m_first_instance= this;
243  m_first_free_instance= this;
244  m_last_cached_sp= this;
245 
246  m_return_field_def.charset = NULL;
247 
248  /*
249  FIXME: the only use case when name is NULL is events, and it should
250  be rewritten soon. Remove the else part and replace 'if' with
251  an assert when this is done.
252  */
253 
254  m_db= NULL_STR;
255  m_name= NULL_STR;
256  m_qname= NULL_STR;
257 
258  m_params= NULL_STR;
259 
260  m_defstr= NULL_STR;
261  m_body= NULL_STR;
262  m_body_utf8= NULL_STR;
263 
264  my_hash_init(&m_sptabs, system_charset_info, 0, 0, 0, sp_table_key, 0, 0);
265  my_hash_init(&m_sroutines, system_charset_info, 0, 0, 0, sp_sroutine_key,
266  0, 0);
267 }
268 
269 
270 void sp_head::init_sp_name(THD *thd, sp_name *spname)
271 {
272  /* Must be initialized in the parser. */
273 
274  DBUG_ASSERT(spname && spname->m_db.str && spname->m_db.length);
275 
276  /* We have to copy strings to get them into the right memroot. */
277 
278  m_db.length= spname->m_db.length;
279  m_db.str= strmake_root(thd->mem_root, spname->m_db.str, spname->m_db.length);
280 
281  m_name.length= spname->m_name.length;
282  m_name.str= strmake_root(thd->mem_root, spname->m_name.str,
283  spname->m_name.length);
284 
286 
287  if (spname->m_qname.length == 0)
288  spname->init_qname(thd);
289 
290  m_qname.length= spname->m_qname.length;
291  m_qname.str= (char*) memdup_root(thd->mem_root,
292  spname->m_qname.str,
293  spname->m_qname.length + 1);
294 }
295 
296 
297 void sp_head::set_body_start(THD *thd, const char *begin_ptr)
298 {
299  m_parser_data.set_body_start_ptr(begin_ptr);
300 
301  thd->m_parser_state->m_lip.body_utf8_start(thd, begin_ptr);
302 }
303 
304 
305 void sp_head::set_body_end(THD *thd)
306 {
307  Lex_input_stream *lip= & thd->m_parser_state->m_lip; /* shortcut */
308  const char *end_ptr= lip->get_cpp_ptr(); /* shortcut */
309 
310  /* Make the string of parameters. */
311 
312  {
313  const char *p_start= m_parser_data.get_parameter_start_ptr();
314  const char *p_end= m_parser_data.get_parameter_end_ptr();
315 
316  if (p_start && p_end)
317  {
318  m_params.length= p_end - p_start;
319  m_params.str= thd->strmake(p_start, m_params.length);
320  }
321  }
322 
323  /* Remember end pointer for further dumping of whole statement. */
324 
325  thd->lex->stmt_definition_end= end_ptr;
326 
327  /* Make the string of body (in the original character set). */
328 
329  m_body.length= end_ptr - m_parser_data.get_body_start_ptr();
330  m_body.str= thd->strmake(m_parser_data.get_body_start_ptr(), m_body.length);
331  trim_whitespace(thd->charset(), & m_body);
332 
333  /* Make the string of UTF-body. */
334 
335  lip->body_utf8_append(end_ptr);
336 
337  m_body_utf8.length= lip->get_body_utf8_length();
338  m_body_utf8.str= thd->strmake(lip->get_body_utf8_str(), m_body_utf8.length);
339  trim_whitespace(thd->charset(), & m_body_utf8);
340 
341  /*
342  Make the string of whole stored-program-definition query (in the
343  original character set).
344  */
345 
346  m_defstr.length= end_ptr - lip->get_cpp_buf();
347  m_defstr.str= thd->strmake(lip->get_cpp_buf(), m_defstr.length);
348  trim_whitespace(thd->charset(), & m_defstr);
349 }
350 
351 
352 sp_head::~sp_head()
353 {
354  LEX *lex;
355  sp_instr *i;
356 
357  // Parsing of SP-body must have been already finished.
358  DBUG_ASSERT(!m_parser_data.is_parsing_sp_body());
359 
360  for (uint ip = 0 ; (i = get_instr(ip)) ; ip++)
361  delete i;
362 
363  delete m_root_parsing_ctx;
364 
365  free_items();
366 
367  /*
368  If we have non-empty LEX stack then we just came out of parser with
369  error. Now we should delete all auxiliary LEXes and restore original
370  THD::lex. It is safe to not update LEX::ptr because further query
371  string parsing and execution will be stopped anyway.
372  */
373  while ((lex= (LEX *) m_parser_data.pop_lex()))
374  {
375  THD *thd= lex->thd;
376  thd->lex->sphead= NULL;
377  lex_end(thd->lex);
378  delete thd->lex;
379  thd->lex= lex;
380  }
381 
382  my_hash_free(&m_sptabs);
383  my_hash_free(&m_sroutines);
384 
385  delete m_next_cached_sp;
386 }
387 
388 
389 Field *sp_head::create_result_field(uint field_max_length,
390  const char *field_name,
391  TABLE *table)
392 {
393  uint field_length= !m_return_field_def.length ?
394  field_max_length : m_return_field_def.length;
395 
396  Field *field=
397  ::make_field(table->s, /* TABLE_SHARE ptr */
398  (uchar*) 0, /* field ptr */
399  field_length, /* field [max] length */
400  (uchar*) "", /* null ptr */
401  0, /* null bit */
402  m_return_field_def.pack_flag,
403  m_return_field_def.sql_type,
404  m_return_field_def.charset,
405  m_return_field_def.geom_type,
406  Field::NONE, /* unreg check */
407  m_return_field_def.interval,
408  field_name ? field_name : (const char *) m_name.str);
409 
410  if (field)
411  field->init(table);
412 
413  return field;
414 }
415 
416 
417 bool sp_head::execute(THD *thd, bool merge_da_on_success)
418 {
419  char saved_cur_db_name_buf[NAME_LEN+1];
420  LEX_STRING saved_cur_db_name=
421  { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) };
422  bool cur_db_changed= FALSE;
423  bool err_status= FALSE;
424  uint ip= 0;
425  sql_mode_t save_sql_mode;
426  bool save_abort_on_warning;
427  Query_arena *old_arena;
428  /* per-instruction arena */
429  MEM_ROOT execute_mem_root;
430  Query_arena execute_arena(&execute_mem_root, STMT_INITIALIZED_FOR_SP),
431  backup_arena;
432  query_id_t old_query_id;
433  TABLE *old_derived_tables;
434  LEX *old_lex;
435  Item_change_list old_change_list;
436  String old_packet;
437  Object_creation_ctx *saved_creation_ctx;
438  Diagnostics_area *da= thd->get_stmt_da();
439  Warning_info sp_wi(da->warning_info_id(), false);
440 
441  /*
442  Just reporting a stack overrun error
443  (@sa check_stack_overrun()) requires stack memory for error
444  message buffer. Thus, we have to put the below check
445  relatively close to the beginning of the execution stack,
446  where available stack margin is still big. As long as the check
447  has to be fairly high up the call stack, the amount of memory
448  we "book" for has to stay fairly high as well, and hence
449  not very accurate. The number below has been calculated
450  by trial and error, and reflects the amount of memory necessary
451  to execute a single stored procedure instruction, be it either
452  an SQL statement, or, heaviest of all, a CALL, which involves
453  parsing and loading of another stored procedure into the cache
454  (@sa db_load_routine() and Bug#10100).
455 
456  TODO: that should be replaced by proper handling of stack overrun error.
457 
458  Stack size depends on the platform:
459  - for most platforms (8 * STACK_MIN_SIZE) is enough;
460  - for Solaris SPARC 64 (10 * STACK_MIN_SIZE) is required.
461  */
462 
463  {
464 #if defined(__sparcv9) && defined(__sun)
465  const int sp_stack_size= 10 * STACK_MIN_SIZE;
466 #else
467  const int sp_stack_size= 8 * STACK_MIN_SIZE;
468 #endif
469 
470  if (check_stack_overrun(thd, sp_stack_size, (uchar*) &old_packet))
471  return true;
472  }
473 
474  opt_trace_disable_if_no_security_context_access(thd);
475 
476  /* init per-instruction memroot */
477  init_sql_alloc(&execute_mem_root, MEM_ROOT_BLOCK_SIZE, 0);
478 
479  DBUG_ASSERT(!(m_flags & IS_INVOKED));
480  m_flags|= IS_INVOKED;
482  if (m_next_cached_sp)
483  {
484  DBUG_PRINT("info",
485  ("first free for 0x%lx ++: 0x%lx->0x%lx level: %lu flags %x",
486  (ulong)m_first_instance, (ulong) this,
487  (ulong) m_next_cached_sp,
488  m_next_cached_sp->m_recursion_level,
489  m_next_cached_sp->m_flags));
490  }
491  /*
492  Check that if there are not any instances after this one then
493  pointer to the last instance points on this instance or if there are
494  some instances after this one then recursion level of next instance
495  greater then recursion level of current instance on 1
496  */
497  DBUG_ASSERT((m_next_cached_sp == 0 &&
498  m_first_instance->m_last_cached_sp == this) ||
500 
501  /*
502  NOTE: The SQL Standard does not specify the context that should be
503  preserved for stored routines. However, at SAP/Walldorf meeting it was
504  decided that current database should be preserved.
505  */
506 
507  if (m_db.length &&
508  (err_status= mysql_opt_change_db(thd, &m_db, &saved_cur_db_name, FALSE,
509  &cur_db_changed)))
510  {
511  goto done;
512  }
513 
514  thd->is_slave_error= 0;
515  old_arena= thd->stmt_arena;
516 
517  /* Push a new warning information area. */
518  da->copy_sql_conditions_to_wi(thd, &sp_wi);
519  da->push_warning_info(&sp_wi);
520 
521  /*
522  Switch query context. This has to be done early as this is sometimes
523  allocated trough sql_alloc
524  */
525  saved_creation_ctx= m_creation_ctx->set_n_backup(thd);
526 
527  /*
528  We have to save/restore this info when we are changing call level to
529  be able properly do close_thread_tables() in instructions.
530  */
531  old_query_id= thd->query_id;
532  old_derived_tables= thd->derived_tables;
533  thd->derived_tables= 0;
534  save_sql_mode= thd->variables.sql_mode;
535  thd->variables.sql_mode= m_sql_mode;
536  save_abort_on_warning= thd->abort_on_warning;
537  thd->abort_on_warning= 0;
556  thd->push_reprepare_observer(NULL);
557 
558  /*
559  It is also more efficient to save/restore current thd->lex once when
560  do it in each instruction
561  */
562  old_lex= thd->lex;
563  /*
564  We should also save Item tree change list to avoid rollback something
565  too early in the calling query.
566  */
567  thd->change_list.move_elements_to(&old_change_list);
568  /*
569  Cursors will use thd->packet, so they may corrupt data which was prepared
570  for sending by upper level. OTOH cursors in the same routine can share this
571  buffer safely so let use use routine-local packet instead of having own
572  packet buffer for each cursor.
573 
574  It is probably safe to use same thd->convert_buff everywhere.
575  */
576  old_packet.swap(thd->packet);
577 
578  /*
579  Switch to per-instruction arena here. We can do it since we cleanup
580  arena after every instruction.
581  */
582  thd->set_n_backup_active_arena(&execute_arena, &backup_arena);
583 
584  /*
585  Save callers arena in order to store instruction results and out
586  parameters in it later during sp_eval_func_item()
587  */
588  thd->sp_runtime_ctx->callers_arena= &backup_arena;
589 
590 #if defined(ENABLED_PROFILING)
591  /* Discard the initial part of executing routines. */
592  thd->profiling.discard_current_query();
593 #endif
594  do
595  {
596  sp_instr *i;
597 
598 #if defined(ENABLED_PROFILING)
599  /*
600  Treat each "instr" of a routine as discrete unit that could be profiled.
601  Profiling only records information for segments of code that set the
602  source of the query, and almost all kinds of instructions in s-p do not.
603  */
604  thd->profiling.finish_current_query();
605  thd->profiling.start_new_query("continuing inside routine");
606 #endif
607 
608  /* get_instr returns NULL when we're done. */
609  i = get_instr(ip);
610  if (i == NULL)
611  {
612 #if defined(ENABLED_PROFILING)
613  thd->profiling.discard_current_query();
614 #endif
615  break;
616  }
617 
618  /* Reset number of warnings for this query. */
619  thd->get_stmt_da()->reset_for_next_command();
620 
621  DBUG_PRINT("execute", ("Instruction %u", ip));
622 
623  /*
624  We need to reset start_time to allow for time to flow inside a stored
625  procedure. This is only done for SP since time is suppose to be constant
626  during execution of triggers and functions.
627  */
628  reset_start_time_for_sp(thd);
629 
630  /*
631  We have to set thd->stmt_arena before executing the instruction
632  to store in the instruction free_list all new items, created
633  during the first execution (for example expanding of '*' or the
634  items made during other permanent subquery transformations).
635  */
636  thd->stmt_arena= i;
637 
638  /*
639  Will write this SP statement into binlog separately.
640  TODO: consider changing the condition to "not inside event union".
641  */
642  if (thd->locked_tables_mode <= LTM_LOCK_TABLES)
643  thd->user_var_events_alloc= thd->mem_root;
644 
645  err_status= i->execute(thd, &ip);
646 
647  if (i->free_list)
648  cleanup_items(i->free_list);
649 
650  /*
651  If we've set thd->user_var_events_alloc to mem_root of this SP
652  statement, clean all the events allocated in it.
653  */
654  if (thd->locked_tables_mode <= LTM_LOCK_TABLES)
655  {
656  reset_dynamic(&thd->user_var_events);
657  thd->user_var_events_alloc= NULL;//DEBUG
658  }
659 
660  /* we should cleanup free_list and memroot, used by instruction */
661  thd->cleanup_after_query();
662  free_root(&execute_mem_root, MYF(0));
663 
664  /*
665  Find and process SQL handlers unless it is a fatal error (fatal
666  errors are not catchable by SQL handlers) or the connection has been
667  killed during execution.
668  */
669  if (!thd->is_fatal_error && !thd->killed_errno() &&
670  thd->sp_runtime_ctx->handle_sql_condition(thd, &ip, i))
671  {
672  err_status= FALSE;
673  }
674 
675  /* Reset sp_rcontext::end_partial_result_set flag. */
676  thd->sp_runtime_ctx->end_partial_result_set= FALSE;
677 
678  } while (!err_status && !thd->killed && !thd->is_fatal_error);
679 
680 #if defined(ENABLED_PROFILING)
681  thd->profiling.finish_current_query();
682  thd->profiling.start_new_query("tail end of routine");
683 #endif
684 
685  /* Restore query context. */
686 
687  m_creation_ctx->restore_env(thd, saved_creation_ctx);
688 
689  /* Restore arena. */
690 
691  thd->restore_active_arena(&execute_arena, &backup_arena);
692 
693  thd->sp_runtime_ctx->pop_all_cursors(); // To avoid memory leaks after an error
694 
695  /* Restore all saved */
696  old_packet.swap(thd->packet);
697  DBUG_ASSERT(thd->change_list.is_empty());
698  old_change_list.move_elements_to(&thd->change_list);
699  thd->lex= old_lex;
700  thd->set_query_id(old_query_id);
701  DBUG_ASSERT(!thd->derived_tables);
702  thd->derived_tables= old_derived_tables;
703  thd->variables.sql_mode= save_sql_mode;
704  thd->abort_on_warning= save_abort_on_warning;
705  thd->pop_reprepare_observer();
706 
707  thd->stmt_arena= old_arena;
708  state= STMT_EXECUTED;
709 
710  /*
711  Restore the caller's original warning information area:
712  - warnings generated during trigger execution should not be
713  propagated to the caller on success;
714  - if there was an exception during execution, warning info should be
715  propagated to the caller in any case.
716  */
717  da->pop_warning_info();
718 
719  if (err_status || merge_da_on_success)
720  {
721  /*
722  If a routine body is empty or if a routine did not generate any warnings,
723  do not duplicate our own contents by appending the contents of the called
724  routine. We know that the called routine did not change its warning info.
725 
726  On the other hand, if the routine body is not empty and some statement in
727  the routine generates a warning or uses tables, warning info is guaranteed
728  to have changed. In this case we know that the routine warning info
729  contains only new warnings, and thus we perform a copy.
730  */
731  if (da->warning_info_changed(&sp_wi))
732  {
733  /*
734  If the invocation of the routine was a standalone statement,
735  rather than a sub-statement, in other words, if it's a CALL
736  of a procedure, rather than invocation of a function or a
737  trigger, we need to clear the current contents of the caller's
738  warning info.
739 
740  This is per MySQL rules: if a statement generates a warning,
741  warnings from the previous statement are flushed. Normally
742  it's done in push_warning(). However, here we don't use
743  push_warning() to avoid invocation of condition handlers or
744  escalation of warnings to errors.
745  */
746  da->opt_clear_warning_info(thd->query_id);
747  da->copy_sql_conditions_from_wi(thd, &sp_wi);
748  da->remove_marked_sql_conditions();
749  }
750  }
751 
752  done:
753  DBUG_PRINT("info", ("err_status: %d killed: %d is_slave_error: %d report_error: %d",
754  err_status, thd->killed, thd->is_slave_error,
755  thd->is_error()));
756 
757  if (thd->killed)
758  err_status= TRUE;
759  /*
760  If the DB has changed, the pointer has changed too, but the
761  original thd->db will then have been freed
762  */
763  if (cur_db_changed && thd->killed != THD::KILL_CONNECTION)
764  {
765  /*
766  Force switching back to the saved current database, because it may be
767  NULL. In this case, mysql_change_db() would generate an error.
768  */
769 
770  err_status|= mysql_change_db(thd, &saved_cur_db_name, TRUE);
771  }
772  m_flags&= ~IS_INVOKED;
773  DBUG_PRINT("info",
774  ("first free for 0x%lx --: 0x%lx->0x%lx, level: %lu, flags %x",
775  (ulong) m_first_instance,
776  (ulong) m_first_instance->m_first_free_instance,
777  (ulong) this, m_recursion_level, m_flags));
778  /*
779  Check that we have one of following:
780 
781  1) there are not free instances which means that this instance is last
782  in the list of instances (pointer to the last instance point on it and
783  there are not other instances after this one in the list)
784 
785  2) There are some free instances which mean that first free instance
786  should go just after this one and recursion level of that free instance
787  should be on 1 more then recursion level of this instance.
788  */
789  DBUG_ASSERT((m_first_instance->m_first_free_instance == 0 &&
790  this == m_first_instance->m_last_cached_sp &&
791  m_next_cached_sp == 0) ||
792  (m_first_instance->m_first_free_instance != 0 &&
793  m_first_instance->m_first_free_instance == m_next_cached_sp &&
794  m_first_instance->m_first_free_instance->m_recursion_level ==
795  m_recursion_level + 1));
796  m_first_instance->m_first_free_instance= this;
797 
798  return err_status;
799 }
800 
801 
803  const LEX_STRING *db_name,
804  const LEX_STRING *table_name,
805  GRANT_INFO *grant_info)
806 {
807  sp_rcontext *parent_sp_runtime_ctx = thd->sp_runtime_ctx;
808  bool err_status= FALSE;
809  MEM_ROOT call_mem_root;
810  Query_arena call_arena(&call_mem_root, Query_arena::STMT_INITIALIZED_FOR_SP);
811  Query_arena backup_arena;
812 
813  DBUG_ENTER("sp_head::execute_trigger");
814  DBUG_PRINT("info", ("trigger %s", m_name.str));
815 
816 #ifndef NO_EMBEDDED_ACCESS_CHECKS
817  Security_context *save_ctx= NULL;
818 
819 
820  if (m_chistics->suid != SP_IS_NOT_SUID &&
821  m_security_ctx.change_security_context(thd,
822  &m_definer_user,
823  &m_definer_host,
824  &m_db,
825  &save_ctx))
826  DBUG_RETURN(true);
827 
828  /*
829  Fetch information about table-level privileges for subject table into
830  GRANT_INFO instance. The access check itself will happen in
831  Item_trigger_field, where this information will be used along with
832  information about column-level privileges.
833  */
834 
835  fill_effective_table_privileges(thd,
836  grant_info,
837  db_name->str,
838  table_name->str);
839 
840  /* Check that the definer has TRIGGER privilege on the subject table. */
841 
842  if (!(grant_info->privilege & TRIGGER_ACL))
843  {
844  char priv_desc[128];
845  get_privilege_desc(priv_desc, sizeof(priv_desc), TRIGGER_ACL);
846 
847  my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0), priv_desc,
848  thd->security_ctx->priv_user, thd->security_ctx->host_or_ip,
849  table_name->str);
850 
851  m_security_ctx.restore_security_context(thd, save_ctx);
852  DBUG_RETURN(true);
853  }
854  /*
855  Optimizer trace note: we needn't explicitly test here that the connected
856  user has TRIGGER privilege: assume he doesn't have it; two possibilities:
857  - connected user == definer: then we threw an error just above;
858  - connected user != definer: then in sp_head::execute(), when checking the
859  security context we will disable tracing.
860  */
861 #endif // NO_EMBEDDED_ACCESS_CHECKS
862 
863  /*
864  Prepare arena and memroot for objects which lifetime is whole
865  duration of trigger call (sp_rcontext, it's tables and items,
866  sp_cursor and Item_cache holders for case expressions). We can't
867  use caller's arena/memroot for those objects because in this case
868  some fixed amount of memory will be consumed for each trigger
869  invocation and so statements which involve lot of them will hog
870  memory.
871 
872  TODO: we should create sp_rcontext once per command and reuse it
873  on subsequent executions of a trigger.
874  */
875  init_sql_alloc(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0);
876  thd->set_n_backup_active_arena(&call_arena, &backup_arena);
877 
878  sp_rcontext *trigger_runtime_ctx=
879  sp_rcontext::create(thd, m_root_parsing_ctx, NULL);
880 
881  if (!trigger_runtime_ctx)
882  {
883  err_status= TRUE;
884  goto err_with_cleanup;
885  }
886 
887  trigger_runtime_ctx->sp= this;
888  thd->sp_runtime_ctx= trigger_runtime_ctx;
889 
890  err_status= execute(thd, FALSE);
891 
892 err_with_cleanup:
893  thd->restore_active_arena(&call_arena, &backup_arena);
894 
895 #ifndef NO_EMBEDDED_ACCESS_CHECKS
896  m_security_ctx.restore_security_context(thd, save_ctx);
897 #endif // NO_EMBEDDED_ACCESS_CHECKS
898 
899  delete trigger_runtime_ctx;
900  call_arena.free_items();
901  free_root(&call_mem_root, MYF(0));
902  thd->sp_runtime_ctx= parent_sp_runtime_ctx;
903 
904  if (thd->killed)
905  thd->send_kill_message();
906 
907  DBUG_RETURN(err_status);
908 }
909 
910 
911 bool sp_head::execute_function(THD *thd, Item **argp, uint argcount,
912  Field *return_value_fld)
913 {
914  ulonglong binlog_save_options;
915  bool need_binlog_call= FALSE;
916  uint arg_no;
917  sp_rcontext *parent_sp_runtime_ctx = thd->sp_runtime_ctx;
918  char buf[STRING_BUFFER_USUAL_SIZE];
919  String binlog_buf(buf, sizeof(buf), &my_charset_bin);
920  bool err_status= FALSE;
921  MEM_ROOT call_mem_root;
922  Query_arena call_arena(&call_mem_root, Query_arena::STMT_INITIALIZED_FOR_SP);
923  Query_arena backup_arena;
924 
925  DBUG_ENTER("sp_head::execute_function");
926  DBUG_PRINT("info", ("function %s", m_name.str));
927 
928  LINT_INIT(binlog_save_options);
929  // Resetting THD::where to its default value
930  thd->where= THD::DEFAULT_WHERE;
931  /*
932  Check that the function is called with all specified arguments.
933 
934  If it is not, use my_error() to report an error, or it will not terminate
935  the invoking query properly.
936  */
937  if (argcount != m_root_parsing_ctx->context_var_count())
938  {
939  /*
940  Need to use my_error here, or it will not terminate the
941  invoking query properly.
942  */
943  my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0),
944  "FUNCTION", m_qname.str,
945  m_root_parsing_ctx->context_var_count(), argcount);
946  DBUG_RETURN(true);
947  }
948  /*
949  Prepare arena and memroot for objects which lifetime is whole
950  duration of function call (sp_rcontext, it's tables and items,
951  sp_cursor and Item_cache holders for case expressions).
952  We can't use caller's arena/memroot for those objects because
953  in this case some fixed amount of memory will be consumed for
954  each function/trigger invocation and so statements which involve
955  lot of them will hog memory.
956  TODO: we should create sp_rcontext once per command and reuse
957  it on subsequent executions of a function/trigger.
958  */
959  init_sql_alloc(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0);
960  thd->set_n_backup_active_arena(&call_arena, &backup_arena);
961 
962  sp_rcontext *func_runtime_ctx= sp_rcontext::create(thd, m_root_parsing_ctx,
963  return_value_fld);
964 
965  if (!func_runtime_ctx)
966  {
967  thd->restore_active_arena(&call_arena, &backup_arena);
968  err_status= TRUE;
969  goto err_with_cleanup;
970  }
971 
972  func_runtime_ctx->sp= this;
973 
974  /*
975  We have to switch temporarily back to callers arena/memroot.
976  Function arguments belong to the caller and so the may reference
977  memory which they will allocate during calculation long after
978  this function call will be finished (e.g. in Item::cleanup()).
979  */
980  thd->restore_active_arena(&call_arena, &backup_arena);
981 
982  /*
983  Pass arguments.
984 
985  Note, THD::sp_runtime_ctx must not be switched before the arguments are
986  passed. Values are taken from the caller's runtime context and set to the
987  runtime context of this function.
988  */
989  for (arg_no= 0; arg_no < argcount; arg_no++)
990  {
991  /* Arguments must be fixed in Item_func_sp::fix_fields */
992  DBUG_ASSERT(argp[arg_no]->fixed);
993 
994  err_status= func_runtime_ctx->set_variable(thd, arg_no, &(argp[arg_no]));
995 
996  if (err_status)
997  goto err_with_cleanup;
998  }
999 
1000  /*
1001  If row-based binlogging, we don't need to binlog the function's call, let
1002  each substatement be binlogged its way.
1003  */
1004  need_binlog_call= mysql_bin_log.is_open() &&
1005  (thd->variables.option_bits & OPTION_BIN_LOG) &&
1006  !thd->is_current_stmt_binlog_format_row();
1007 
1008  /*
1009  Remember the original arguments for unrolled replication of functions
1010  before they are changed by execution.
1011 
1012  Note, THD::sp_runtime_ctx must not be switched before the arguments are
1013  logged. Values are taken from the caller's runtime context.
1014  */
1015  if (need_binlog_call)
1016  {
1017  binlog_buf.length(0);
1018  binlog_buf.append(STRING_WITH_LEN("SELECT "));
1019  append_identifier(thd, &binlog_buf, m_db.str, m_db.length);
1020  binlog_buf.append('.');
1021  append_identifier(thd, &binlog_buf, m_name.str, m_name.length);
1022  binlog_buf.append('(');
1023  for (arg_no= 0; arg_no < argcount; arg_no++)
1024  {
1025  String str_value_holder;
1026  String *str_value;
1027 
1028  if (arg_no)
1029  binlog_buf.append(',');
1030 
1031  str_value= sp_get_item_value(thd, func_runtime_ctx->get_item(arg_no),
1032  &str_value_holder);
1033 
1034  if (str_value)
1035  binlog_buf.append(*str_value);
1036  else
1037  binlog_buf.append(STRING_WITH_LEN("NULL"));
1038  }
1039  binlog_buf.append(')');
1040  }
1041 
1042  thd->sp_runtime_ctx= func_runtime_ctx;
1043 
1044 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1045  Security_context *save_security_ctx;
1046  if (set_security_ctx(thd, &save_security_ctx))
1047  {
1048  err_status= TRUE;
1049  goto err_with_cleanup;
1050  }
1051 #endif
1052 
1053  if (need_binlog_call)
1054  {
1055  query_id_t q;
1056  reset_dynamic(&thd->user_var_events);
1057  /*
1058  In case of artificially constructed events for function calls
1059  we have separate union for each such event and hence can't use
1060  query_id of real calling statement as the start of all these
1061  unions (this will break logic of replication of user-defined
1062  variables). So we use artificial value which is guaranteed to
1063  be greater than all query_id's of all statements belonging
1064  to previous events/unions.
1065  Possible alternative to this is logging of all function invocations
1066  as one select and not resetting THD::user_var_events before
1067  each invocation.
1068  */
1069  mysql_mutex_lock(&LOCK_thread_count);
1070  q= global_query_id;
1071  mysql_mutex_unlock(&LOCK_thread_count);
1072  mysql_bin_log.start_union_events(thd, q + 1);
1073  binlog_save_options= thd->variables.option_bits;
1074  thd->variables.option_bits&= ~OPTION_BIN_LOG;
1075  }
1076 
1077  opt_trace_disable_if_no_stored_proc_func_access(thd, this);
1078 
1079  /*
1080  Switch to call arena/mem_root so objects like sp_cursor or
1081  Item_cache holders for case expressions can be allocated on it.
1082 
1083  TODO: In future we should associate call arena/mem_root with
1084  sp_rcontext and allocate all these objects (and sp_rcontext
1085  itself) on it directly rather than juggle with arenas.
1086  */
1087  thd->set_n_backup_active_arena(&call_arena, &backup_arena);
1088 
1089  err_status= execute(thd, TRUE);
1090 
1091  thd->restore_active_arena(&call_arena, &backup_arena);
1092 
1093  if (need_binlog_call)
1094  {
1095  mysql_bin_log.stop_union_events(thd);
1096  thd->variables.option_bits= binlog_save_options;
1097  if (thd->binlog_evt_union.unioned_events)
1098  {
1099  int errcode = query_error_code(thd, thd->killed == THD::NOT_KILLED);
1100  Query_log_event qinfo(thd, binlog_buf.ptr(), binlog_buf.length(),
1101  thd->binlog_evt_union.unioned_events_trans, FALSE, FALSE, errcode);
1102  if (mysql_bin_log.write_event(&qinfo) &&
1103  thd->binlog_evt_union.unioned_events_trans)
1104  {
1105  push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
1106  "Invoked ROUTINE modified a transactional table but MySQL "
1107  "failed to reflect this change in the binary log");
1108  err_status= TRUE;
1109  }
1110  reset_dynamic(&thd->user_var_events);
1111  /* Forget those values, in case more function calls are binlogged: */
1112  thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
1113  thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
1114  }
1115  }
1116 
1117  if (!err_status)
1118  {
1119  /* We need result only in function but not in trigger */
1120 
1121  if (!thd->sp_runtime_ctx->is_return_value_set())
1122  {
1123  my_error(ER_SP_NORETURNEND, MYF(0), m_name.str);
1124  err_status= TRUE;
1125  }
1126  }
1127 
1128 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1129  m_security_ctx.restore_security_context(thd, save_security_ctx);
1130 #endif
1131 
1132 err_with_cleanup:
1133  delete func_runtime_ctx;
1134  call_arena.free_items();
1135  free_root(&call_mem_root, MYF(0));
1136  thd->sp_runtime_ctx= parent_sp_runtime_ctx;
1137 
1138  /*
1139  If not inside a procedure and a function printing warning
1140  messages.
1141  */
1142  if (need_binlog_call &&
1143  thd->sp_runtime_ctx == NULL && !thd->binlog_evt_union.do_union)
1144  thd->issue_unsafe_warnings();
1145 
1146  DBUG_RETURN(err_status);
1147 }
1148 
1149 
1151 {
1152  bool err_status= FALSE;
1153  uint params = m_root_parsing_ctx->context_var_count();
1154  /* Query start time may be reset in a multi-stmt SP; keep this for later. */
1155  ulonglong utime_before_sp_exec= thd->utime_after_lock;
1156  sp_rcontext *parent_sp_runtime_ctx= thd->sp_runtime_ctx;
1157  sp_rcontext *sp_runtime_ctx_saved= thd->sp_runtime_ctx;
1158  bool save_enable_slow_log= false;
1159  bool save_log_general= false;
1160 
1161  DBUG_ENTER("sp_head::execute_procedure");
1162  DBUG_PRINT("info", ("procedure %s", m_name.str));
1163 
1164  if (args->elements != params)
1165  {
1166  my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0), "PROCEDURE",
1167  m_qname.str, params, args->elements);
1168  DBUG_RETURN(true);
1169  }
1170 
1171  if (!parent_sp_runtime_ctx)
1172  {
1173  // Create a temporary old context. We need it to pass OUT-parameter values.
1174  parent_sp_runtime_ctx= sp_rcontext::create(thd, m_root_parsing_ctx, NULL);
1175 
1176  if (!parent_sp_runtime_ctx)
1177  DBUG_RETURN(true);
1178 
1179  parent_sp_runtime_ctx->sp= 0;
1180  thd->sp_runtime_ctx= parent_sp_runtime_ctx;
1181 
1182  /* set callers_arena to thd, for upper-level function to work */
1183  thd->sp_runtime_ctx->callers_arena= thd;
1184  }
1185 
1186  sp_rcontext *proc_runtime_ctx=
1187  sp_rcontext::create(thd, m_root_parsing_ctx, NULL);
1188 
1189  if (!proc_runtime_ctx)
1190  {
1191  thd->sp_runtime_ctx= sp_runtime_ctx_saved;
1192 
1193  if (!sp_runtime_ctx_saved)
1194  delete parent_sp_runtime_ctx;
1195 
1196  DBUG_RETURN(true);
1197  }
1198 
1199  proc_runtime_ctx->sp= this;
1200 
1201  if (params > 0)
1202  {
1203  List_iterator<Item> it_args(*args);
1204 
1205  DBUG_PRINT("info",(" %.*s: eval args", (int) m_name.length, m_name.str));
1206 
1207  for (uint i= 0 ; i < params ; i++)
1208  {
1209  Item *arg_item= it_args++;
1210 
1211  if (!arg_item)
1212  break;
1213 
1214  sp_variable *spvar= m_root_parsing_ctx->find_variable(i);
1215 
1216  if (!spvar)
1217  continue;
1218 
1219  if (spvar->mode != sp_variable::MODE_IN)
1220  {
1222  arg_item->get_settable_routine_parameter();
1223 
1224  if (!srp)
1225  {
1226  my_error(ER_SP_NOT_VAR_ARG, MYF(0), i+1, m_qname.str);
1227  err_status= TRUE;
1228  break;
1229  }
1230 
1231  srp->set_required_privilege(spvar->mode == sp_variable::MODE_INOUT);
1232  }
1233 
1234  if (spvar->mode == sp_variable::MODE_OUT)
1235  {
1236  Item_null *null_item= new Item_null();
1237 
1238  if (!null_item ||
1239  proc_runtime_ctx->set_variable(thd, i, (Item **)&null_item))
1240  {
1241  err_status= TRUE;
1242  break;
1243  }
1244  }
1245  else
1246  {
1247  if (proc_runtime_ctx->set_variable(thd, i, it_args.ref()))
1248  {
1249  err_status= TRUE;
1250  break;
1251  }
1252  }
1253  }
1254 
1255  /*
1256  Okay, got values for all arguments. Close tables that might be used by
1257  arguments evaluation. If arguments evaluation required prelocking mode,
1258  we'll leave it here.
1259  */
1260  thd->lex->unit.cleanup();
1261 
1262  if (!thd->in_sub_stmt)
1263  {
1264  thd->get_stmt_da()->set_overwrite_status(true);
1265  thd->is_error() ? trans_rollback_stmt(thd) : trans_commit_stmt(thd);
1266  thd->get_stmt_da()->set_overwrite_status(false);
1267  }
1268 
1269  thd_proc_info(thd, "closing tables");
1270  close_thread_tables(thd);
1271  thd_proc_info(thd, 0);
1272 
1273  if (! thd->in_sub_stmt)
1274  {
1275  if (thd->transaction_rollback_request)
1276  {
1277  trans_rollback_implicit(thd);
1278  thd->mdl_context.release_transactional_locks();
1279  }
1280  else if (! thd->in_multi_stmt_transaction_mode())
1281  thd->mdl_context.release_transactional_locks();
1282  else
1283  thd->mdl_context.release_statement_locks();
1284  }
1285 
1286  thd->rollback_item_tree_changes();
1287 
1288  DBUG_PRINT("info",(" %.*s: eval args done", (int) m_name.length,
1289  m_name.str));
1290  }
1291  if (!(m_flags & LOG_SLOW_STATEMENTS) && thd->enable_slow_log)
1292  {
1293  DBUG_PRINT("info", ("Disabling slow log for the execution"));
1294  save_enable_slow_log= true;
1295  thd->enable_slow_log= FALSE;
1296  }
1297  if (!(m_flags & LOG_GENERAL_LOG) && !(thd->variables.option_bits & OPTION_LOG_OFF))
1298  {
1299  DBUG_PRINT("info", ("Disabling general log for the execution"));
1300  save_log_general= true;
1301  /* disable this bit */
1302  thd->variables.option_bits |= OPTION_LOG_OFF;
1303  }
1304  thd->sp_runtime_ctx= proc_runtime_ctx;
1305 
1306 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1307  Security_context *save_security_ctx= 0;
1308  if (!err_status)
1309  err_status= set_security_ctx(thd, &save_security_ctx);
1310 #endif
1311 
1312  opt_trace_disable_if_no_stored_proc_func_access(thd, this);
1313 
1314  if (!err_status)
1315  err_status= execute(thd, TRUE);
1316 
1317  if (save_log_general)
1318  thd->variables.option_bits &= ~OPTION_LOG_OFF;
1319  if (save_enable_slow_log)
1320  thd->enable_slow_log= true;
1321  /*
1322  In the case when we weren't able to employ reuse mechanism for
1323  OUT/INOUT parameters, we should reallocate memory. This
1324  allocation should be done on the arena which will live through
1325  all execution of calling routine.
1326  */
1327  thd->sp_runtime_ctx->callers_arena= parent_sp_runtime_ctx->callers_arena;
1328 
1329  if (!err_status && params > 0)
1330  {
1331  List_iterator<Item> it_args(*args);
1332 
1333  /*
1334  Copy back all OUT or INOUT values to the previous frame, or
1335  set global user variables
1336  */
1337  for (uint i= 0 ; i < params ; i++)
1338  {
1339  Item *arg_item= it_args++;
1340 
1341  if (!arg_item)
1342  break;
1343 
1344  sp_variable *spvar= m_root_parsing_ctx->find_variable(i);
1345 
1346  if (spvar->mode == sp_variable::MODE_IN)
1347  continue;
1348 
1350  arg_item->get_settable_routine_parameter();
1351 
1352  DBUG_ASSERT(srp);
1353 
1354  if (srp->set_value(thd, parent_sp_runtime_ctx, proc_runtime_ctx->get_item_addr(i)))
1355  {
1356  err_status= TRUE;
1357  break;
1358  }
1359 
1360  Send_field *out_param_info= new (thd->mem_root) Send_field();
1361  proc_runtime_ctx->get_item(i)->make_field(out_param_info);
1362  out_param_info->db_name= m_db.str;
1363  out_param_info->table_name= m_name.str;
1364  out_param_info->org_table_name= m_name.str;
1365  out_param_info->col_name= spvar->name.str;
1366  out_param_info->org_col_name= spvar->name.str;
1367 
1368  srp->set_out_param_info(out_param_info);
1369  }
1370  }
1371 
1372 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1373  if (save_security_ctx)
1374  m_security_ctx.restore_security_context(thd, save_security_ctx);
1375 #endif
1376 
1377  if (!sp_runtime_ctx_saved)
1378  delete parent_sp_runtime_ctx;
1379 
1380  delete proc_runtime_ctx;
1381  thd->sp_runtime_ctx= sp_runtime_ctx_saved;
1382  thd->utime_after_lock= utime_before_sp_exec;
1383 
1384  /*
1385  If not insided a procedure and a function printing warning
1386  messages.
1387  */
1388  bool need_binlog_call= mysql_bin_log.is_open() &&
1389  (thd->variables.option_bits & OPTION_BIN_LOG) &&
1390  !thd->is_current_stmt_binlog_format_row();
1391  if (need_binlog_call && thd->sp_runtime_ctx == NULL &&
1392  !thd->binlog_evt_union.do_union)
1393  thd->issue_unsafe_warnings();
1394 
1395  DBUG_RETURN(err_status);
1396 }
1397 
1398 
1399 bool sp_head::reset_lex(THD *thd)
1400 {
1401  LEX *oldlex= thd->lex;
1402 
1403  LEX *sublex= new (thd->mem_root)st_lex_local;
1404 
1405  if (!sublex)
1406  return true;
1407 
1408  thd->lex= sublex;
1409  m_parser_data.push_lex(oldlex);
1410 
1411  /* Reset most stuff. */
1412  lex_start(thd);
1413 
1414  /* And keep the SP stuff too */
1415  sublex->sphead= oldlex->sphead;
1416  sublex->set_sp_current_parsing_ctx(oldlex->get_sp_current_parsing_ctx());
1417  sublex->sp_lex_in_use= FALSE;
1418 
1419  /* Reset type info. */
1420 
1421  sublex->charset= NULL;
1422  sublex->length= NULL;
1423  sublex->dec= NULL;
1424  sublex->interval_list.empty();
1425  sublex->type= 0;
1426 
1427  /* Reset part of parser state which needs this. */
1428  thd->m_parser_state->m_yacc.reset_before_substatement();
1429 
1430  return false;
1431 }
1432 
1433 
1434 bool sp_head::restore_lex(THD *thd)
1435 {
1436  LEX *sublex= thd->lex;
1437 
1438  sublex->set_trg_event_type_for_tables();
1439 
1440  LEX *oldlex= (LEX *) m_parser_data.pop_lex();
1441 
1442  if (!oldlex)
1443  return false; // Nothing to restore
1444 
1445  /* If this substatement is unsafe, the entire routine is too. */
1446  DBUG_PRINT("info", ("lex->get_stmt_unsafe_flags: 0x%x",
1447  thd->lex->get_stmt_unsafe_flags()));
1448  unsafe_flags|= sublex->get_stmt_unsafe_flags();
1449 
1450  /*
1451  Add routines which are used by statement to respective set for
1452  this routine.
1453  */
1454  if (sp_update_sp_used_routines(&m_sroutines, &sublex->sroutines))
1455  return true;
1456 
1457  /* If this substatement is a update query, then mark MODIFIES_DATA */
1458  if (is_update_query(sublex->sql_command))
1460 
1461  /*
1462  Merge tables used by this statement (but not by its functions or
1463  procedures) to multiset of tables used by this routine.
1464  */
1465  merge_table_list(thd, sublex->query_tables, sublex);
1466 
1467  if (!sublex->sp_lex_in_use)
1468  {
1469  sublex->sphead= NULL;
1470  lex_end(sublex);
1471  delete sublex;
1472  }
1473 
1474  thd->lex= oldlex;
1475  return false;
1476 }
1477 
1478 void sp_head::set_info(longlong created,
1479  longlong modified,
1480  st_sp_chistics *chistics,
1481  sql_mode_t sql_mode)
1482 {
1483  m_created= created;
1484  m_modified= modified;
1485  m_chistics= (st_sp_chistics *) memdup_root(mem_root, (char*) chistics,
1486  sizeof(*chistics));
1487  if (m_chistics->comment.length == 0)
1488  m_chistics->comment.str= 0;
1489  else
1490  m_chistics->comment.str= strmake_root(mem_root,
1491  m_chistics->comment.str,
1492  m_chistics->comment.length);
1493  m_sql_mode= sql_mode;
1494 }
1495 
1496 
1497 void sp_head::set_definer(const char *definer, uint definerlen)
1498 {
1499  char user_name_holder[USERNAME_LENGTH + 1];
1500  LEX_STRING user_name= { user_name_holder, USERNAME_LENGTH };
1501 
1502  char host_name_holder[HOSTNAME_LENGTH + 1];
1503  LEX_STRING host_name= { host_name_holder, HOSTNAME_LENGTH };
1504 
1505  parse_user(definer, definerlen, user_name.str, &user_name.length,
1506  host_name.str, &host_name.length);
1507 
1508  set_definer(&user_name, &host_name);
1509 }
1510 
1511 
1512 void sp_head::set_definer(const LEX_STRING *user_name,
1513  const LEX_STRING *host_name)
1514 {
1515  m_definer_user.str= strmake_root(mem_root, user_name->str, user_name->length);
1516  m_definer_user.length= user_name->length;
1517 
1518  m_definer_host.str= strmake_root(mem_root, host_name->str, host_name->length);
1519  m_definer_host.length= host_name->length;
1520 }
1521 
1522 
1523 bool sp_head::show_create_routine(THD *thd, enum_sp_type type)
1524 {
1525  const char *col1_caption= (type == SP_TYPE_PROCEDURE) ?
1526  "Procedure" : "Function";
1527 
1528  const char *col3_caption= (type == SP_TYPE_PROCEDURE) ?
1529  "Create Procedure" : "Create Function";
1530 
1531  bool err_status;
1532 
1533  Protocol *protocol= thd->protocol;
1534  List<Item> fields;
1535 
1536  LEX_STRING sql_mode;
1537 
1538  bool full_access;
1539 
1540  DBUG_ASSERT(type == SP_TYPE_PROCEDURE || type == SP_TYPE_FUNCTION);
1541 
1542  if (check_show_access(thd, &full_access))
1543  return true;
1544 
1545  sql_mode_string_representation(thd, m_sql_mode, &sql_mode);
1546 
1547  /* Send header. */
1548 
1549  fields.push_back(new Item_empty_string(col1_caption, NAME_CHAR_LEN));
1550  fields.push_back(new Item_empty_string("sql_mode", sql_mode.length));
1551 
1552  {
1553  /*
1554  NOTE: SQL statement field must be not less than 1024 in order not to
1555  confuse old clients.
1556  */
1557 
1558  Item_empty_string *stmt_fld=
1559  new Item_empty_string(col3_caption,
1560  std::max<size_t>(m_defstr.length, 1024U));
1561 
1562  stmt_fld->maybe_null= TRUE;
1563 
1564  fields.push_back(stmt_fld);
1565  }
1566 
1567  fields.push_back(new Item_empty_string("character_set_client",
1568  MY_CS_NAME_SIZE));
1569 
1570  fields.push_back(new Item_empty_string("collation_connection",
1571  MY_CS_NAME_SIZE));
1572 
1573  fields.push_back(new Item_empty_string("Database Collation",
1574  MY_CS_NAME_SIZE));
1575 
1576  if (protocol->send_result_set_metadata(&fields,
1577  Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
1578  {
1579  return true;
1580  }
1581 
1582  /* Send data. */
1583 
1584  protocol->prepare_for_resend();
1585 
1586  protocol->store(m_name.str, m_name.length, system_charset_info);
1587  protocol->store(sql_mode.str, sql_mode.length, system_charset_info);
1588 
1589  if (full_access)
1590  protocol->store(m_defstr.str, m_defstr.length,
1591  m_creation_ctx->get_client_cs());
1592  else
1593  protocol->store_null();
1594 
1595 
1596  protocol->store(m_creation_ctx->get_client_cs()->csname, system_charset_info);
1597  protocol->store(m_creation_ctx->get_connection_cl()->name, system_charset_info);
1598  protocol->store(m_creation_ctx->get_db_cl()->name, system_charset_info);
1599 
1600  err_status= protocol->write();
1601 
1602  if (!err_status)
1603  my_eof(thd);
1604 
1605  return err_status;
1606 }
1607 
1608 
1609 bool sp_head::add_instr(THD *thd, sp_instr *instr)
1610 {
1611  m_parser_data.process_new_sp_instr(thd, instr);
1612 
1613  /*
1614  Memory root of every instruction is designated for permanent
1615  transformations (optimizations) made on the parsed tree during
1616  the first execution. It points to the memory root of the
1617  entire stored procedure, as their life span is equal.
1618  */
1619  instr->mem_root= get_persistent_mem_root();
1620 
1621  return m_instructions.append(instr);
1622 }
1623 
1624 
1626 {
1628  sp_instr *i;
1629  uint src, dst;
1630 
1631  opt_mark();
1632 
1633  bp.empty();
1634  src= dst= 0;
1635  while ((i= get_instr(src)))
1636  {
1637  if (!i->opt_is_marked())
1638  {
1639  delete i;
1640  src+= 1;
1641  }
1642  else
1643  {
1644  if (src != dst)
1645  {
1646  m_instructions.set(dst, i);
1647 
1648  /* Move the instruction and update prev. jumps */
1649  sp_branch_instr *ibp;
1651 
1652  while ((ibp= li++))
1653  ibp->set_destination(src, dst);
1654  }
1655  i->opt_move(dst, &bp);
1656  src+= 1;
1657  dst+= 1;
1658  }
1659  }
1660 
1661  m_instructions.elements(dst);
1662  bp.empty();
1663 }
1664 
1665 
1667 {
1668  sp_instr *i= get_instr(ip);
1669 
1670  if (i && !i->opt_is_marked())
1671  leads->push_front(i);
1672 }
1673 
1674 
1675 void sp_head::opt_mark()
1676 {
1677  uint ip;
1678  sp_instr *i;
1679  List<sp_instr> leads;
1680 
1681  /*
1682  Forward flow analysis algorithm in the instruction graph:
1683  - first, add the entry point in the graph (the first instruction) to the
1684  'leads' list of paths to explore.
1685  - while there are still leads to explore:
1686  - pick one lead, and follow the path forward. Mark instruction reached.
1687  Stop only if the end of the routine is reached, or the path converge
1688  to code already explored (marked).
1689  - while following a path, collect in the 'leads' list any fork to
1690  another path (caused by conditional jumps instructions), so that these
1691  paths can be explored as well.
1692  */
1693 
1694  /* Add the entry point */
1695  i= get_instr(0);
1696  leads.push_front(i);
1697 
1698  /* For each path of code ... */
1699  while (leads.elements != 0)
1700  {
1701  i= leads.pop();
1702 
1703  /* Mark the entire path, collecting new leads. */
1704  while (i && !i->opt_is_marked())
1705  {
1706  ip= i->opt_mark(this, & leads);
1707  i= get_instr(ip);
1708  }
1709  }
1710 }
1711 
1712 
1713 #ifndef DBUG_OFF
1715 {
1716  Protocol *protocol= thd->protocol;
1717  char buff[2048];
1718  String buffer(buff, sizeof(buff), system_charset_info);
1719  List<Item> field_list;
1720  sp_instr *i;
1721  bool full_access;
1722  bool res= false;
1723  uint ip;
1724 
1725  if (check_show_access(thd, &full_access) || !full_access)
1726  return true;
1727 
1728  field_list.push_back(new Item_uint(NAME_STRING("Pos"), 0, 9));
1729  // 1024 is for not to confuse old clients
1730  field_list.push_back(new Item_empty_string("Instruction",
1731  std::max(buffer.length(), 1024U)));
1732  if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS |
1733  Protocol::SEND_EOF))
1734  return true;
1735 
1736  for (ip= 0; (i = get_instr(ip)) ; ip++)
1737  {
1738  /*
1739  Consistency check. If these are different something went wrong
1740  during optimization.
1741  */
1742  if (ip != i->get_ip())
1743  {
1744  const char *format= "Instruction at position %u has m_ip=%u";
1745  char tmp[sizeof(format) + 2 * sizeof(uint) + 1];
1746 
1747  sprintf(tmp, format, ip, i->get_ip());
1748  /*
1749  Since this is for debugging purposes only, we don't bother to
1750  introduce a special error code for it.
1751  */
1752  push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, tmp);
1753  }
1754  protocol->prepare_for_resend();
1755  protocol->store((longlong)ip);
1756 
1757  buffer.set("", 0, system_charset_info);
1758  i->print(&buffer);
1759  protocol->store(buffer.ptr(), buffer.length(), system_charset_info);
1760  if ((res= protocol->write()))
1761  break;
1762  }
1763 
1764  if (!res)
1765  my_eof(thd);
1766 
1767  return res;
1768 }
1769 #endif // ifndef DBUG_OFF
1770 
1771 
1772 bool sp_head::merge_table_list(THD *thd,
1773  TABLE_LIST *table,
1774  LEX *lex_for_tmp_check)
1775 {
1776  if (lex_for_tmp_check->sql_command == SQLCOM_DROP_TABLE &&
1777  lex_for_tmp_check->drop_temporary)
1778  return true;
1779 
1780  for (uint i= 0 ; i < m_sptabs.records ; i++)
1781  {
1782  SP_TABLE *tab= (SP_TABLE*) my_hash_element(&m_sptabs, i);
1783  tab->query_lock_count= 0;
1784  }
1785 
1786  for (; table ; table= table->next_global)
1787  if (!table->derived && !table->schema_table)
1788  {
1789  /*
1790  Structure of key for the multi-set is "db\0table\0alias\0".
1791  Since "alias" part can have arbitrary length we use String
1792  object to construct the key. By default String will use
1793  buffer allocated on stack with NAME_LEN bytes reserved for
1794  alias, since in most cases it is going to be smaller than
1795  NAME_LEN bytes.
1796  */
1797  char tname_buff[(NAME_LEN + 1) * 3];
1798  String tname(tname_buff, sizeof(tname_buff), &my_charset_bin);
1799  uint temp_table_key_length;
1800 
1801  tname.length(0);
1802  tname.append(table->db, table->db_length);
1803  tname.append('\0');
1804  tname.append(table->table_name, table->table_name_length);
1805  tname.append('\0');
1806  temp_table_key_length= tname.length();
1807  tname.append(table->alias);
1808  tname.append('\0');
1809 
1810  /*
1811  Upgrade the lock type because this table list will be used
1812  only in pre-locked mode, in which DELAYED inserts are always
1813  converted to normal inserts.
1814  */
1815  if (table->lock_type == TL_WRITE_DELAYED)
1816  table->lock_type= TL_WRITE;
1817 
1818  /*
1819  We ignore alias when we check if table was already marked as temporary
1820  (and therefore should not be prelocked). Otherwise we will erroneously
1821  treat table with same name but with different alias as non-temporary.
1822  */
1823 
1824  SP_TABLE *tab;
1825 
1826  if ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname.ptr(),
1827  tname.length())) ||
1828  ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname.ptr(),
1829  temp_table_key_length)) &&
1830  tab->temp))
1831  {
1832  if (tab->lock_type < table->lock_type)
1833  tab->lock_type= table->lock_type; // Use the table with the highest lock type
1834  tab->query_lock_count++;
1835  if (tab->query_lock_count > tab->lock_count)
1836  tab->lock_count++;
1837  tab->trg_event_map|= table->trg_event_map;
1838  }
1839  else
1840  {
1841  if (!(tab= (SP_TABLE *)thd->calloc(sizeof(SP_TABLE))))
1842  return false;
1843  if (lex_for_tmp_check->sql_command == SQLCOM_CREATE_TABLE &&
1844  lex_for_tmp_check->query_tables == table &&
1845  lex_for_tmp_check->create_info.options & HA_LEX_CREATE_TMP_TABLE)
1846  {
1847  tab->temp= true;
1848  tab->qname.length= temp_table_key_length;
1849  }
1850  else
1851  tab->qname.length= tname.length();
1852  tab->qname.str= (char*) thd->memdup(tname.ptr(), tab->qname.length);
1853  if (!tab->qname.str)
1854  return false;
1855  tab->table_name_length= table->table_name_length;
1856  tab->db_length= table->db_length;
1857  tab->lock_type= table->lock_type;
1858  tab->lock_count= tab->query_lock_count= 1;
1859  tab->trg_event_map= table->trg_event_map;
1860  if (my_hash_insert(&m_sptabs, (uchar *)tab))
1861  return false;
1862  }
1863  }
1864  return true;
1865 }
1866 
1867 
1869  TABLE_LIST ***query_tables_last_ptr,
1870  TABLE_LIST *belong_to_view)
1871 {
1872  bool result= false;
1873 
1874  /*
1875  Use persistent arena for table list allocation to be PS/SP friendly.
1876  Note that we also have to copy database/table names and alias to PS/SP
1877  memory since current instance of sp_head object can pass away before
1878  next execution of PS/SP for which tables are added to prelocking list.
1879  This will be fixed by introducing of proper invalidation mechanism
1880  once new TDC is ready.
1881  */
1882  Prepared_stmt_arena_holder ps_arena_holder(thd);
1883 
1884  for (uint i= 0; i < m_sptabs.records; i++)
1885  {
1886  char *tab_buff, *key_buff;
1887  SP_TABLE *stab= (SP_TABLE*) my_hash_element(&m_sptabs, i);
1888  if (stab->temp)
1889  continue;
1890 
1891  if (!(tab_buff= (char *)thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST)) *
1892  stab->lock_count)) ||
1893  !(key_buff= (char*)thd->memdup(stab->qname.str,
1894  stab->qname.length)))
1895  return false;
1896 
1897  for (uint j= 0; j < stab->lock_count; j++)
1898  {
1899  TABLE_LIST *table= (TABLE_LIST *)tab_buff;
1900 
1901  table->db= key_buff;
1902  table->db_length= stab->db_length;
1903  table->table_name= table->db + table->db_length + 1;
1904  table->table_name_length= stab->table_name_length;
1905  table->alias= table->table_name + table->table_name_length + 1;
1906  table->lock_type= stab->lock_type;
1907  table->cacheable_table= 1;
1908  table->prelocking_placeholder= 1;
1909  table->belong_to_view= belong_to_view;
1910  table->trg_event_map= stab->trg_event_map;
1911  /*
1912  Since we don't allow DDL on base tables in prelocked mode it
1913  is safe to infer the type of metadata lock from the type of
1914  table lock.
1915  */
1916  table->mdl_request.init(MDL_key::TABLE, table->db, table->table_name,
1917  table->lock_type >= TL_WRITE_ALLOW_WRITE ?
1918  MDL_SHARED_WRITE : MDL_SHARED_READ,
1919  MDL_TRANSACTION);
1920 
1921  /* Everyting else should be zeroed */
1922 
1923  **query_tables_last_ptr= table;
1924  table->prev_global= *query_tables_last_ptr;
1925  *query_tables_last_ptr= &table->next_global;
1926 
1927  tab_buff+= ALIGN_SIZE(sizeof(TABLE_LIST));
1928  result= true;
1929  }
1930  }
1931 
1932  return result;
1933 }
1934 
1935 
1936 bool sp_head::check_show_access(THD *thd, bool *full_access)
1937 {
1938  TABLE_LIST tables;
1939  memset(&tables, 0, sizeof(tables));
1940  tables.db= (char*) "mysql";
1941  tables.table_name= tables.alias= (char*) "proc";
1942 
1943  *full_access=
1944  ((!check_table_access(thd, SELECT_ACL, &tables, false, 1, true) &&
1945  (tables.grant.privilege & SELECT_ACL) != 0) ||
1946  (!strcmp(m_definer_user.str, thd->security_ctx->priv_user) &&
1947  !strcmp(m_definer_host.str, thd->security_ctx->priv_host)));
1948 
1949  return *full_access ?
1950  false :
1951  check_some_routine_access(thd, m_db.str, m_name.str,
1952  m_type == SP_TYPE_PROCEDURE);
1953 }
1954 
1955 
1956 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1957 bool sp_head::set_security_ctx(THD *thd, Security_context **save_ctx)
1958 {
1959  *save_ctx= NULL;
1960 
1961  if (m_chistics->suid != SP_IS_NOT_SUID &&
1962  m_security_ctx.change_security_context(thd,
1963  &m_definer_user, &m_definer_host,
1964  &m_db, save_ctx))
1965  {
1966  return true;
1967  }
1968 
1969  /*
1970  If we changed context to run as another user, we need to check the
1971  access right for the new context again as someone may have revoked
1972  the right to use the procedure from this user.
1973  */
1974 
1975  if (*save_ctx &&
1976  check_routine_access(thd, EXECUTE_ACL, m_db.str, m_name.str,
1977  m_type == SP_TYPE_PROCEDURE, false))
1978  {
1979  m_security_ctx.restore_security_context(thd, *save_ctx);
1980  *save_ctx= NULL;
1981  return true;
1982  }
1983 
1984  return false;
1985 }
1986 #endif // ! NO_EMBEDDED_ACCESS_CHECKS
1987 
1988 
1990 // sp_parser_data implementation.
1992 
1993 
1995 {
1996  m_saved_memroot= thd->mem_root;
1997  m_saved_free_list= thd->free_list;
1998 
1999  thd->mem_root= sp->get_persistent_mem_root();
2000  thd->free_list= NULL;
2001 }
2002 
2003 
2005  sp_label *label)
2006 {
2007  Backpatch_info *bp= (Backpatch_info *)sql_alloc(sizeof(Backpatch_info));
2008 
2009  if (!bp)
2010  return true;
2011 
2012  bp->label= label;
2013  bp->instr= i;
2014  return m_backpatch.push_front(bp);
2015 }
2016 
2017 
2019 {
2020  Backpatch_info *bp;
2021  List_iterator_fast<Backpatch_info> li(m_backpatch);
2022 
2023  while ((bp= li++))
2024  {
2025  if (bp->label == label)
2026  bp->instr->backpatch(dest);
2027  }
2028 }
2029 
2030 
2032 {
2033  i->set_cont_dest(m_cont_level);
2034  return m_cont_backpatch.push_front(i);
2035 }
2036 
2037 
2039 {
2041 
2042  while ((i= m_cont_backpatch.head()) && i->get_cont_dest() == m_cont_level)
2043  {
2044  i->set_cont_dest(dest);
2045  m_cont_backpatch.pop();
2046  }
2047 
2048  --m_cont_level;
2049 }
2050 
2051 
2052 void sp_parser_data::process_new_sp_instr(THD* thd, sp_instr *i)
2053 {
2054  /*
2055  thd->free_list should be cleaned here because it's implicitly expected
2056  that that process_new_sp_instr() (called from sp_head::add_instr) is
2057  called as the last action after parsing the SP-instruction's SQL query.
2058 
2059  Thus, at this point thd->free_list contains all Item-objects, created for
2060  this SP-instruction.
2061 
2062  Next SP-instruction should start its own free-list from the scratch.
2063  */
2064 
2065  i->free_list= thd->free_list;
2066 
2067  thd->free_list= NULL;
2068 }