MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
item_strfunc.cc
Go to the documentation of this file.
1 /*
2  Copyright (c) 2000, 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 
18 
30 /* May include caustic 3rd-party defs. Use early, so it can override nothing. */
31 #include "sha2.h"
32 #include "my_global.h" // HAVE_*
33 
34 
35 #include "sql_priv.h"
36 /*
37  It is necessary to include set_var.h instead of item.h because there
38  are dependencies on include order for set_var.h and item.h. This
39  will be resolved later.
40 */
41 #include "sql_class.h" // set_var.h: THD
42 #include "set_var.h"
43 #include "mysqld.h" // LOCK_uuid_generator
44 #include "sql_acl.h" // SUPER_ACL
45 #include "des_key_file.h" // st_des_keyschedule, st_des_keyblock
46 #include "password.h" // my_make_scrambled_password,
47  // my_make_scrambled_password_323
48 #include "crypt_genhash_impl.h"
49 #include <m_ctype.h>
50 #include <base64.h>
51 #include "my_md5.h"
52 #include "sha1.h"
53 #include "my_aes.h"
54 #include <zlib.h>
55 C_MODE_START
56 #include "../mysys/my_static.h" // For soundex_map
57 C_MODE_END
58 
59 using std::min;
60 using std::max;
61 
62 /*
63  For the Items which have only val_str_ascii() method
64  and don't have their own "native" val_str(),
65  we provide a "wrapper" method to convert from ASCII
66  to Item character set when it's necessary.
67  Conversion happens only in case of "tricky" Item character set (e.g. UCS2).
68  Normally conversion does not happen, and val_str_ascii() is immediately
69  returned instead.
70 */
71 String *Item_str_func::val_str_from_val_str_ascii(String *str, String *str2)
72 {
73  DBUG_ASSERT(fixed == 1);
74 
75  if (!(collation.collation->state & MY_CS_NONASCII))
76  {
77  String *res= val_str_ascii(str);
78  if (res)
79  res->set_charset(collation.collation);
80  return res;
81  }
82 
83  DBUG_ASSERT(str != str2);
84 
85  uint errors;
86  String *res= val_str_ascii(str);
87  if (!res)
88  return 0;
89 
90  if ((null_value= str2->copy(res->ptr(), res->length(),
91  &my_charset_latin1, collation.collation,
92  &errors)))
93  return 0;
94 
95  return str2;
96 }
97 
98 bool Item_str_func::fix_fields(THD *thd, Item **ref)
99 {
100  bool res= Item_func::fix_fields(thd, ref);
101  /*
102  In Item_str_func::check_well_formed_result() we may set null_value
103  flag on the same condition as in test() below.
104  */
105  maybe_null= (maybe_null || thd->is_strict_mode());
106  return res;
107 }
108 
109 
110 my_decimal *Item_str_func::val_decimal(my_decimal *decimal_value)
111 {
112  DBUG_ASSERT(fixed == 1);
113  char buff[64];
114  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
115  res= val_str(&tmp);
116  if (!res)
117  return 0;
118  (void)str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(),
119  res->length(), res->charset(), decimal_value);
120  return decimal_value;
121 }
122 
123 
124 double Item_str_func::val_real()
125 {
126  DBUG_ASSERT(fixed == 1);
127  int err_not_used;
128  char *end_not_used, buff[64];
129  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
130  res= val_str(&tmp);
131  return res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
132  &end_not_used, &err_not_used) : 0.0;
133 }
134 
135 
136 longlong Item_str_func::val_int()
137 {
138  DBUG_ASSERT(fixed == 1);
139  int err;
140  char buff[22];
141  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
142  res= val_str(&tmp);
143  return (res ?
144  my_strntoll(res->charset(), res->ptr(), res->length(), 10, NULL,
145  &err) :
146  (longlong) 0);
147 }
148 
149 
150 String *Item_func_md5::val_str_ascii(String *str)
151 {
152  DBUG_ASSERT(fixed == 1);
153  String * sptr= args[0]->val_str(str);
154  str->set_charset(&my_charset_bin);
155  if (sptr)
156  {
157  uchar digest[MD5_HASH_SIZE];
158 
159  null_value=0;
160  compute_md5_hash((char *) digest, (const char *) sptr->ptr(), sptr->length());
161  if (str->alloc(32)) // Ensure that memory is free
162  {
163  null_value=1;
164  return 0;
165  }
166  array_to_hex((char *) str->ptr(), digest, MD5_HASH_SIZE);
167  str->length((uint) 32);
168  return str;
169  }
170  null_value=1;
171  return 0;
172 }
173 
174 
175 void Item_func_md5::fix_length_and_dec()
176 {
177  /*
178  The MD5() function treats its parameter as being a case sensitive. Thus
179  we set binary collation on it so different instances of MD5() will be
180  compared properly.
181  */
182  args[0]->collation.set(
183  get_charset_by_csname(args[0]->collation.collation->csname,
184  MY_CS_BINSORT,MYF(0)), DERIVATION_COERCIBLE);
185  fix_length_and_charset(32, default_charset());
186 }
187 
188 
189 String *Item_func_sha::val_str_ascii(String *str)
190 {
191  DBUG_ASSERT(fixed == 1);
192  String * sptr= args[0]->val_str(str);
193  str->set_charset(&my_charset_bin);
194  if (sptr) /* If we got value different from NULL */
195  {
196  /* Temporary buffer to store 160bit digest */
197  uint8 digest[SHA1_HASH_SIZE];
198  compute_sha1_hash(digest, (const char *) sptr->ptr(), sptr->length());
199  /* Ensure that memory is free */
200  if (!(str->alloc(SHA1_HASH_SIZE * 2)))
201  {
202  array_to_hex((char *) str->ptr(), digest, SHA1_HASH_SIZE);
203  str->length((uint) SHA1_HASH_SIZE*2);
204  null_value=0;
205  return str;
206  }
207  }
208  null_value=1;
209  return 0;
210 }
211 
212 void Item_func_sha::fix_length_and_dec()
213 {
214  /*
215  The SHA() function treats its parameter as being a case sensitive. Thus
216  we set binary collation on it so different instances of MD5() will be
217  compared properly.
218  */
219  args[0]->collation.set(
220  get_charset_by_csname(args[0]->collation.collation->csname,
221  MY_CS_BINSORT,MYF(0)), DERIVATION_COERCIBLE);
222  // size of hex representation of hash
223  fix_length_and_charset(SHA1_HASH_SIZE * 2, default_charset());
224 }
225 
226 String *Item_func_sha2::val_str_ascii(String *str)
227 {
228  DBUG_ASSERT(fixed == 1);
229 #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
230  unsigned char digest_buf[SHA512_DIGEST_LENGTH];
231  String *input_string;
232  unsigned char *input_ptr;
233  size_t input_len;
234  uint digest_length= 0;
235 
236  str->set_charset(&my_charset_bin);
237 
238  input_string= args[0]->val_str(str);
239  if (input_string == NULL)
240  {
241  null_value= TRUE;
242  return (String *) NULL;
243  }
244 
245  null_value= args[0]->null_value;
246  if (null_value)
247  return (String *) NULL;
248 
249  input_ptr= (unsigned char *) input_string->ptr();
250  input_len= input_string->length();
251 
252  switch ((uint) args[1]->val_int()) {
253 #ifndef OPENSSL_NO_SHA512
254  case 512:
255  digest_length= SHA512_DIGEST_LENGTH;
256  (void) SHA512(input_ptr, input_len, digest_buf);
257  break;
258  case 384:
259  digest_length= SHA384_DIGEST_LENGTH;
260  (void) SHA384(input_ptr, input_len, digest_buf);
261  break;
262 #endif
263 #ifndef OPENSSL_NO_SHA256
264  case 224:
265  digest_length= SHA224_DIGEST_LENGTH;
266  (void) SHA224(input_ptr, input_len, digest_buf);
267  break;
268  case 256:
269  case 0: // SHA-256 is the default
270  digest_length= SHA256_DIGEST_LENGTH;
271  (void) SHA256(input_ptr, input_len, digest_buf);
272  break;
273 #endif
274  default:
275  if (!args[1]->const_item())
276  push_warning_printf(current_thd,
277  Sql_condition::WARN_LEVEL_WARN,
278  ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
279  ER(ER_WRONG_PARAMETERS_TO_NATIVE_FCT), "sha2");
280  null_value= TRUE;
281  return NULL;
282  }
283 
284  /*
285  Since we're subverting the usual String methods, we must make sure that
286  the destination has space for the bytes we're about to write.
287  */
288  str->realloc((uint) digest_length*2 + 1); /* Each byte as two nybbles */
289 
290  /* Convert the large number to a string-hex representation. */
291  array_to_hex((char *) str->ptr(), digest_buf, digest_length);
292 
293  /* We poked raw bytes in. We must inform the the String of its length. */
294  str->length((uint) digest_length*2); /* Each byte as two nybbles */
295 
296  null_value= FALSE;
297  return str;
298 
299 #else
300  push_warning_printf(current_thd,
301  Sql_condition::WARN_LEVEL_WARN,
302  ER_FEATURE_DISABLED,
303  ER(ER_FEATURE_DISABLED),
304  "sha2", "--with-ssl");
305  null_value= TRUE;
306  return (String *) NULL;
307 #endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
308 }
309 
310 
311 void Item_func_sha2::fix_length_and_dec()
312 {
313  maybe_null = 1;
314  max_length = 0;
315 
316 #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
317  int sha_variant= args[1]->const_item() ? args[1]->val_int() : 512;
318 
319  switch (sha_variant) {
320 #ifndef OPENSSL_NO_SHA512
321  case 512:
322  fix_length_and_charset(SHA512_DIGEST_LENGTH * 2, default_charset());
323  break;
324  case 384:
325  fix_length_and_charset(SHA384_DIGEST_LENGTH * 2, default_charset());
326  break;
327 #endif
328 #ifndef OPENSSL_NO_SHA256
329  case 256:
330  case 0: // SHA-256 is the default
331  fix_length_and_charset(SHA256_DIGEST_LENGTH * 2, default_charset());
332  break;
333  case 224:
334  fix_length_and_charset(SHA224_DIGEST_LENGTH * 2, default_charset());
335  break;
336 #endif
337  default:
338  push_warning_printf(current_thd,
339  Sql_condition::WARN_LEVEL_WARN,
340  ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
341  ER(ER_WRONG_PARAMETERS_TO_NATIVE_FCT), "sha2");
342  }
343 
344  /*
345  The SHA2() function treats its parameter as being a case sensitive.
346  Thus we set binary collation on it so different instances of SHA2()
347  will be compared properly.
348  */
349 
350  args[0]->collation.set(
351  get_charset_by_csname(
352  args[0]->collation.collation->csname,
353  MY_CS_BINSORT,
354  MYF(0)),
355  DERIVATION_COERCIBLE);
356 #else
357  push_warning_printf(current_thd,
358  Sql_condition::WARN_LEVEL_WARN,
359  ER_FEATURE_DISABLED,
360  ER(ER_FEATURE_DISABLED),
361  "sha2", "--with-ssl");
362 #endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
363 }
364 
365 /* Implementation of AES encryption routines */
366 
367 String *Item_func_aes_encrypt::val_str(String *str)
368 {
369  DBUG_ASSERT(fixed == 1);
370  char key_buff[80];
371  String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
372  String *sptr= args[0]->val_str(str); // String to encrypt
373  String *key= args[1]->val_str(&tmp_key_value); // key
374  int aes_length;
375  if (sptr && key) // we need both arguments to be not NULL
376  {
377  null_value=0;
378  aes_length=my_aes_get_size(sptr->length()); // Calculate result length
379 
380  if (!str_value.alloc(aes_length)) // Ensure that memory is free
381  {
382  // finally encrypt directly to allocated buffer.
383  if (my_aes_encrypt(sptr->ptr(),sptr->length(), (char*) str_value.ptr(),
384  key->ptr(), key->length()) == aes_length)
385  {
386  // We got the expected result length
387  str_value.length((uint) aes_length);
388  return &str_value;
389  }
390  }
391  }
392  null_value=1;
393  return 0;
394 }
395 
396 
397 void Item_func_aes_encrypt::fix_length_and_dec()
398 {
399  max_length=my_aes_get_size(args[0]->max_length);
400 }
401 
402 
403 String *Item_func_aes_decrypt::val_str(String *str)
404 {
405  DBUG_ASSERT(fixed == 1);
406  char key_buff[80];
407  String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
408  String *sptr, *key;
409  DBUG_ENTER("Item_func_aes_decrypt::val_str");
410 
411  sptr= args[0]->val_str(str); // String to decrypt
412  key= args[1]->val_str(&tmp_key_value); // Key
413  if (sptr && key) // Need to have both arguments not NULL
414  {
415  null_value=0;
416  if (!str_value.alloc(sptr->length())) // Ensure that memory is free
417  {
418  // finally decrypt directly to allocated buffer.
419  int length;
420  length=my_aes_decrypt(sptr->ptr(), sptr->length(),
421  (char*) str_value.ptr(),
422  key->ptr(), key->length());
423  if (length >= 0) // if we got correct data data
424  {
425  str_value.length((uint) length);
426  DBUG_RETURN(&str_value);
427  }
428  }
429  }
430  // Bad parameters. No memory or bad data will all go here
431  null_value=1;
432  DBUG_RETURN(0);
433 }
434 
435 
436 void Item_func_aes_decrypt::fix_length_and_dec()
437 {
438  max_length=args[0]->max_length;
439  maybe_null= 1;
440 }
441 
442 
443 void Item_func_to_base64::fix_length_and_dec()
444 {
445  maybe_null= args[0]->maybe_null;
446  collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII);
447  if (args[0]->max_length > (uint) base64_encode_max_arg_length())
448  {
449  maybe_null= 1;
450  fix_char_length_ulonglong((ulonglong) base64_encode_max_arg_length());
451  }
452  else
453  {
454  int length= base64_needed_encoded_length((int) args[0]->max_length);
455  DBUG_ASSERT(length > 0);
456  fix_char_length_ulonglong((ulonglong) length - 1);
457  }
458 }
459 
460 
461 String *Item_func_to_base64::val_str_ascii(String *str)
462 {
463  String *res= args[0]->val_str(str);
464  bool too_long= false;
465  int length;
466  if (!res ||
467  res->length() > (uint) base64_encode_max_arg_length() ||
468  (too_long=
469  ((uint) (length= base64_needed_encoded_length((int) res->length())) >
470  current_thd->variables.max_allowed_packet)) ||
471  tmp_value.alloc((uint) length))
472  {
473  null_value= 1; // NULL input, too long input, or OOM.
474  if (too_long)
475  {
476  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
477  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
478  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
479  current_thd->variables.max_allowed_packet);
480  }
481  return 0;
482  }
483  base64_encode(res->ptr(), (int) res->length(), (char*) tmp_value.ptr());
484  DBUG_ASSERT(length > 0);
485  tmp_value.length((uint) length - 1); // Without trailing '\0'
486  null_value= 0;
487  return &tmp_value;
488 }
489 
490 
491 void Item_func_from_base64::fix_length_and_dec()
492 {
493  if (args[0]->max_length > (uint) base64_decode_max_arg_length())
494  {
495  fix_char_length_ulonglong((ulonglong) base64_decode_max_arg_length());
496  }
497  else
498  {
499  int length= base64_needed_decoded_length((int) args[0]->max_length);
500  fix_char_length_ulonglong((ulonglong) length);
501  }
502  maybe_null= 1; // Can be NULL, e.g. in case of badly formed input string
503 }
504 
505 
506 String *Item_func_from_base64::val_str(String *str)
507 {
508  String *res= args[0]->val_str_ascii(str);
509  bool too_long= false;
510  int length;
511  const char *end_ptr;
512 
513  if (!res ||
514  res->length() > (uint) base64_decode_max_arg_length() ||
515  (too_long=
516  ((uint) (length= base64_needed_decoded_length((int) res->length())) >
517  current_thd->variables.max_allowed_packet)) ||
518  tmp_value.alloc((uint) length) ||
519  (length= base64_decode(res->ptr(), (int) res->length(),
520  (char *) tmp_value.ptr(), &end_ptr, 0)) < 0 ||
521  end_ptr < res->ptr() + res->length())
522  {
523  null_value= 1; // NULL input, too long input, OOM, or badly formed input
524  if (too_long)
525  {
526  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
527  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
528  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
529  current_thd->variables.max_allowed_packet);
530  }
531  return 0;
532  }
533  tmp_value.length((uint) length);
534  null_value= 0;
535  return &tmp_value;
536 }
537 
538 
546 {
547  DBUG_ASSERT(fixed == 1);
548  String *res,*res2,*use_as_buff;
549  uint i;
550  bool is_const= 0;
551 
552  null_value=0;
553  if (!(res=args[0]->val_str(str)))
554  goto null;
555  use_as_buff= &tmp_value;
556  /* Item_subselect in --ps-protocol mode will state it as a non-const */
557  is_const= args[0]->const_item() || !args[0]->used_tables();
558  for (i=1 ; i < arg_count ; i++)
559  {
560  if (res->length() == 0)
561  {
562  if (!(res=args[i]->val_str(str)))
563  goto null;
564  /*
565  CONCAT accumulates its result in the result of its the first
566  non-empty argument. Because of this we need is_const to be
567  evaluated only for it.
568  */
569  is_const= args[i]->const_item() || !args[i]->used_tables();
570  }
571  else
572  {
573  if (!(res2=args[i]->val_str(use_as_buff)))
574  goto null;
575  if (res2->length() == 0)
576  continue;
577  if (res->length()+res2->length() >
578  current_thd->variables.max_allowed_packet)
579  {
580  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
581  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
582  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
583  current_thd->variables.max_allowed_packet);
584  goto null;
585  }
586  if (!is_const && res->alloced_length() >= res->length()+res2->length())
587  { // Use old buffer
588  res->append(*res2);
589  }
590  else if (str->alloced_length() >= res->length()+res2->length())
591  {
592  if (str->ptr() == res2->ptr())
593  str->replace(0,0,*res);
594  else
595  {
596  str->copy(*res);
597  str->append(*res2);
598  }
599  res= str;
600  use_as_buff= &tmp_value;
601  }
602  else if (res == &tmp_value)
603  {
604  if (res->append(*res2)) // Must be a blob
605  goto null;
606  }
607  else if (res2 == &tmp_value)
608  { // This can happend only 1 time
609  if (tmp_value.replace(0,0,*res))
610  goto null;
611  res= &tmp_value;
612  use_as_buff=str; // Put next arg here
613  }
614  else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
615  res2->ptr() <= tmp_value.ptr() + tmp_value.alloced_length())
616  {
617  /*
618  This happens really seldom:
619  In this case res2 is sub string of tmp_value. We will
620  now work in place in tmp_value to set it to res | res2
621  */
622  /* Chop the last characters in tmp_value that isn't in res2 */
623  tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
624  res2->length());
625  /* Place res2 at start of tmp_value, remove chars before res2 */
626  if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
627  *res))
628  goto null;
629  res= &tmp_value;
630  use_as_buff=str; // Put next arg here
631  }
632  else
633  { // Two big const strings
634  /*
635  NOTE: We should be prudent in the initial allocation unit -- the
636  size of the arguments is a function of data distribution, which
637  can be any. Instead of overcommitting at the first row, we grow
638  the allocated amount by the factor of 2. This ensures that no
639  more than 25% of memory will be overcommitted on average.
640  */
641 
642  uint concat_len= res->length() + res2->length();
643 
644  if (tmp_value.alloced_length() < concat_len)
645  {
646  if (tmp_value.alloced_length() == 0)
647  {
648  if (tmp_value.alloc(concat_len))
649  goto null;
650  }
651  else
652  {
653  uint new_len = max(tmp_value.alloced_length() * 2, concat_len);
654 
655  if (tmp_value.realloc(new_len))
656  goto null;
657  }
658  }
659 
660  if (tmp_value.copy(*res) || tmp_value.append(*res2))
661  goto null;
662 
663  res= &tmp_value;
664  use_as_buff=str;
665  }
666  is_const= 0;
667  }
668  }
669  res->set_charset(collation.collation);
670  return res;
671 
672 null:
673  null_value=1;
674  return 0;
675 }
676 
677 
678 void Item_func_concat::fix_length_and_dec()
679 {
680  ulonglong char_length= 0;
681 
682  if (agg_arg_charsets_for_string_result(collation, args, arg_count))
683  return;
684 
685  for (uint i=0 ; i < arg_count ; i++)
686  char_length+= args[i]->max_char_length();
687 
688  fix_char_length_ulonglong(char_length);
689 }
690 
703 {
704  DBUG_ASSERT(fixed == 1);
705 #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
706  uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
707  DES_cblock ivec;
708  struct st_des_keyblock keyblock;
709  struct st_des_keyschedule keyschedule;
710  const char *append_str="********";
711  uint key_number, res_length, tail;
712  String *res= args[0]->val_str(str);
713 
714  if ((null_value= args[0]->null_value))
715  return 0; // ENCRYPT(NULL) == NULL
716  if ((res_length=res->length()) == 0)
717  return make_empty_result();
718  if (arg_count == 1)
719  {
720  /* Protect against someone doing FLUSH DES_KEY_FILE */
721  mysql_mutex_lock(&LOCK_des_key_file);
722  keyschedule= des_keyschedule[key_number=des_default_key];
723  mysql_mutex_unlock(&LOCK_des_key_file);
724  }
725  else if (args[1]->result_type() == INT_RESULT)
726  {
727  key_number= (uint) args[1]->val_int();
728  if (key_number > 9)
729  goto error;
730  mysql_mutex_lock(&LOCK_des_key_file);
731  keyschedule= des_keyschedule[key_number];
732  mysql_mutex_unlock(&LOCK_des_key_file);
733  }
734  else
735  {
736  String *keystr=args[1]->val_str(&tmp_value);
737  if (!keystr)
738  goto error;
739  key_number=127; // User key string
740 
741  /* We make good 24-byte (168 bit) key from given plaintext key with MD5 */
742  memset(&ivec, 0, sizeof(ivec));
743  EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
744  (uchar*) keystr->ptr(), (int) keystr->length(),
745  1, (uchar*) &keyblock,ivec);
746  DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
747  DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
748  DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
749  }
750 
751  /*
752  The problem: DES algorithm requires original data to be in 8-bytes
753  chunks. Missing bytes get filled with '*'s and result of encryption
754  can be up to 8 bytes longer than original string. When decrypted,
755  we do not know the size of original string :(
756  We add one byte with value 0x1..0x8 as the last byte of the padded
757  string marking change of string length.
758  */
759 
760  tail= 8 - (res_length % 8); // 1..8 marking extra length
761  res_length+=tail;
762  tmp_arg.realloc(res_length);
763  tmp_arg.length(0);
764  tmp_arg.append(res->ptr(), res->length());
765  code= ER_OUT_OF_RESOURCES;
766  if (tmp_arg.append(append_str, tail) || tmp_value.alloc(res_length+1))
767  goto error;
768  tmp_arg[res_length-1]=tail; // save extra length
769  tmp_value.realloc(res_length+1);
770  tmp_value.length(res_length+1);
771  tmp_value.set_charset(&my_charset_bin);
772  tmp_value[0]=(char) (128 | key_number);
773  // Real encryption
774  memset(&ivec, 0, sizeof(ivec));
775  DES_ede3_cbc_encrypt((const uchar*) (tmp_arg.ptr()),
776  (uchar*) (tmp_value.ptr()+1),
777  res_length,
778  &keyschedule.ks1,
779  &keyschedule.ks2,
780  &keyschedule.ks3,
781  &ivec, TRUE);
782  return &tmp_value;
783 
784 error:
785  push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
786  code, ER(code),
787  "des_encrypt");
788 #else
789  push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
790  ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED),
791  "des_encrypt", "--with-ssl");
792 #endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
793  null_value=1;
794  return 0;
795 }
796 
797 
798 String *Item_func_des_decrypt::val_str(String *str)
799 {
800  DBUG_ASSERT(fixed == 1);
801 #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
802  uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
803  DES_cblock ivec;
804  struct st_des_keyblock keyblock;
805  struct st_des_keyschedule keyschedule;
806  String *res= args[0]->val_str(str);
807  uint length,tail;
808 
809  if ((null_value= args[0]->null_value))
810  return 0;
811  length= res->length();
812  if (length < 9 || (length % 8) != 1 || !((*res)[0] & 128))
813  return res; // Skip decryption if not encrypted
814 
815  if (arg_count == 1) // If automatic uncompression
816  {
817  uint key_number=(uint) (*res)[0] & 127;
818  // Check if automatic key and that we have privilege to uncompress using it
819  if (!(current_thd->security_ctx->master_access & SUPER_ACL) ||
820  key_number > 9)
821  goto error;
822 
823  mysql_mutex_lock(&LOCK_des_key_file);
824  keyschedule= des_keyschedule[key_number];
825  mysql_mutex_unlock(&LOCK_des_key_file);
826  }
827  else
828  {
829  // We make good 24-byte (168 bit) key from given plaintext key with MD5
830  String *keystr=args[1]->val_str(&tmp_value);
831  if (!keystr)
832  goto error;
833 
834  memset(&ivec, 0, sizeof(ivec));
835  EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
836  (uchar*) keystr->ptr(),(int) keystr->length(),
837  1,(uchar*) &keyblock,ivec);
838  // Here we set all 64-bit keys (56 effective) one by one
839  DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
840  DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
841  DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
842  }
843  code= ER_OUT_OF_RESOURCES;
844  if (tmp_value.alloc(length-1))
845  goto error;
846 
847  memset(&ivec, 0, sizeof(ivec));
848  DES_ede3_cbc_encrypt((const uchar*) res->ptr()+1,
849  (uchar*) (tmp_value.ptr()),
850  length-1,
851  &keyschedule.ks1,
852  &keyschedule.ks2,
853  &keyschedule.ks3,
854  &ivec, FALSE);
855  /* Restore old length of key */
856  if ((tail=(uint) (uchar) tmp_value[length-2]) > 8)
857  goto wrong_key; // Wrong key
858  tmp_value.length(length-1-tail);
859  tmp_value.set_charset(&my_charset_bin);
860  return &tmp_value;
861 
862 error:
863  push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
864  code, ER(code),
865  "des_decrypt");
866 wrong_key:
867 #else
868  push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
869  ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED),
870  "des_decrypt", "--with-ssl");
871 #endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
872  null_value=1;
873  return 0;
874 }
875 
876 
883 {
884  DBUG_ASSERT(fixed == 1);
885  char tmp_str_buff[10];
886  String tmp_sep_str(tmp_str_buff, sizeof(tmp_str_buff),default_charset_info),
887  *sep_str, *res, *res2,*use_as_buff;
888  uint i;
889  bool is_const= 0;
890 
891  null_value=0;
892  if (!(sep_str= args[0]->val_str(&tmp_sep_str)))
893  goto null;
894 
895  use_as_buff= &tmp_value;
896  str->length(0); // QQ; Should be removed
897  res=str;
898 
899  // Skip until non-null argument is found.
900  // If not, return the empty string
901  for (i=1; i < arg_count; i++)
902  if ((res= args[i]->val_str(str)))
903  {
904  is_const= args[i]->const_item() || !args[i]->used_tables();
905  break;
906  }
907 
908  if (i == arg_count)
909  return make_empty_result();
910 
911  for (i++; i < arg_count ; i++)
912  {
913  if (!(res2= args[i]->val_str(use_as_buff)))
914  continue; // Skip NULL
915 
916  if (res->length() + sep_str->length() + res2->length() >
917  current_thd->variables.max_allowed_packet)
918  {
919  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
920  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
921  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
922  current_thd->variables.max_allowed_packet);
923  goto null;
924  }
925  if (!is_const && res->alloced_length() >=
926  res->length() + sep_str->length() + res2->length())
927  { // Use old buffer
928  res->append(*sep_str); // res->length() > 0 always
929  res->append(*res2);
930  }
931  else if (str->alloced_length() >=
932  res->length() + sep_str->length() + res2->length())
933  {
934  /* We have room in str; We can't get any errors here */
935  if (str->ptr() == res2->ptr())
936  { // This is quite uncommon!
937  str->replace(0,0,*sep_str);
938  str->replace(0,0,*res);
939  }
940  else
941  {
942  str->copy(*res);
943  str->append(*sep_str);
944  str->append(*res2);
945  }
946  res=str;
947  use_as_buff= &tmp_value;
948  }
949  else if (res == &tmp_value)
950  {
951  if (res->append(*sep_str) || res->append(*res2))
952  goto null; // Must be a blob
953  }
954  else if (res2 == &tmp_value)
955  { // This can happend only 1 time
956  if (tmp_value.replace(0,0,*sep_str) || tmp_value.replace(0,0,*res))
957  goto null;
958  res= &tmp_value;
959  use_as_buff=str; // Put next arg here
960  }
961  else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
962  res2->ptr() < tmp_value.ptr() + tmp_value.alloced_length())
963  {
964  /*
965  This happens really seldom:
966  In this case res2 is sub string of tmp_value. We will
967  now work in place in tmp_value to set it to res | sep_str | res2
968  */
969  /* Chop the last characters in tmp_value that isn't in res2 */
970  tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
971  res2->length());
972  /* Place res2 at start of tmp_value, remove chars before res2 */
973  if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
974  *res) ||
975  tmp_value.replace(res->length(),0, *sep_str))
976  goto null;
977  res= &tmp_value;
978  use_as_buff=str; // Put next arg here
979  }
980  else
981  { // Two big const strings
982  /*
983  NOTE: We should be prudent in the initial allocation unit -- the
984  size of the arguments is a function of data distribution, which can
985  be any. Instead of overcommitting at the first row, we grow the
986  allocated amount by the factor of 2. This ensures that no more than
987  25% of memory will be overcommitted on average.
988  */
989 
990  uint concat_len= res->length() + sep_str->length() + res2->length();
991 
992  if (tmp_value.alloced_length() < concat_len)
993  {
994  if (tmp_value.alloced_length() == 0)
995  {
996  if (tmp_value.alloc(concat_len))
997  goto null;
998  }
999  else
1000  {
1001  uint new_len = max(tmp_value.alloced_length() * 2, concat_len);
1002 
1003  if (tmp_value.realloc(new_len))
1004  goto null;
1005  }
1006  }
1007 
1008  if (tmp_value.copy(*res) ||
1009  tmp_value.append(*sep_str) ||
1010  tmp_value.append(*res2))
1011  goto null;
1012  res= &tmp_value;
1013  use_as_buff=str;
1014  }
1015  }
1016  res->set_charset(collation.collation);
1017  return res;
1018 
1019 null:
1020  null_value=1;
1021  return 0;
1022 }
1023 
1024 
1025 void Item_func_concat_ws::fix_length_and_dec()
1026 {
1027  ulonglong char_length;
1028 
1029  if (agg_arg_charsets_for_string_result(collation, args, arg_count))
1030  return;
1031 
1032  /*
1033  arg_count cannot be less than 2,
1034  it is done on parser level in sql_yacc.yy
1035  so, (arg_count - 2) is safe here.
1036  */
1037  char_length= (ulonglong) args[0]->max_char_length() * (arg_count - 2);
1038  for (uint i=1 ; i < arg_count ; i++)
1039  char_length+= args[i]->max_char_length();
1040 
1041  fix_char_length_ulonglong(char_length);
1042 }
1043 
1044 
1045 String *Item_func_reverse::val_str(String *str)
1046 {
1047  DBUG_ASSERT(fixed == 1);
1048  String *res = args[0]->val_str(str);
1049  char *ptr, *end, *tmp;
1050 
1051  if ((null_value=args[0]->null_value))
1052  return 0;
1053  /* An empty string is a special case as the string pointer may be null */
1054  if (!res->length())
1055  return make_empty_result();
1056  if (tmp_value.alloced_length() < res->length() &&
1057  tmp_value.realloc(res->length()))
1058  {
1059  null_value= 1;
1060  return 0;
1061  }
1062  tmp_value.length(res->length());
1063  tmp_value.set_charset(res->charset());
1064  ptr= (char *) res->ptr();
1065  end= ptr + res->length();
1066  tmp= (char *) tmp_value.ptr() + tmp_value.length();
1067 #ifdef USE_MB
1068  if (use_mb(res->charset()))
1069  {
1070  register uint32 l;
1071  while (ptr < end)
1072  {
1073  if ((l= my_ismbchar(res->charset(),ptr,end)))
1074  {
1075  tmp-= l;
1076  memcpy(tmp,ptr,l);
1077  ptr+= l;
1078  }
1079  else
1080  *--tmp= *ptr++;
1081  }
1082  }
1083  else
1084 #endif /* USE_MB */
1085  {
1086  while (ptr < end)
1087  *--tmp= *ptr++;
1088  }
1089  return &tmp_value;
1090 }
1091 
1092 
1093 void Item_func_reverse::fix_length_and_dec()
1094 {
1095  agg_arg_charsets_for_string_result(collation, args, 1);
1096  DBUG_ASSERT(collation.collation != NULL);
1097  fix_char_length(args[0]->max_char_length());
1098 }
1099 
1110 {
1111  DBUG_ASSERT(fixed == 1);
1112  String *res,*res2,*res3;
1113  int offset;
1114  uint from_length,to_length;
1115  bool alloced=0;
1116 #ifdef USE_MB
1117  const char *ptr,*end,*strend,*search,*search_end;
1118  register uint32 l;
1119  bool binary_cmp;
1120 #endif
1121 
1122  null_value=0;
1123  res=args[0]->val_str(str);
1124  if (args[0]->null_value)
1125  goto null;
1126  res2=args[1]->val_str(&tmp_value);
1127  if (args[1]->null_value)
1128  goto null;
1129 
1130  res->set_charset(collation.collation);
1131 
1132 #ifdef USE_MB
1133  binary_cmp = ((res->charset()->state & MY_CS_BINSORT) || !use_mb(res->charset()));
1134 #endif
1135 
1136  if (res2->length() == 0)
1137  return res;
1138 #ifndef USE_MB
1139  if ((offset=res->strstr(*res2)) < 0)
1140  return res;
1141 #else
1142  offset=0;
1143  if (binary_cmp && (offset=res->strstr(*res2)) < 0)
1144  return res;
1145 #endif
1146  if (!(res3=args[2]->val_str(&tmp_value2)))
1147  goto null;
1148  from_length= res2->length();
1149  to_length= res3->length();
1150 
1151 #ifdef USE_MB
1152  if (!binary_cmp)
1153  {
1154  search=res2->ptr();
1155  search_end=search+from_length;
1156 redo:
1157  DBUG_ASSERT(res->ptr() || !offset);
1158  ptr=res->ptr()+offset;
1159  strend=res->ptr()+res->length();
1160  /*
1161  In some cases val_str() can return empty string
1162  with ptr() == NULL and length() == 0.
1163  Let's check strend to avoid overflow.
1164  */
1165  end= strend ? strend - from_length + 1 : NULL;
1166  while (ptr < end)
1167  {
1168  if (*ptr == *search)
1169  {
1170  register char *i,*j;
1171  i=(char*) ptr+1; j=(char*) search+1;
1172  while (j != search_end)
1173  if (*i++ != *j++) goto skip;
1174  offset= (int) (ptr-res->ptr());
1175  if (res->length()-from_length + to_length >
1176  current_thd->variables.max_allowed_packet)
1177  {
1178  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
1179  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1180  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
1181  func_name(),
1182  current_thd->variables.max_allowed_packet);
1183 
1184  goto null;
1185  }
1186  if (!alloced)
1187  {
1188  alloced=1;
1189  res=copy_if_not_alloced(str,res,res->length()+to_length);
1190  }
1191  res->replace((uint) offset,from_length,*res3);
1192  offset+=(int) to_length;
1193  goto redo;
1194  }
1195 skip:
1196  if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
1197  else ++ptr;
1198  }
1199  }
1200  else
1201 #endif /* USE_MB */
1202  do
1203  {
1204  if (res->length()-from_length + to_length >
1205  current_thd->variables.max_allowed_packet)
1206  {
1207  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
1208  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1209  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
1210  current_thd->variables.max_allowed_packet);
1211  goto null;
1212  }
1213  if (!alloced)
1214  {
1215  alloced=1;
1216  res=copy_if_not_alloced(str,res,res->length()+to_length);
1217  }
1218  res->replace((uint) offset,from_length,*res3);
1219  offset+=(int) to_length;
1220  }
1221  while ((offset=res->strstr(*res2,(uint) offset)) >= 0);
1222  return res;
1223 
1224 null:
1225  null_value=1;
1226  return 0;
1227 }
1228 
1229 
1230 void Item_func_replace::fix_length_and_dec()
1231 {
1232  ulonglong char_length= (ulonglong) args[0]->max_char_length();
1233  int diff=(int) (args[2]->max_char_length() - args[1]->max_char_length());
1234  if (diff > 0 && args[1]->max_char_length())
1235  { // Calculate of maxreplaces
1236  ulonglong max_substrs= char_length / args[1]->max_char_length();
1237  char_length+= max_substrs * (uint) diff;
1238  }
1239 
1240  if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 3))
1241  return;
1242  fix_char_length_ulonglong(char_length);
1243 }
1244 
1245 
1246 String *Item_func_insert::val_str(String *str)
1247 {
1248  DBUG_ASSERT(fixed == 1);
1249  String *res,*res2;
1250  longlong start, length; /* must be longlong to avoid truncation */
1251 
1252  null_value=0;
1253  res=args[0]->val_str(str);
1254  res2=args[3]->val_str(&tmp_value);
1255  start= args[1]->val_int() - 1;
1256  length= args[2]->val_int();
1257 
1258  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
1259  args[3]->null_value)
1260  goto null; /* purecov: inspected */
1261 
1262  if ((start < 0) || (start > res->length()))
1263  return res; // Wrong param; skip insert
1264  if ((length < 0) || (length > res->length()))
1265  length= res->length();
1266 
1267  /*
1268  There is one exception not handled (intentionaly) by the character set
1269  aggregation code. If one string is strong side and is binary, and
1270  another one is weak side and is a multi-byte character string,
1271  then we need to operate on the second string in terms on bytes when
1272  calling ::numchars() and ::charpos(), rather than in terms of characters.
1273  Lets substitute its character set to binary.
1274  */
1275  if (collation.collation == &my_charset_bin)
1276  {
1277  res->set_charset(&my_charset_bin);
1278  res2->set_charset(&my_charset_bin);
1279  }
1280 
1281  /* start and length are now sufficiently valid to pass to charpos function */
1282  start= res->charpos((int) start);
1283  length= res->charpos((int) length, (uint32) start);
1284 
1285  /* Re-testing with corrected params */
1286  if (start > res->length())
1287  return res; /* purecov: inspected */ // Wrong param; skip insert
1288  if (length > res->length() - start)
1289  length= res->length() - start;
1290 
1291  if ((ulonglong) (res->length() - length + res2->length()) >
1292  (ulonglong) current_thd->variables.max_allowed_packet)
1293  {
1294  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
1295  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1296  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
1297  func_name(), current_thd->variables.max_allowed_packet);
1298  goto null;
1299  }
1300  res=copy_if_not_alloced(str,res,res->length());
1301  res->replace((uint32) start,(uint32) length,*res2);
1302  return res;
1303 null:
1304  null_value=1;
1305  return 0;
1306 }
1307 
1308 
1309 void Item_func_insert::fix_length_and_dec()
1310 {
1311  ulonglong char_length;
1312 
1313  // Handle character set for args[0] and args[3].
1314  if (agg_arg_charsets_for_string_result(collation, args, 2, 3))
1315  return;
1316  char_length= ((ulonglong) args[0]->max_char_length() +
1317  (ulonglong) args[3]->max_char_length());
1318  fix_char_length_ulonglong(char_length);
1319 }
1320 
1321 
1322 String *Item_str_conv::val_str(String *str)
1323 {
1324  DBUG_ASSERT(fixed == 1);
1325  String *res;
1326  if (!(res=args[0]->val_str(str)))
1327  {
1328  null_value=1; /* purecov: inspected */
1329  return 0; /* purecov: inspected */
1330  }
1331  null_value=0;
1332  if (multiply == 1)
1333  {
1334  uint len;
1335  res= copy_if_not_alloced(str,res,res->length());
1336  len= converter(collation.collation, (char*) res->ptr(), res->length(),
1337  (char*) res->ptr(), res->length());
1338  DBUG_ASSERT(len <= res->length());
1339  res->length(len);
1340  }
1341  else
1342  {
1343  uint len= res->length() * multiply;
1344  tmp_value.alloc(len);
1345  tmp_value.set_charset(collation.collation);
1346  len= converter(collation.collation, (char*) res->ptr(), res->length(),
1347  (char*) tmp_value.ptr(), len);
1348  tmp_value.length(len);
1349  res= &tmp_value;
1350  }
1351  return res;
1352 }
1353 
1354 
1355 void Item_func_lcase::fix_length_and_dec()
1356 {
1357  agg_arg_charsets_for_string_result(collation, args, 1);
1358  DBUG_ASSERT(collation.collation != NULL);
1359  multiply= collation.collation->casedn_multiply;
1360  converter= collation.collation->cset->casedn;
1361  fix_char_length_ulonglong((ulonglong) args[0]->max_char_length() * multiply);
1362 }
1363 
1364 void Item_func_ucase::fix_length_and_dec()
1365 {
1366  agg_arg_charsets_for_string_result(collation, args, 1);
1367  DBUG_ASSERT(collation.collation != NULL);
1368  multiply= collation.collation->caseup_multiply;
1369  converter= collation.collation->cset->caseup;
1370  fix_char_length_ulonglong((ulonglong) args[0]->max_char_length() * multiply);
1371 }
1372 
1373 
1374 String *Item_func_left::val_str(String *str)
1375 {
1376  DBUG_ASSERT(fixed == 1);
1377  String *res= args[0]->val_str(str);
1378 
1379  /* must be longlong to avoid truncation */
1380  longlong length= args[1]->val_int();
1381  uint char_pos;
1382 
1383  if ((null_value=(args[0]->null_value || args[1]->null_value)))
1384  return 0;
1385 
1386  /* if "unsigned_flag" is set, we have a *huge* positive number. */
1387  if ((length <= 0) && (!args[1]->unsigned_flag))
1388  return make_empty_result();
1389  if ((res->length() <= (ulonglong) length) ||
1390  (res->length() <= (char_pos= res->charpos((int) length))))
1391  return res;
1392 
1393  tmp_value.set(*res, 0, char_pos);
1394  return &tmp_value;
1395 }
1396 
1397 
1398 void Item_str_func::left_right_max_length()
1399 {
1400  uint32 char_length= args[0]->max_char_length();
1401  if (args[1]->const_item())
1402  {
1403  int length= (int) args[1]->val_int();
1404  if (args[1]->null_value)
1405  goto end;
1406 
1407  if (length <= 0)
1408  char_length=0;
1409  else
1410  set_if_smaller(char_length, (uint) length);
1411  }
1412 
1413 end:
1414  fix_char_length(char_length);
1415 }
1416 
1417 
1418 void Item_func_left::fix_length_and_dec()
1419 {
1420  agg_arg_charsets_for_string_result(collation, args, 1);
1421  DBUG_ASSERT(collation.collation != NULL);
1422  left_right_max_length();
1423 }
1424 
1425 
1426 String *Item_func_right::val_str(String *str)
1427 {
1428  DBUG_ASSERT(fixed == 1);
1429  String *res= args[0]->val_str(str);
1430  /* must be longlong to avoid truncation */
1431  longlong length= args[1]->val_int();
1432 
1433  if ((null_value=(args[0]->null_value || args[1]->null_value)))
1434  return 0; /* purecov: inspected */
1435 
1436  /* if "unsigned_flag" is set, we have a *huge* positive number. */
1437  if ((length <= 0) && (!args[1]->unsigned_flag))
1438  return make_empty_result(); /* purecov: inspected */
1439 
1440  if (res->length() <= (ulonglong) length)
1441  return res; /* purecov: inspected */
1442 
1443  uint start=res->numchars();
1444  if (start <= (uint) length)
1445  return res;
1446  start=res->charpos(start - (uint) length);
1447  tmp_value.set(*res,start,res->length()-start);
1448  return &tmp_value;
1449 }
1450 
1451 
1452 void Item_func_right::fix_length_and_dec()
1453 {
1454  agg_arg_charsets_for_string_result(collation, args, 1);
1455  DBUG_ASSERT(collation.collation != NULL);
1456  left_right_max_length();
1457 }
1458 
1459 
1460 String *Item_func_substr::val_str(String *str)
1461 {
1462  DBUG_ASSERT(fixed == 1);
1463  String *res = args[0]->val_str(str);
1464  /* must be longlong to avoid truncation */
1465  longlong start= args[1]->val_int();
1466  /* Assumes that the maximum length of a String is < INT_MAX32. */
1467  /* Limit so that code sees out-of-bound value properly. */
1468  longlong length= arg_count == 3 ? args[2]->val_int() : INT_MAX32;
1469  longlong tmp_length;
1470 
1471  if ((null_value=(args[0]->null_value || args[1]->null_value ||
1472  (arg_count == 3 && args[2]->null_value))))
1473  return 0; /* purecov: inspected */
1474 
1475  /* Negative or zero length, will return empty string. */
1476  if ((arg_count == 3) && (length <= 0) &&
1477  (length == 0 || !args[2]->unsigned_flag))
1478  return make_empty_result();
1479 
1480  /* Assumes that the maximum length of a String is < INT_MAX32. */
1481  /* Set here so that rest of code sees out-of-bound value as such. */
1482  if ((length <= 0) || (length > INT_MAX32))
1483  length= INT_MAX32;
1484 
1485  /* if "unsigned_flag" is set, we have a *huge* positive number. */
1486  /* Assumes that the maximum length of a String is < INT_MAX32. */
1487  if ((!args[1]->unsigned_flag && (start < INT_MIN32 || start > INT_MAX32)) ||
1488  (args[1]->unsigned_flag && ((ulonglong) start > INT_MAX32)))
1489  return make_empty_result();
1490 
1491  start= ((start < 0) ? res->numchars() + start : start - 1);
1492  start= res->charpos((int) start);
1493  if ((start < 0) || ((uint) start + 1 > res->length()))
1494  return make_empty_result();
1495 
1496  length= res->charpos((int) length, (uint32) start);
1497  tmp_length= res->length() - start;
1498  length= min(length, tmp_length);
1499 
1500  if (!start && (longlong) res->length() == length)
1501  return res;
1502  tmp_value.set(*res, (uint32) start, (uint32) length);
1503  return &tmp_value;
1504 }
1505 
1506 
1507 void Item_func_substr::fix_length_and_dec()
1508 {
1509  max_length=args[0]->max_length;
1510 
1511  agg_arg_charsets_for_string_result(collation, args, 1);
1512  DBUG_ASSERT(collation.collation != NULL);
1513  if (args[1]->const_item())
1514  {
1515  int32 start= (int32) args[1]->val_int();
1516  if (args[1]->null_value)
1517  goto end;
1518  if (start < 0)
1519  max_length= ((uint)(-start) > max_length) ? 0 : (uint)(-start);
1520  else
1521  max_length-= min((uint)(start - 1), max_length);
1522  }
1523  if (arg_count == 3 && args[2]->const_item())
1524  {
1525  int32 length= (int32) args[2]->val_int();
1526  if (args[2]->null_value)
1527  goto end;
1528  if (length <= 0)
1529  max_length=0; /* purecov: inspected */
1530  else
1531  set_if_smaller(max_length,(uint) length);
1532  }
1533 
1534 end:
1535  max_length*= collation.collation->mbmaxlen;
1536 }
1537 
1538 
1539 void Item_func_substr_index::fix_length_and_dec()
1540 {
1541  if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 2))
1542  return;
1543  fix_char_length(args[0]->max_char_length());
1544 }
1545 
1546 
1547 String *Item_func_substr_index::val_str(String *str)
1548 {
1549  DBUG_ASSERT(fixed == 1);
1550  char buff[MAX_FIELD_WIDTH];
1551  String tmp(buff,sizeof(buff),system_charset_info);
1552  String *res= args[0]->val_str(str);
1553  String *delimiter= args[1]->val_str(&tmp);
1554  int32 count= (int32) args[2]->val_int();
1555  int offset;
1556 
1557  if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
1558  { // string and/or delim are null
1559  null_value=1;
1560  return 0;
1561  }
1562  null_value=0;
1563  uint delimiter_length= delimiter->length();
1564  if (!res->length() || !delimiter_length || !count)
1565  return make_empty_result(); // Wrong parameters
1566 
1567  res->set_charset(collation.collation);
1568 
1569 #ifdef USE_MB
1570  if (use_mb(res->charset()))
1571  {
1572  const char *ptr= res->ptr();
1573  const char *strend= ptr+res->length();
1574  const char *end= strend-delimiter_length+1;
1575  const char *search= delimiter->ptr();
1576  const char *search_end= search+delimiter_length;
1577  int32 n=0,c=count,pass;
1578  register uint32 l;
1579  for (pass=(count>0);pass<2;++pass)
1580  {
1581  while (ptr < end)
1582  {
1583  if (*ptr == *search)
1584  {
1585  register char *i,*j;
1586  i=(char*) ptr+1; j=(char*) search+1;
1587  while (j != search_end)
1588  if (*i++ != *j++) goto skip;
1589  if (pass==0) ++n;
1590  else if (!--c) break;
1591  ptr+= delimiter_length;
1592  continue;
1593  }
1594  skip:
1595  if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
1596  else ++ptr;
1597  } /* either not found or got total number when count<0 */
1598  if (pass == 0) /* count<0 */
1599  {
1600  c+=n+1;
1601  if (c<=0) return res; /* not found, return original string */
1602  ptr=res->ptr();
1603  }
1604  else
1605  {
1606  if (c) return res; /* Not found, return original string */
1607  if (count>0) /* return left part */
1608  {
1609  tmp_value.set(*res,0,(ulong) (ptr-res->ptr()));
1610  }
1611  else /* return right part */
1612  {
1613  ptr+= delimiter_length;
1614  tmp_value.set(*res,(ulong) (ptr-res->ptr()), (ulong) (strend-ptr));
1615  }
1616  }
1617  }
1618  }
1619  else
1620 #endif /* USE_MB */
1621  {
1622  if (count > 0)
1623  { // start counting from the beginning
1624  for (offset=0; ; offset+= delimiter_length)
1625  {
1626  if ((offset= res->strstr(*delimiter, offset)) < 0)
1627  return res; // Didn't find, return org string
1628  if (!--count)
1629  {
1630  tmp_value.set(*res,0,offset);
1631  break;
1632  }
1633  }
1634  }
1635  else
1636  {
1637  /*
1638  Negative index, start counting at the end
1639  */
1640  for (offset=res->length(); offset; )
1641  {
1642  /*
1643  this call will result in finding the position pointing to one
1644  address space less than where the found substring is located
1645  in res
1646  */
1647  if ((offset= res->strrstr(*delimiter, offset)) < 0)
1648  return res; // Didn't find, return org string
1649  /*
1650  At this point, we've searched for the substring
1651  the number of times as supplied by the index value
1652  */
1653  if (!++count)
1654  {
1655  offset+= delimiter_length;
1656  tmp_value.set(*res,offset,res->length()- offset);
1657  break;
1658  }
1659  }
1660  if (count)
1661  return res; // Didn't find, return org string
1662  }
1663  }
1664  return (&tmp_value);
1665 }
1666 
1667 /*
1668 ** The trim functions are extension to ANSI SQL because they trim substrings
1669 ** They ltrim() and rtrim() functions are optimized for 1 byte strings
1670 ** They also return the original string if possible, else they return
1671 ** a substring that points at the original string.
1672 */
1673 
1674 
1675 String *Item_func_ltrim::val_str(String *str)
1676 {
1677  DBUG_ASSERT(fixed == 1);
1678  char buff[MAX_FIELD_WIDTH], *ptr, *end;
1679  String tmp(buff,sizeof(buff),system_charset_info);
1680  String *res, *remove_str;
1681  uint remove_length;
1682  LINT_INIT(remove_length);
1683 
1684  res= args[0]->val_str(str);
1685  if ((null_value=args[0]->null_value))
1686  return 0;
1687  remove_str= &remove; /* Default value. */
1688  if (arg_count == 2)
1689  {
1690  remove_str= args[1]->val_str(&tmp);
1691  if ((null_value= args[1]->null_value))
1692  return 0;
1693  }
1694 
1695  if ((remove_length= remove_str->length()) == 0 ||
1696  remove_length > res->length())
1697  return res;
1698 
1699  ptr= (char*) res->ptr();
1700  end= ptr+res->length();
1701  if (remove_length == 1)
1702  {
1703  char chr=(*remove_str)[0];
1704  while (ptr != end && *ptr == chr)
1705  ptr++;
1706  }
1707  else
1708  {
1709  const char *r_ptr=remove_str->ptr();
1710  end-=remove_length;
1711  while (ptr <= end && !memcmp(ptr, r_ptr, remove_length))
1712  ptr+=remove_length;
1713  end+=remove_length;
1714  }
1715  if (ptr == res->ptr())
1716  return res;
1717  tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
1718  return &tmp_value;
1719 }
1720 
1721 
1722 String *Item_func_rtrim::val_str(String *str)
1723 {
1724  DBUG_ASSERT(fixed == 1);
1725  char buff[MAX_FIELD_WIDTH], *ptr, *end;
1726  String tmp(buff, sizeof(buff), system_charset_info);
1727  String *res, *remove_str;
1728  uint remove_length;
1729  LINT_INIT(remove_length);
1730 
1731  res= args[0]->val_str(str);
1732  if ((null_value=args[0]->null_value))
1733  return 0;
1734  remove_str= &remove; /* Default value. */
1735  if (arg_count == 2)
1736  {
1737  remove_str= args[1]->val_str(&tmp);
1738  if ((null_value= args[1]->null_value))
1739  return 0;
1740  }
1741 
1742  if ((remove_length= remove_str->length()) == 0 ||
1743  remove_length > res->length())
1744  return res;
1745 
1746  ptr= (char*) res->ptr();
1747  end= ptr+res->length();
1748 #ifdef USE_MB
1749  char *p=ptr;
1750  register uint32 l;
1751 #endif
1752  if (remove_length == 1)
1753  {
1754  char chr=(*remove_str)[0];
1755 #ifdef USE_MB
1756  if (use_mb(res->charset()))
1757  {
1758  while (ptr < end)
1759  {
1760  if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l,p=ptr;
1761  else ++ptr;
1762  }
1763  ptr=p;
1764  }
1765 #endif
1766  while (ptr != end && end[-1] == chr)
1767  end--;
1768  }
1769  else
1770  {
1771  const char *r_ptr=remove_str->ptr();
1772 #ifdef USE_MB
1773  if (use_mb(res->charset()))
1774  {
1775  loop:
1776  while (ptr + remove_length < end)
1777  {
1778  if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
1779  else ++ptr;
1780  }
1781  if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
1782  {
1783  end-=remove_length;
1784  ptr=p;
1785  goto loop;
1786  }
1787  }
1788  else
1789 #endif /* USE_MB */
1790  {
1791  while (ptr + remove_length <= end &&
1792  !memcmp(end-remove_length, r_ptr, remove_length))
1793  end-=remove_length;
1794  }
1795  }
1796  if (end == res->ptr()+res->length())
1797  return res;
1798  tmp_value.set(*res,0,(uint) (end-res->ptr()));
1799  return &tmp_value;
1800 }
1801 
1802 
1803 String *Item_func_trim::val_str(String *str)
1804 {
1805  DBUG_ASSERT(fixed == 1);
1806  char buff[MAX_FIELD_WIDTH], *ptr, *end;
1807  const char *r_ptr;
1808  String tmp(buff, sizeof(buff), system_charset_info);
1809  String *res, *remove_str;
1810  uint remove_length;
1811  LINT_INIT(remove_length);
1812 
1813  res= args[0]->val_str(str);
1814  if ((null_value=args[0]->null_value))
1815  return 0;
1816  remove_str= &remove; /* Default value. */
1817  if (arg_count == 2)
1818  {
1819  remove_str= args[1]->val_str(&tmp);
1820  if ((null_value= args[1]->null_value))
1821  return 0;
1822  }
1823 
1824  if ((remove_length= remove_str->length()) == 0 ||
1825  remove_length > res->length())
1826  return res;
1827 
1828  ptr= (char*) res->ptr();
1829  end= ptr+res->length();
1830  r_ptr= remove_str->ptr();
1831  while (ptr+remove_length <= end && !memcmp(ptr,r_ptr,remove_length))
1832  ptr+=remove_length;
1833 #ifdef USE_MB
1834  if (use_mb(res->charset()))
1835  {
1836  char *p=ptr;
1837  register uint32 l;
1838  loop:
1839  while (ptr + remove_length < end)
1840  {
1841  if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
1842  else ++ptr;
1843  }
1844  if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
1845  {
1846  end-=remove_length;
1847  ptr=p;
1848  goto loop;
1849  }
1850  ptr=p;
1851  }
1852  else
1853 #endif /* USE_MB */
1854  {
1855  while (ptr + remove_length <= end &&
1856  !memcmp(end-remove_length,r_ptr,remove_length))
1857  end-=remove_length;
1858  }
1859  if (ptr == res->ptr() && end == ptr+res->length())
1860  return res;
1861  tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
1862  return &tmp_value;
1863 }
1864 
1865 void Item_func_trim::fix_length_and_dec()
1866 {
1867  if (arg_count == 1)
1868  {
1869  agg_arg_charsets_for_string_result(collation, args, 1);
1870  DBUG_ASSERT(collation.collation != NULL);
1871  remove.set_charset(collation.collation);
1872  remove.set_ascii(" ",1);
1873  }
1874  else
1875  {
1876  // Handle character set for args[1] and args[0].
1877  // Note that we pass args[1] as the first item, and args[0] as the second.
1878  if (agg_arg_charsets_for_string_result_with_comparison(collation,
1879  &args[1], 2, -1))
1880  return;
1881  }
1882  fix_char_length(args[0]->max_char_length());
1883 }
1884 
1885 void Item_func_trim::print(String *str, enum_query_type query_type)
1886 {
1887  if (arg_count == 1)
1888  {
1889  Item_func::print(str, query_type);
1890  return;
1891  }
1892  str->append(Item_func_trim::func_name());
1893  str->append('(');
1894  str->append(mode_name());
1895  str->append(' ');
1896  args[1]->print(str, query_type);
1897  str->append(STRING_WITH_LEN(" from "));
1898  args[0]->print(str, query_type);
1899  str->append(')');
1900 }
1901 
1902 
1915 static int calculate_password(String *str, char *buffer)
1916 {
1917  DBUG_ASSERT(str);
1918  if (str->length() == 0) // PASSWORD('') returns ''
1919  return 0;
1920 
1921  int buffer_len= 0;
1922  THD *thd= current_thd;
1923  int old_passwords= 0;
1924  if (thd)
1925  old_passwords= thd->variables.old_passwords;
1926 
1927 #if defined(HAVE_OPENSSL)
1928  if (old_passwords == 2)
1929  {
1930  my_make_scrambled_password(buffer, str->ptr(),
1931  str->length());
1932  buffer_len= (int) strlen(buffer) + 1;
1933  }
1934  else
1935 #endif
1936  if (old_passwords == 0)
1937  {
1938  my_make_scrambled_password_sha1(buffer, str->ptr(),
1939  str->length());
1940  buffer_len= SCRAMBLED_PASSWORD_CHAR_LENGTH;
1941  }
1942  else
1943  if (old_passwords == 1)
1944  {
1945  my_make_scrambled_password_323(buffer, str->ptr(),
1946  str->length());
1947  buffer_len= SCRAMBLED_PASSWORD_CHAR_LENGTH_323;
1948  }
1949  return buffer_len;
1950 }
1951 
1952 /* Item_func_password */
1953 void Item_func_password::fix_length_and_dec()
1954 {
1955  maybe_null= false; // PASSWORD() never returns NULL
1956 
1957  if (args[0]->const_item())
1958  {
1959  String str;
1960  String *res= args[0]->val_str(&str);
1961  if (!args[0]->null_value)
1962  {
1963  m_hashed_password_buffer_len=
1964  calculate_password(res, m_hashed_password_buffer);
1965  fix_length_and_charset(m_hashed_password_buffer_len, default_charset());
1966  m_recalculate_password= false;
1967  return;
1968  }
1969  }
1970 
1971  m_recalculate_password= true;
1972  fix_length_and_charset(CRYPT_MAX_PASSWORD_SIZE, default_charset());
1973 }
1974 
1975 String *Item_func_password::val_str_ascii(String *str)
1976 {
1977  DBUG_ASSERT(fixed == 1);
1978 
1979  String *res= args[0]->val_str(str);
1980 
1981  if (args[0]->null_value)
1982  res= make_empty_result();
1983 
1984  /* we treat NULLs as equal to empty string when calling the plugin */
1985  check_password_policy(res);
1986 
1987  null_value= 0;
1988  if (args[0]->null_value) // PASSWORD(NULL) returns ''
1989  return res;
1990 
1991  if (m_recalculate_password)
1992  m_hashed_password_buffer_len= calculate_password(res,
1993  m_hashed_password_buffer);
1994 
1995  if (m_hashed_password_buffer_len == 0)
1996  return make_empty_result();
1997 
1998  str->set(m_hashed_password_buffer, m_hashed_password_buffer_len,
1999  default_charset());
2000 
2001  return str;
2002 }
2003 
2004 char *Item_func_password::
2005  create_password_hash_buffer(THD *thd, const char *password, size_t pass_len)
2006 {
2007  String *password_str= new (thd->mem_root)String(password, thd->variables.
2008  character_set_client);
2009  check_password_policy(password_str);
2010 
2011  char *buff= NULL;
2012  if (thd->variables.old_passwords == 0)
2013  {
2014  /* Allocate memory for the password scramble and one extra byte for \0 */
2015  buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH + 1);
2016  my_make_scrambled_password_sha1(buff, password, pass_len);
2017  }
2018 #if defined(HAVE_OPENSSL)
2019  else
2020  {
2021  /* Allocate memory for the password scramble and one extra byte for \0 */
2022  buff= (char *) thd->alloc(CRYPT_MAX_PASSWORD_SIZE + 1);
2023  my_make_scrambled_password(buff, password, pass_len);
2024  }
2025 #endif
2026  return buff;
2027 }
2028 
2029 /* Item_func_old_password */
2030 
2031 String *Item_func_old_password::val_str_ascii(String *str)
2032 {
2033  String *res;
2034 
2035  DBUG_ASSERT(fixed == 1);
2036 
2037  res= args[0]->val_str(str);
2038 
2039  if ((null_value= args[0]->null_value))
2040  res= make_empty_result();
2041 
2042  /* we treat NULLs as equal to empty string when calling the plugin */
2043  check_password_policy(res);
2044 
2045  if (null_value)
2046  return 0;
2047 
2048  if (res->length() == 0)
2049  return make_empty_result();
2050 
2051  my_make_scrambled_password_323(tmp_value, res->ptr(), res->length());
2052  str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH_323, &my_charset_latin1);
2053  return str;
2054 }
2055 
2056 char *Item_func_old_password::alloc(THD *thd, const char *password,
2057  size_t pass_len)
2058 {
2059  char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH_323+1);
2060  if (buff)
2061  {
2062  String *password_str= new (thd->mem_root)String(password, thd->variables.
2063  character_set_client);
2064  check_password_policy(password_str);
2065  my_make_scrambled_password_323(buff, password, pass_len);
2066  }
2067  return buff;
2068 }
2069 
2070 
2071 #define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.')
2072 
2073 String *Item_func_encrypt::val_str(String *str)
2074 {
2075  DBUG_ASSERT(fixed == 1);
2076  String *res =args[0]->val_str(str);
2077 
2078 #ifdef HAVE_CRYPT
2079  char salt[3],*salt_ptr;
2080  if ((null_value=args[0]->null_value))
2081  return 0;
2082  if (res->length() == 0)
2083  return make_empty_result();
2084  if (arg_count == 1)
2085  { // generate random salt
2086  time_t timestamp=current_thd->query_start();
2087  salt[0] = bin_to_ascii( (ulong) timestamp & 0x3f);
2088  salt[1] = bin_to_ascii(( (ulong) timestamp >> 5) & 0x3f);
2089  salt[2] = 0;
2090  salt_ptr=salt;
2091  }
2092  else
2093  { // obtain salt from the first two bytes
2094  String *salt_str=args[1]->val_str(&tmp_value);
2095  if ((null_value= (args[1]->null_value || salt_str->length() < 2)))
2096  return 0;
2097  salt_ptr= salt_str->c_ptr_safe();
2098  }
2099  mysql_mutex_lock(&LOCK_crypt);
2100  char *tmp= crypt(res->c_ptr_safe(),salt_ptr);
2101  if (!tmp)
2102  {
2103  mysql_mutex_unlock(&LOCK_crypt);
2104  null_value= 1;
2105  return 0;
2106  }
2107  str->set(tmp, (uint) strlen(tmp), &my_charset_bin);
2108  str->copy();
2109  mysql_mutex_unlock(&LOCK_crypt);
2110  return str;
2111 #else
2112  null_value=1;
2113  return 0;
2114 #endif /* HAVE_CRYPT */
2115 }
2116 
2117 bool Item_func_encode::seed()
2118 {
2119  char buf[80];
2120  ulong rand_nr[2];
2121  String *key, tmp(buf, sizeof(buf), system_charset_info);
2122 
2123  if (!(key= args[1]->val_str(&tmp)))
2124  return TRUE;
2125 
2126  hash_password(rand_nr, key->ptr(), key->length());
2127  sql_crypt.init(rand_nr);
2128 
2129  return FALSE;
2130 }
2131 
2132 void Item_func_encode::fix_length_and_dec()
2133 {
2134  max_length=args[0]->max_length;
2135  maybe_null=args[0]->maybe_null || args[1]->maybe_null;
2136  collation.set(&my_charset_bin);
2137  /* Precompute the seed state if the item is constant. */
2138  seeded= args[1]->const_item() &&
2139  (args[1]->result_type() == STRING_RESULT) && !seed();
2140 }
2141 
2142 String *Item_func_encode::val_str(String *str)
2143 {
2144  String *res;
2145  DBUG_ASSERT(fixed == 1);
2146 
2147  if (!(res=args[0]->val_str(str)))
2148  {
2149  null_value= 1;
2150  return NULL;
2151  }
2152 
2153  if (!seeded && seed())
2154  {
2155  null_value= 1;
2156  return NULL;
2157  }
2158 
2159  null_value= 0;
2160  res= copy_if_not_alloced(str, res, res->length());
2161  crypto_transform(res);
2162  sql_crypt.reinit();
2163 
2164  return res;
2165 }
2166 
2167 void Item_func_encode::crypto_transform(String *res)
2168 {
2169  sql_crypt.encode((char*) res->ptr(),res->length());
2170  res->set_charset(&my_charset_bin);
2171 }
2172 
2173 void Item_func_decode::crypto_transform(String *res)
2174 {
2175  sql_crypt.decode((char*) res->ptr(),res->length());
2176 }
2177 
2178 
2179 Item *Item_func_sysconst::safe_charset_converter(const CHARSET_INFO *tocs)
2180 {
2181  Item_string *conv;
2182  uint conv_errors;
2183  String tmp, cstr, *ostr= val_str(&tmp);
2184  if (null_value)
2185  {
2186  Item *null_item= new Item_null(fully_qualified_func_name());
2187  null_item->collation.set (tocs);
2188  return null_item;
2189  }
2190  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
2191  if (conv_errors ||
2192  !(conv= new Item_static_string_func(fully_qualified_func_name(),
2193  cstr.ptr(), cstr.length(),
2194  cstr.charset(),
2195  collation.derivation)))
2196  {
2197  return NULL;
2198  }
2199  conv->str_value.copy();
2200  conv->str_value.mark_as_const();
2201  return conv;
2202 }
2203 
2204 
2205 String *Item_func_database::val_str(String *str)
2206 {
2207  DBUG_ASSERT(fixed == 1);
2208  THD *thd= current_thd;
2209  if (thd->db == NULL)
2210  {
2211  null_value= 1;
2212  return 0;
2213  }
2214  else
2215  str->copy(thd->db, thd->db_length, system_charset_info);
2216  return str;
2217 }
2218 
2219 
2225 bool Item_func_user::init(const char *user, const char *host)
2226 {
2227  DBUG_ASSERT(fixed == 1);
2228 
2229  // For system threads (e.g. replication SQL thread) user may be empty
2230  if (user)
2231  {
2232  const CHARSET_INFO *cs= str_value.charset();
2233  size_t res_length= (strlen(user)+strlen(host)+2) * cs->mbmaxlen;
2234 
2235  if (str_value.alloc((uint) res_length))
2236  {
2237  null_value=1;
2238  return TRUE;
2239  }
2240 
2241  res_length=cs->cset->snprintf(cs, (char*)str_value.ptr(), (uint) res_length,
2242  "%s@%s", user, host);
2243  str_value.length((uint) res_length);
2244  str_value.mark_as_const();
2245  }
2246  return FALSE;
2247 }
2248 
2249 
2250 bool Item_func_user::fix_fields(THD *thd, Item **ref)
2251 {
2252  return (Item_func_sysconst::fix_fields(thd, ref) ||
2253  init(thd->main_security_ctx.user,
2254  thd->main_security_ctx.host_or_ip));
2255 }
2256 
2257 
2258 bool Item_func_current_user::fix_fields(THD *thd, Item **ref)
2259 {
2260  if (Item_func_sysconst::fix_fields(thd, ref))
2261  return TRUE;
2262 
2263  Security_context *ctx=
2264 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2265  (context->security_ctx
2266  ? context->security_ctx : thd->security_ctx);
2267 #else
2268  thd->security_ctx;
2269 #endif /*NO_EMBEDDED_ACCESS_CHECKS*/
2270  return init(ctx->priv_user, ctx->priv_host);
2271 }
2272 
2273 
2274 void Item_func_soundex::fix_length_and_dec()
2275 {
2276  uint32 char_length= args[0]->max_char_length();
2277  agg_arg_charsets_for_string_result(collation, args, 1);
2278  DBUG_ASSERT(collation.collation != NULL);
2279  set_if_bigger(char_length, 4);
2280  fix_char_length(char_length);
2281  tmp_value.set_charset(collation.collation);
2282 }
2283 
2284 
2291 static int soundex_toupper(int ch)
2292 {
2293  return (ch >= 'a' && ch <= 'z') ? ch - 'a' + 'A' : ch;
2294 }
2295 
2296 
2297 static char get_scode(int wc)
2298 {
2299  int ch= soundex_toupper(wc);
2300  if (ch < 'A' || ch > 'Z')
2301  {
2302  // Thread extended alfa (country spec)
2303  return '0'; // as vokal
2304  }
2305  return(soundex_map[ch-'A']);
2306 }
2307 
2308 
2309 static bool my_uni_isalpha(int wc)
2310 {
2311  /*
2312  Return true for all Basic Latin letters: a..z A..Z.
2313  Return true for all Unicode characters with code higher than U+00C0:
2314  - characters between 'z' and U+00C0 are controls and punctuations.
2315  - "U+00C0 LATIN CAPITAL LETTER A WITH GRAVE" is the first letter after 'z'.
2316  */
2317  return (wc >= 'a' && wc <= 'z') ||
2318  (wc >= 'A' && wc <= 'Z') ||
2319  (wc >= 0xC0);
2320 }
2321 
2322 
2323 String *Item_func_soundex::val_str(String *str)
2324 {
2325  DBUG_ASSERT(fixed == 1);
2326  String *res =args[0]->val_str(str);
2327  char last_ch,ch;
2328  const CHARSET_INFO *cs= collation.collation;
2329  my_wc_t wc;
2330  uint nchars;
2331  int rc;
2332 
2333  if ((null_value= args[0]->null_value))
2334  return 0; /* purecov: inspected */
2335 
2336  if (tmp_value.alloc(max(res->length(), 4 * cs->mbminlen)))
2337  return str; /* purecov: inspected */
2338  char *to= (char *) tmp_value.ptr();
2339  char *to_end= to + tmp_value.alloced_length();
2340  char *from= (char *) res->ptr(), *end= from + res->length();
2341 
2342  for ( ; ; ) /* Skip pre-space */
2343  {
2344  if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
2345  return make_empty_result(); /* EOL or invalid byte sequence */
2346 
2347  if (rc == 1 && cs->ctype)
2348  {
2349  /* Single byte letter found */
2350  if (my_isalpha(cs, *from))
2351  {
2352  last_ch= get_scode(*from); // Code of the first letter
2353  *to++= soundex_toupper(*from++); // Copy first letter
2354  break;
2355  }
2356  from++;
2357  }
2358  else
2359  {
2360  from+= rc;
2361  if (my_uni_isalpha(wc))
2362  {
2363  /* Multibyte letter found */
2364  wc= soundex_toupper(wc);
2365  last_ch= get_scode(wc); // Code of the first letter
2366  if ((rc= cs->cset->wc_mb(cs, wc, (uchar*) to, (uchar*) to_end)) <= 0)
2367  {
2368  /* Extra safety - should not really happen */
2369  DBUG_ASSERT(false);
2370  return make_empty_result();
2371  }
2372  to+= rc;
2373  break;
2374  }
2375  }
2376  }
2377 
2378  /*
2379  last_ch is now set to the first 'double-letter' check.
2380  loop on input letters until end of input
2381  */
2382  for (nchars= 1 ; ; )
2383  {
2384  if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
2385  break; /* EOL or invalid byte sequence */
2386 
2387  if (rc == 1 && cs->ctype)
2388  {
2389  if (!my_isalpha(cs, *from++))
2390  continue;
2391  }
2392  else
2393  {
2394  from+= rc;
2395  if (!my_uni_isalpha(wc))
2396  continue;
2397  }
2398 
2399  ch= get_scode(wc);
2400  if ((ch != '0') && (ch != last_ch)) // if not skipped or double
2401  {
2402  // letter, copy to output
2403  if ((rc= cs->cset->wc_mb(cs, (my_wc_t) ch,
2404  (uchar*) to, (uchar*) to_end)) <= 0)
2405  {
2406  // Extra safety - should not really happen
2407  DBUG_ASSERT(false);
2408  break;
2409  }
2410  to+= rc;
2411  nchars++;
2412  last_ch= ch; // save code of last input letter
2413  } // for next double-letter check
2414  }
2415 
2416  /* Pad up to 4 characters with DIGIT ZERO, if the string is shorter */
2417  if (nchars < 4)
2418  {
2419  uint nbytes= (4 - nchars) * cs->mbminlen;
2420  cs->cset->fill(cs, to, nbytes, '0');
2421  to+= nbytes;
2422  }
2423 
2424  tmp_value.length((uint) (to-tmp_value.ptr()));
2425  return &tmp_value;
2426 }
2427 
2428 
2435 const int FORMAT_MAX_DECIMALS= 30;
2436 
2437 
2438 MY_LOCALE *Item_func_format::get_locale(Item *item)
2439 {
2440  DBUG_ASSERT(arg_count == 3);
2441  String tmp, *locale_name= args[2]->val_str_ascii(&tmp);
2442  MY_LOCALE *lc;
2443  if (!locale_name ||
2444  !(lc= my_locale_by_name(locale_name->c_ptr_safe())))
2445  {
2446  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
2447  ER_UNKNOWN_LOCALE,
2448  ER(ER_UNKNOWN_LOCALE),
2449  locale_name ? locale_name->c_ptr_safe() : "NULL");
2450  lc= &my_locale_en_US;
2451  }
2452  return lc;
2453 }
2454 
2455 void Item_func_format::fix_length_and_dec()
2456 {
2457  uint32 char_length= args[0]->max_char_length();
2458  uint32 max_sep_count= (char_length / 3) + (decimals ? 1 : 0) + /*sign*/1;
2459  collation.set(default_charset());
2460  fix_char_length(char_length + max_sep_count + decimals);
2461  if (arg_count == 3)
2462  locale= args[2]->basic_const_item() ? get_locale(args[2]) : NULL;
2463  else
2464  locale= &my_locale_en_US; /* Two arguments */
2465 }
2466 
2467 
2475 {
2476  uint32 str_length;
2477  /* Number of decimal digits */
2478  int dec;
2479  /* Number of characters used to represent the decimals, including '.' */
2480  uint32 dec_length;
2481  MY_LOCALE *lc;
2482  DBUG_ASSERT(fixed == 1);
2483 
2484  dec= (int) args[1]->val_int();
2485  if (args[1]->null_value)
2486  {
2487  null_value=1;
2488  return NULL;
2489  }
2490 
2491  lc= locale ? locale : get_locale(args[2]);
2492 
2493  dec= set_zone(dec, 0, FORMAT_MAX_DECIMALS);
2494  dec_length= dec ? dec+1 : 0;
2495  null_value=0;
2496 
2497  if (args[0]->result_type() == DECIMAL_RESULT ||
2498  args[0]->result_type() == INT_RESULT)
2499  {
2500  my_decimal dec_val, rnd_dec, *res;
2501  res= args[0]->val_decimal(&dec_val);
2502  if ((null_value=args[0]->null_value))
2503  return 0; /* purecov: inspected */
2504  my_decimal_round(E_DEC_FATAL_ERROR, res, dec, false, &rnd_dec);
2505  my_decimal2string(E_DEC_FATAL_ERROR, &rnd_dec, 0, 0, 0, str);
2506  str_length= str->length();
2507  }
2508  else
2509  {
2510  double nr= args[0]->val_real();
2511  if ((null_value=args[0]->null_value))
2512  return 0; /* purecov: inspected */
2513  nr= my_double_round(nr, (longlong) dec, FALSE, FALSE);
2514  str->set_real(nr, dec, &my_charset_numeric);
2515  if (isnan(nr) || my_isinf(nr))
2516  return str;
2517  str_length=str->length();
2518  }
2519  /* We need this test to handle 'nan' and short values */
2520  if (lc->grouping[0] > 0 &&
2521  str_length >= dec_length + 1 + lc->grouping[0])
2522  {
2523  /* We need space for ',' between each group of digits as well. */
2524  char buf[2 * FLOATING_POINT_BUFFER];
2525  int count;
2526  const char *grouping= lc->grouping;
2527  char sign_length= *str->ptr() == '-' ? 1 : 0;
2528  const char *src= str->ptr() + str_length - dec_length - 1;
2529  const char *src_begin= str->ptr() + sign_length;
2530  char *dst= buf + sizeof(buf);
2531 
2532  /* Put the fractional part */
2533  if (dec)
2534  {
2535  dst-= (dec + 1);
2536  *dst= lc->decimal_point;
2537  memcpy(dst + 1, src + 2, dec);
2538  }
2539 
2540  /* Put the integer part with grouping */
2541  for (count= *grouping; src >= src_begin; count--)
2542  {
2543  /*
2544  When *grouping==0x80 (which means "end of grouping")
2545  count will be initialized to -1 and
2546  we'll never get into this "if" anymore.
2547  */
2548  if (count == 0)
2549  {
2550  *--dst= lc->thousand_sep;
2551  if (grouping[1])
2552  grouping++;
2553  count= *grouping;
2554  }
2555  DBUG_ASSERT(dst > buf);
2556  *--dst= *src--;
2557  }
2558 
2559  if (sign_length) /* Put '-' */
2560  *--dst= *str->ptr();
2561 
2562  /* Put the rest of the integer part without grouping */
2563  str->copy(dst, buf + sizeof(buf) - dst, &my_charset_latin1);
2564  }
2565  else if (dec_length && lc->decimal_point != '.')
2566  {
2567  /*
2568  For short values without thousands (<1000)
2569  replace decimal point to localized value.
2570  */
2571  DBUG_ASSERT(dec_length <= str_length);
2572  ((char*) str->ptr())[str_length - dec_length]= lc->decimal_point;
2573  }
2574  return str;
2575 }
2576 
2577 
2578 void Item_func_format::print(String *str, enum_query_type query_type)
2579 {
2580  str->append(STRING_WITH_LEN("format("));
2581  args[0]->print(str, query_type);
2582  str->append(',');
2583  args[1]->print(str, query_type);
2584  if(arg_count > 2)
2585  {
2586  str->append(',');
2587  args[2]->print(str,query_type);
2588  }
2589  str->append(')');
2590 }
2591 
2592 void Item_func_elt::fix_length_and_dec()
2593 {
2594  uint32 char_length= 0;
2595  decimals=0;
2596 
2597  if (agg_arg_charsets_for_string_result(collation, args + 1, arg_count - 1))
2598  return;
2599 
2600  for (uint i= 1 ; i < arg_count ; i++)
2601  {
2602  set_if_bigger(char_length, args[i]->max_char_length());
2603  set_if_bigger(decimals,args[i]->decimals);
2604  }
2605  fix_char_length(char_length);
2606  maybe_null=1; // NULL if wrong first arg
2607 }
2608 
2609 
2610 double Item_func_elt::val_real()
2611 {
2612  DBUG_ASSERT(fixed == 1);
2613  uint tmp;
2614  null_value=1;
2615  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2616  return 0.0;
2617  double result= args[tmp]->val_real();
2618  null_value= args[tmp]->null_value;
2619  return result;
2620 }
2621 
2622 
2623 longlong Item_func_elt::val_int()
2624 {
2625  DBUG_ASSERT(fixed == 1);
2626  uint tmp;
2627  null_value=1;
2628  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2629  return 0;
2630 
2631  longlong result= args[tmp]->val_int();
2632  null_value= args[tmp]->null_value;
2633  return result;
2634 }
2635 
2636 
2637 String *Item_func_elt::val_str(String *str)
2638 {
2639  DBUG_ASSERT(fixed == 1);
2640  uint tmp;
2641  null_value=1;
2642  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2643  return NULL;
2644 
2645  String *result= args[tmp]->val_str(str);
2646  if (result)
2647  result->set_charset(collation.collation);
2648  null_value= args[tmp]->null_value;
2649  return result;
2650 }
2651 
2652 
2654  Ref_ptr_array ref_pointer_array,
2655  List<Item> &fields)
2656 {
2657  item->split_sum_func2(thd, ref_pointer_array, fields, &item, TRUE);
2658  Item_str_func::split_sum_func(thd, ref_pointer_array, fields);
2659 }
2660 
2661 
2662 void Item_func_make_set::fix_length_and_dec()
2663 {
2664  uint32 char_length= arg_count - 1; /* Separators */
2665 
2666  if (agg_arg_charsets_for_string_result(collation, args, arg_count))
2667  return;
2668 
2669  for (uint i=0 ; i < arg_count ; i++)
2670  char_length+= args[i]->max_char_length();
2671  fix_char_length(char_length);
2672  used_tables_cache|= item->used_tables();
2673  not_null_tables_cache&= item->not_null_tables();
2674  const_item_cache&= item->const_item();
2675  with_sum_func= with_sum_func || item->with_sum_func;
2676 }
2677 
2678 
2679 void Item_func_make_set::update_used_tables()
2680 {
2681  Item_func::update_used_tables();
2682  item->update_used_tables();
2683  used_tables_cache|=item->used_tables();
2684  const_item_cache&=item->const_item();
2685  with_subselect= item->has_subquery();
2686  with_stored_program= item->has_stored_program();
2687 }
2688 
2689 
2690 String *Item_func_make_set::val_str(String *str)
2691 {
2692  DBUG_ASSERT(fixed == 1);
2693  ulonglong bits;
2694  bool first_found=0;
2695  Item **ptr=args;
2696  String *result= NULL;
2697 
2698  bits=item->val_int();
2699  if ((null_value=item->null_value))
2700  return NULL;
2701 
2702  if (arg_count < 64)
2703  bits &= ((ulonglong) 1 << arg_count)-1;
2704 
2705  for (; bits; bits >>= 1, ptr++)
2706  {
2707  if (bits & 1)
2708  {
2709  String *res= (*ptr)->val_str(str);
2710  if (res) // Skip nulls
2711  {
2712  if (!first_found)
2713  { // First argument
2714  first_found=1;
2715  if (res != str)
2716  result=res; // Use original string
2717  else
2718  {
2719  if (tmp_str.copy(*res)) // Don't use 'str'
2720  return make_empty_result();
2721  result= &tmp_str;
2722  }
2723  }
2724  else
2725  {
2726  if (result != &tmp_str)
2727  { // Copy data to tmp_str
2728  if (tmp_str.alloc((result != NULL ? result->length() : 0) +
2729  res->length() + 1) ||
2730  tmp_str.copy(*result))
2731  return make_empty_result();
2732  result= &tmp_str;
2733  }
2734  if (tmp_str.append(STRING_WITH_LEN(","), &my_charset_bin) ||
2735  tmp_str.append(*res))
2736  return make_empty_result();
2737  }
2738  }
2739  }
2740  }
2741  if (result == NULL)
2742  return make_empty_result();
2743  return result;
2744 }
2745 
2746 
2747 Item *Item_func_make_set::transform(Item_transformer transformer, uchar *arg)
2748 {
2749  DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
2750 
2751  Item *new_item= item->transform(transformer, arg);
2752  if (!new_item)
2753  return 0;
2754 
2755  /*
2756  THD::change_item_tree() should be called only if the tree was
2757  really transformed, i.e. when a new item has been created.
2758  Otherwise we'll be allocating a lot of unnecessary memory for
2759  change records at each execution.
2760  */
2761  if (item != new_item)
2762  current_thd->change_item_tree(&item, new_item);
2763  return Item_str_func::transform(transformer, arg);
2764 }
2765 
2766 
2767 void Item_func_make_set::print(String *str, enum_query_type query_type)
2768 {
2769  str->append(STRING_WITH_LEN("make_set("));
2770  item->print(str, query_type);
2771  if (arg_count)
2772  {
2773  str->append(',');
2774  print_args(str, 0, query_type);
2775  }
2776  str->append(')');
2777 }
2778 
2779 
2780 String *Item_func_char::val_str(String *str)
2781 {
2782  DBUG_ASSERT(fixed == 1);
2783  str->length(0);
2784  str->set_charset(collation.collation);
2785  for (uint i=0 ; i < arg_count ; i++)
2786  {
2787  int32 num=(int32) args[i]->val_int();
2788  if (!args[i]->null_value)
2789  {
2790  char tmp[4];
2791  if (num & 0xFF000000L)
2792  {
2793  mi_int4store(tmp, num);
2794  str->append(tmp, 4, &my_charset_bin);
2795  }
2796  else if (num & 0xFF0000L)
2797  {
2798  mi_int3store(tmp, num);
2799  str->append(tmp, 3, &my_charset_bin);
2800  }
2801  else if (num & 0xFF00L)
2802  {
2803  mi_int2store(tmp, num);
2804  str->append(tmp, 2, &my_charset_bin);
2805  }
2806  else
2807  {
2808  tmp[0]= (char) num;
2809  str->append(tmp, 1, &my_charset_bin);
2810  }
2811  }
2812  }
2813  str->realloc(str->length()); // Add end 0 (for Purify)
2814  return check_well_formed_result(str);
2815 }
2816 
2817 
2818 inline String* alloc_buffer(String *res,String *str,String *tmp_value,
2819  ulong length)
2820 {
2821  if (res->alloced_length() < length)
2822  {
2823  if (str->alloced_length() >= length)
2824  {
2825  (void) str->copy(*res);
2826  str->length(length);
2827  return str;
2828  }
2829  if (tmp_value->alloc(length))
2830  return 0;
2831  (void) tmp_value->copy(*res);
2832  tmp_value->length(length);
2833  return tmp_value;
2834  }
2835  res->length(length);
2836  return res;
2837 }
2838 
2839 
2840 void Item_func_repeat::fix_length_and_dec()
2841 {
2842  agg_arg_charsets_for_string_result(collation, args, 1);
2843  DBUG_ASSERT(collation.collation != NULL);
2844  if (args[1]->const_item())
2845  {
2846  /* must be longlong to avoid truncation */
2847  longlong count= args[1]->val_int();
2848  if (args[1]->null_value)
2849  goto end;
2850 
2851  /* Assumes that the maximum length of a String is < INT_MAX32. */
2852  /* Set here so that rest of code sees out-of-bound value as such. */
2853  if (count > INT_MAX32)
2854  count= INT_MAX32;
2855 
2856  ulonglong char_length= (ulonglong) args[0]->max_char_length() * count;
2857  fix_char_length_ulonglong(char_length);
2858  return;
2859  }
2860 
2861 end:
2862  max_length= MAX_BLOB_WIDTH;
2863  maybe_null= 1;
2864 }
2865 
2872 {
2873  DBUG_ASSERT(fixed == 1);
2874  uint length,tot_length;
2875  char *to;
2876  /* must be longlong to avoid truncation */
2877  longlong count= args[1]->val_int();
2878  String *res= args[0]->val_str(str);
2879 
2880  if (args[0]->null_value || args[1]->null_value)
2881  goto err; // string and/or delim are null
2882  null_value= 0;
2883 
2884  if (count <= 0 && (count == 0 || !args[1]->unsigned_flag))
2885  return make_empty_result();
2886 
2887  /* Assumes that the maximum length of a String is < INT_MAX32. */
2888  /* Bounds check on count: If this is triggered, we will error. */
2889  if ((ulonglong) count > INT_MAX32)
2890  count= INT_MAX32;
2891  if (count == 1) // To avoid reallocs
2892  return res;
2893  length=res->length();
2894  // Safe length check
2895  if (length > current_thd->variables.max_allowed_packet / (uint) count)
2896  {
2897  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
2898  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2899  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
2900  func_name(), current_thd->variables.max_allowed_packet);
2901  goto err;
2902  }
2903  tot_length= length*(uint) count;
2904  if (!(res= alloc_buffer(res,str,&tmp_value,tot_length)))
2905  goto err;
2906 
2907  to=(char*) res->ptr()+length;
2908  while (--count)
2909  {
2910  memcpy(to,res->ptr(),length);
2911  to+=length;
2912  }
2913  return (res);
2914 
2915 err:
2916  null_value=1;
2917  return 0;
2918 }
2919 
2920 
2921 
2922 void Item_func_space::fix_length_and_dec()
2923 {
2924  collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII);
2925  if (args[0]->const_item())
2926  {
2927  /* must be longlong to avoid truncation */
2928  longlong count= args[0]->val_int();
2929  if (args[0]->null_value)
2930  goto end;
2931  /*
2932  Assumes that the maximum length of a String is < INT_MAX32.
2933  Set here so that rest of code sees out-of-bound value as such.
2934  */
2935  if (count > INT_MAX32)
2936  count= INT_MAX32;
2937  fix_char_length_ulonglong(count);
2938  return;
2939  }
2940 
2941 end:
2942  max_length= MAX_BLOB_WIDTH;
2943  maybe_null= 1;
2944 }
2945 
2946 
2947 String *Item_func_space::val_str(String *str)
2948 {
2949  uint tot_length;
2950  longlong count= args[0]->val_int();
2951  const CHARSET_INFO *cs= collation.collation;
2952 
2953  if (args[0]->null_value)
2954  goto err; // string and/or delim are null
2955  null_value= 0;
2956 
2957  if (count <= 0 && (count == 0 || !args[0]->unsigned_flag))
2958  return make_empty_result();
2959  /*
2960  Assumes that the maximum length of a String is < INT_MAX32.
2961  Bounds check on count: If this is triggered, we will error.
2962  */
2963  if ((ulonglong) count > INT_MAX32)
2964  count= INT_MAX32;
2965 
2966  // Safe length check
2967  tot_length= (uint) count * cs->mbminlen;
2968  if (tot_length > current_thd->variables.max_allowed_packet)
2969  {
2970  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
2971  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2972  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
2973  func_name(),
2974  current_thd->variables.max_allowed_packet);
2975  goto err;
2976  }
2977 
2978  if (str->alloc(tot_length))
2979  goto err;
2980  str->length(tot_length);
2981  str->set_charset(cs);
2982  cs->cset->fill(cs, (char*) str->ptr(), tot_length, ' ');
2983  return str;
2984 
2985 err:
2986  null_value= 1;
2987  return 0;
2988 }
2989 
2990 
2991 void Item_func_rpad::fix_length_and_dec()
2992 {
2993  // Handle character set for args[0] and args[2].
2994  if (agg_arg_charsets_for_string_result(collation, &args[0], 2, 2))
2995  return;
2996  if (args[1]->const_item())
2997  {
2998  ulonglong char_length= (ulonglong) args[1]->val_int();
2999  if (args[1]->null_value)
3000  goto end;
3001  DBUG_ASSERT(collation.collation->mbmaxlen > 0);
3002  /* Assumes that the maximum length of a String is < INT_MAX32. */
3003  /* Set here so that rest of code sees out-of-bound value as such. */
3004  if (char_length > INT_MAX32)
3005  char_length= INT_MAX32;
3006  fix_char_length_ulonglong(char_length);
3007  return;
3008  }
3009 
3010 end:
3011  max_length= MAX_BLOB_WIDTH;
3012  maybe_null= 1;
3013 }
3014 
3015 
3016 String *Item_func_rpad::val_str(String *str)
3017 {
3018  DBUG_ASSERT(fixed == 1);
3019  uint32 res_byte_length,res_char_length,pad_char_length,pad_byte_length;
3020  char *to;
3021  const char *ptr_pad;
3022  /* must be longlong to avoid truncation */
3023  longlong count= args[1]->val_int();
3024  longlong byte_count;
3025  String *res= args[0]->val_str(str);
3026  String *rpad= args[2]->val_str(&rpad_str);
3027 
3028  if (!res || args[1]->null_value || !rpad ||
3029  ((count < 0) && !args[1]->unsigned_flag))
3030  goto err;
3031  null_value=0;
3032  /* Assumes that the maximum length of a String is < INT_MAX32. */
3033  /* Set here so that rest of code sees out-of-bound value as such. */
3034  if ((ulonglong) count > INT_MAX32)
3035  count= INT_MAX32;
3036  /*
3037  There is one exception not handled (intentionaly) by the character set
3038  aggregation code. If one string is strong side and is binary, and
3039  another one is weak side and is a multi-byte character string,
3040  then we need to operate on the second string in terms on bytes when
3041  calling ::numchars() and ::charpos(), rather than in terms of characters.
3042  Lets substitute its character set to binary.
3043  */
3044  if (collation.collation == &my_charset_bin)
3045  {
3046  res->set_charset(&my_charset_bin);
3047  rpad->set_charset(&my_charset_bin);
3048  }
3049 
3050  if (count <= (res_char_length= res->numchars()))
3051  { // String to pad is big enough
3052  res->length(res->charpos((int) count)); // Shorten result if longer
3053  return (res);
3054  }
3055  pad_char_length= rpad->numchars();
3056 
3057  byte_count= count * collation.collation->mbmaxlen;
3058  if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
3059  {
3060  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3061  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3062  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3063  func_name(), current_thd->variables.max_allowed_packet);
3064  goto err;
3065  }
3066  if (args[2]->null_value || !pad_char_length)
3067  goto err;
3068  res_byte_length= res->length(); /* Must be done before alloc_buffer */
3069  if (!(res= alloc_buffer(res,str,&tmp_value, (ulong) byte_count)))
3070  goto err;
3071 
3072  to= (char*) res->ptr()+res_byte_length;
3073  ptr_pad=rpad->ptr();
3074  pad_byte_length= rpad->length();
3075  count-= res_char_length;
3076  for ( ; (uint32) count > pad_char_length; count-= pad_char_length)
3077  {
3078  memcpy(to,ptr_pad,pad_byte_length);
3079  to+= pad_byte_length;
3080  }
3081  if (count)
3082  {
3083  pad_byte_length= rpad->charpos((int) count);
3084  memcpy(to,ptr_pad,(size_t) pad_byte_length);
3085  to+= pad_byte_length;
3086  }
3087  res->length((uint) (to- (char*) res->ptr()));
3088  return (res);
3089 
3090  err:
3091  null_value=1;
3092  return 0;
3093 }
3094 
3095 
3096 void Item_func_lpad::fix_length_and_dec()
3097 {
3098  // Handle character set for args[0] and args[2].
3099  if (agg_arg_charsets_for_string_result(collation, &args[0], 2, 2))
3100  return;
3101 
3102  if (args[1]->const_item())
3103  {
3104  ulonglong char_length= (ulonglong) args[1]->val_int();
3105  if (args[1]->null_value)
3106  goto end;
3107  DBUG_ASSERT(collation.collation->mbmaxlen > 0);
3108  /* Assumes that the maximum length of a String is < INT_MAX32. */
3109  /* Set here so that rest of code sees out-of-bound value as such. */
3110  if (char_length > INT_MAX32)
3111  char_length= INT_MAX32;
3112  fix_char_length_ulonglong(char_length);
3113  return;
3114  }
3115 
3116 end:
3117  max_length= MAX_BLOB_WIDTH;
3118  maybe_null= 1;
3119 }
3120 
3121 
3122 String *Item_func_lpad::val_str(String *str)
3123 {
3124  DBUG_ASSERT(fixed == 1);
3125  uint32 res_char_length,pad_char_length;
3126  /* must be longlong to avoid truncation */
3127  longlong count= args[1]->val_int();
3128  longlong byte_count;
3129  String *res= args[0]->val_str(&tmp_value);
3130  String *pad= args[2]->val_str(&lpad_str);
3131 
3132  if (!res || args[1]->null_value || !pad ||
3133  ((count < 0) && !args[1]->unsigned_flag))
3134  goto err;
3135  null_value=0;
3136  /* Assumes that the maximum length of a String is < INT_MAX32. */
3137  /* Set here so that rest of code sees out-of-bound value as such. */
3138  if ((ulonglong) count > INT_MAX32)
3139  count= INT_MAX32;
3140 
3141  /*
3142  There is one exception not handled (intentionaly) by the character set
3143  aggregation code. If one string is strong side and is binary, and
3144  another one is weak side and is a multi-byte character string,
3145  then we need to operate on the second string in terms on bytes when
3146  calling ::numchars() and ::charpos(), rather than in terms of characters.
3147  Lets substitute its character set to binary.
3148  */
3149  if (collation.collation == &my_charset_bin)
3150  {
3151  res->set_charset(&my_charset_bin);
3152  pad->set_charset(&my_charset_bin);
3153  }
3154 
3155  res_char_length= res->numchars();
3156 
3157  if (count <= res_char_length)
3158  {
3159  res->length(res->charpos((int) count));
3160  return res;
3161  }
3162 
3163  pad_char_length= pad->numchars();
3164  byte_count= count * collation.collation->mbmaxlen;
3165 
3166  if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
3167  {
3168  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3169  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3170  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3171  func_name(), current_thd->variables.max_allowed_packet);
3172  goto err;
3173  }
3174 
3175  if (args[2]->null_value || !pad_char_length ||
3176  str->alloc((uint32) byte_count))
3177  goto err;
3178 
3179  str->length(0);
3180  str->set_charset(collation.collation);
3181  count-= res_char_length;
3182  while (count >= pad_char_length)
3183  {
3184  str->append(*pad);
3185  count-= pad_char_length;
3186  }
3187  if (count > 0)
3188  str->append(pad->ptr(), pad->charpos((int) count), collation.collation);
3189 
3190  str->append(*res);
3191  null_value= 0;
3192  return str;
3193 
3194 err:
3195  null_value= 1;
3196  return 0;
3197 }
3198 
3199 
3200 String *Item_func_conv::val_str(String *str)
3201 {
3202  DBUG_ASSERT(fixed == 1);
3203  String *res= args[0]->val_str(str);
3204  char *endptr,ans[65],*ptr;
3205  longlong dec;
3206  int from_base= (int) args[1]->val_int();
3207  int to_base= (int) args[2]->val_int();
3208  int err;
3209 
3210  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
3211  abs(to_base) > 36 || abs(to_base) < 2 ||
3212  abs(from_base) > 36 || abs(from_base) < 2 || !(res->length()))
3213  {
3214  null_value= 1;
3215  return NULL;
3216  }
3217  null_value= 0;
3218  unsigned_flag= !(from_base < 0);
3219 
3220  if (args[0]->field_type() == MYSQL_TYPE_BIT)
3221  {
3222  /*
3223  Special case: The string representation of BIT doesn't resemble the
3224  decimal representation, so we shouldn't change it to string and then to
3225  decimal.
3226  */
3227  dec= args[0]->val_int();
3228  }
3229  else
3230  {
3231  if (from_base < 0)
3232  dec= my_strntoll(res->charset(), res->ptr(), res->length(),
3233  -from_base, &endptr, &err);
3234  else
3235  dec= (longlong) my_strntoull(res->charset(), res->ptr(), res->length(),
3236  from_base, &endptr, &err);
3237  }
3238 
3239  if (!(ptr= longlong2str(dec, ans, to_base)) ||
3240  str->copy(ans, (uint32) (ptr - ans), default_charset()))
3241  {
3242  null_value= 1;
3243  return NULL;
3244  }
3245  return str;
3246 }
3247 
3248 
3249 String *Item_func_conv_charset::val_str(String *str)
3250 {
3251  DBUG_ASSERT(fixed == 1);
3252  if (use_cached_value)
3253  return null_value ? 0 : &str_value;
3254  String *arg= args[0]->val_str(str);
3255  uint dummy_errors;
3256  if (!arg)
3257  {
3258  null_value=1;
3259  return 0;
3260  }
3261  null_value= tmp_value.copy(arg->ptr(), arg->length(), arg->charset(),
3262  conv_charset, &dummy_errors);
3263  return null_value ? 0 : check_well_formed_result(&tmp_value);
3264 }
3265 
3266 void Item_func_conv_charset::fix_length_and_dec()
3267 {
3268  collation.set(conv_charset, DERIVATION_IMPLICIT);
3269  fix_char_length(args[0]->max_char_length());
3270 }
3271 
3272 void Item_func_conv_charset::print(String *str, enum_query_type query_type)
3273 {
3274  str->append(STRING_WITH_LEN("convert("));
3275  args[0]->print(str, query_type);
3276  str->append(STRING_WITH_LEN(" using "));
3277  str->append(conv_charset->csname);
3278  str->append(')');
3279 }
3280 
3281 String *Item_func_set_collation::val_str(String *str)
3282 {
3283  DBUG_ASSERT(fixed == 1);
3284  str=args[0]->val_str(str);
3285  if ((null_value=args[0]->null_value))
3286  return 0;
3287  str->set_charset(collation.collation);
3288  return str;
3289 }
3290 
3291 void Item_func_set_collation::fix_length_and_dec()
3292 {
3293  CHARSET_INFO *set_collation;
3294  const char *colname;
3295  String tmp, *str= args[1]->val_str(&tmp);
3296  colname= str->c_ptr();
3297  if (colname == binary_keyword)
3298  set_collation= get_charset_by_csname(args[0]->collation.collation->csname,
3299  MY_CS_BINSORT,MYF(0));
3300  else
3301  {
3302  if (!(set_collation= mysqld_collation_get_by_name(colname)))
3303  return;
3304  }
3305 
3306  if (!set_collation ||
3307  !my_charset_same(args[0]->collation.collation,set_collation))
3308  {
3309  my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0),
3310  colname, args[0]->collation.collation->csname);
3311  return;
3312  }
3313  collation.set(set_collation, DERIVATION_EXPLICIT,
3314  args[0]->collation.repertoire);
3315  max_length= args[0]->max_length;
3316 }
3317 
3318 
3319 bool Item_func_set_collation::eq(const Item *item, bool binary_cmp) const
3320 {
3321  /* Assume we don't have rtti */
3322  if (this == item)
3323  return 1;
3324  if (item->type() != FUNC_ITEM)
3325  return 0;
3326  Item_func *item_func=(Item_func*) item;
3327  if (arg_count != item_func->arg_count ||
3328  functype() != item_func->functype())
3329  return 0;
3330  Item_func_set_collation *item_func_sc=(Item_func_set_collation*) item;
3331  if (collation.collation != item_func_sc->collation.collation)
3332  return 0;
3333  for (uint i=0; i < arg_count ; i++)
3334  if (!args[i]->eq(item_func_sc->args[i], binary_cmp))
3335  return 0;
3336  return 1;
3337 }
3338 
3339 
3340 void Item_func_set_collation::print(String *str, enum_query_type query_type)
3341 {
3342  str->append('(');
3343  args[0]->print(str, query_type);
3344  str->append(STRING_WITH_LEN(" collate "));
3345  DBUG_ASSERT(args[1]->basic_const_item() &&
3346  args[1]->type() == Item::STRING_ITEM);
3347  args[1]->str_value.print(str);
3348  str->append(')');
3349 }
3350 
3351 String *Item_func_charset::val_str(String *str)
3352 {
3353  DBUG_ASSERT(fixed == 1);
3354  uint dummy_errors;
3355 
3356  const CHARSET_INFO *cs= args[0]->charset_for_protocol();
3357  null_value= 0;
3358  str->copy(cs->csname, (uint) strlen(cs->csname),
3359  &my_charset_latin1, collation.collation, &dummy_errors);
3360  return str;
3361 }
3362 
3363 String *Item_func_collation::val_str(String *str)
3364 {
3365  DBUG_ASSERT(fixed == 1);
3366  uint dummy_errors;
3367  const CHARSET_INFO *cs= args[0]->charset_for_protocol();
3368 
3369  null_value= 0;
3370  str->copy(cs->name, (uint) strlen(cs->name),
3371  &my_charset_latin1, collation.collation, &dummy_errors);
3372  return str;
3373 }
3374 
3375 
3376 void Item_func_weight_string::fix_length_and_dec()
3377 {
3378  const CHARSET_INFO *cs= args[0]->collation.collation;
3379  collation.set(&my_charset_bin, args[0]->collation.derivation);
3380  flags= my_strxfrm_flag_normalize(flags, cs->levels_for_order);
3381  field= args[0]->type() == FIELD_ITEM && args[0]->is_temporal() ?
3382  ((Item_field *) (args[0]))->field : (Field *) NULL;
3383  /*
3384  Use result_length if it was given explicitly in constructor,
3385  otherwise calculate max_length using argument's max_length
3386  and "nweights".
3387  */
3388  max_length= field ? field->pack_length() :
3389  result_length ? result_length :
3390  cs->mbmaxlen * max(args[0]->max_length, nweights);
3391  maybe_null= 1;
3392 }
3393 
3394 
3395 /* Return a weight_string according to collation */
3396 String *Item_func_weight_string::val_str(String *str)
3397 {
3398  String *res;
3399  const CHARSET_INFO *cs= args[0]->collation.collation;
3400  uint tmp_length, frm_length;
3401  DBUG_ASSERT(fixed == 1);
3402 
3403  if (args[0]->result_type() != STRING_RESULT ||
3404  !(res= args[0]->val_str(str)))
3405  goto nl;
3406 
3407  /*
3408  Use result_length if it was given in constructor
3409  explicitly, otherwise calculate result length
3410  from argument and "nweights".
3411  */
3412  tmp_length= field ? field->pack_length() :
3413  result_length ? result_length :
3414  cs->coll->strnxfrmlen(cs, cs->mbmaxlen *
3415  max(res->length(), nweights));
3416 
3417  if(tmp_length > current_thd->variables.max_allowed_packet)
3418  {
3419  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3420  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3421  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
3422  current_thd->variables.max_allowed_packet);
3423  goto nl;
3424  }
3425 
3426  if (tmp_value.alloc(tmp_length))
3427  goto nl;
3428 
3429  if (field)
3430  {
3431  frm_length= field->pack_length();
3432  field->make_sort_key((uchar *) tmp_value.ptr(), tmp_length);
3433  }
3434  else
3435  frm_length= cs->coll->strnxfrm(cs,
3436  (uchar *) tmp_value.ptr(), tmp_length,
3437  nweights ? nweights : tmp_length,
3438  (const uchar *) res->ptr(), res->length(),
3439  flags);
3440  tmp_value.length(frm_length);
3441  null_value= 0;
3442  return &tmp_value;
3443 
3444 nl:
3445  null_value= 1;
3446  return 0;
3447 }
3448 
3449 
3450 String *Item_func_hex::val_str_ascii(String *str)
3451 {
3452  String *res;
3453  DBUG_ASSERT(fixed == 1);
3454  if (args[0]->result_type() != STRING_RESULT)
3455  {
3456  ulonglong dec;
3457  char ans[65],*ptr;
3458  /* Return hex of unsigned longlong value */
3459  if (args[0]->result_type() == REAL_RESULT ||
3460  args[0]->result_type() == DECIMAL_RESULT)
3461  {
3462  double val= args[0]->val_real();
3463  if ((val <= (double) LONGLONG_MIN) ||
3464  (val >= (double) (ulonglong) ULONGLONG_MAX))
3465  dec= ~(longlong) 0;
3466  else
3467  dec= (ulonglong) (val + (val > 0 ? 0.5 : -0.5));
3468  }
3469  else
3470  dec= (ulonglong) args[0]->val_int();
3471 
3472  if ((null_value= args[0]->null_value))
3473  return 0;
3474 
3475  if (!(ptr= longlong2str(dec, ans, 16)) ||
3476  str->copy(ans,(uint32) (ptr - ans),
3477  &my_charset_numeric))
3478  return make_empty_result(); // End of memory
3479  return str;
3480  }
3481 
3482  /* Convert given string to a hex string, character by character */
3483  res= args[0]->val_str(str);
3484  if (!res || tmp_value.alloc(res->length()*2+1))
3485  {
3486  null_value=1;
3487  return 0;
3488  }
3489  null_value=0;
3490  tmp_value.length(res->length()*2);
3491  tmp_value.set_charset(&my_charset_latin1);
3492 
3493  octet2hex((char*) tmp_value.ptr(), res->ptr(), res->length());
3494  return &tmp_value;
3495 }
3496 
3500 {
3501  const char *from, *end;
3502  char *to;
3503  String *res;
3504  uint length;
3505  DBUG_ASSERT(fixed == 1);
3506 
3507  res= args[0]->val_str(str);
3508  if (!res || tmp_value.alloc(length= (1+res->length())/2))
3509  {
3510  null_value=1;
3511  return 0;
3512  }
3513 
3514  from= res->ptr();
3515  null_value= 0;
3516  tmp_value.length(length);
3517  to= (char*) tmp_value.ptr();
3518  if (res->length() % 2)
3519  {
3520  int hex_char;
3521  *to++= hex_char= hexchar_to_int(*from++);
3522  if ((null_value= (hex_char == -1)))
3523  return 0;
3524  }
3525  for (end=res->ptr()+res->length(); from < end ; from+=2, to++)
3526  {
3527  int hex_char;
3528  *to= (hex_char= hexchar_to_int(from[0])) << 4;
3529  if ((null_value= (hex_char == -1)))
3530  return 0;
3531  *to|= hex_char= hexchar_to_int(from[1]);
3532  if ((null_value= (hex_char == -1)))
3533  return 0;
3534  }
3535  return &tmp_value;
3536 }
3537 
3538 
3539 #ifndef DBUG_OFF
3540 String *Item_func_like_range::val_str(String *str)
3541 {
3542  DBUG_ASSERT(fixed == 1);
3543  longlong nbytes= args[1]->val_int();
3544  String *res= args[0]->val_str(str);
3545  size_t min_len, max_len;
3546  const CHARSET_INFO *cs= collation.collation;
3547 
3548  if (!res || args[0]->null_value || args[1]->null_value ||
3549  nbytes < 0 || nbytes > MAX_BLOB_WIDTH ||
3550  min_str.alloc(nbytes) || max_str.alloc(nbytes))
3551  goto err;
3552  null_value=0;
3553 
3554  if (cs->coll->like_range(cs, res->ptr(), res->length(),
3555  '\\', '_', '%', nbytes,
3556  (char*) min_str.ptr(), (char*) max_str.ptr(),
3557  &min_len, &max_len))
3558  goto err;
3559 
3560  min_str.set_charset(collation.collation);
3561  max_str.set_charset(collation.collation);
3562  min_str.length(min_len);
3563  max_str.length(max_len);
3564 
3565  return is_min ? &min_str : &max_str;
3566 
3567 err:
3568  null_value= 1;
3569  return 0;
3570 }
3571 #endif
3572 
3573 
3574 bool Item_char_typecast::eq(const Item *item, bool binary_cmp) const
3575 {
3576  if (this == item)
3577  return 1;
3578  if (item->type() != FUNC_ITEM ||
3579  functype() != ((Item_func*)item)->functype())
3580  return 0;
3581 
3582  Item_char_typecast *cast= (Item_char_typecast*)item;
3583  if (cast_length != cast->cast_length ||
3584  cast_cs != cast->cast_cs)
3585  return 0;
3586 
3587  if (!args[0]->eq(cast->args[0], binary_cmp))
3588  return 0;
3589  return 1;
3590 }
3591 
3592 
3593 void Item_char_typecast::print(String *str, enum_query_type query_type)
3594 {
3595  str->append(STRING_WITH_LEN("cast("));
3596  args[0]->print(str, query_type);
3597  str->append(STRING_WITH_LEN(" as char"));
3598  if (cast_length >= 0)
3599  str->append_parenthesized(cast_length);
3600  if (cast_cs)
3601  {
3602  str->append(STRING_WITH_LEN(" charset "));
3603  str->append(cast_cs->csname);
3604  }
3605  str->append(')');
3606 }
3607 
3608 
3609 String *Item_char_typecast::val_str(String *str)
3610 {
3611  DBUG_ASSERT(fixed == 1);
3612  String *res;
3613  uint32 length;
3614 
3615  if (cast_length >= 0 &&
3616  ((unsigned) cast_length) > current_thd->variables.max_allowed_packet)
3617  {
3618  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3619  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3620  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3621  cast_cs == &my_charset_bin ?
3622  "cast_as_binary" : func_name(),
3623  current_thd->variables.max_allowed_packet);
3624  null_value= 1;
3625  return 0;
3626  }
3627 
3628  if (!charset_conversion)
3629  {
3630  if (!(res= args[0]->val_str(str)))
3631  {
3632  null_value= 1;
3633  return 0;
3634  }
3635  }
3636  else
3637  {
3638  // Convert character set if differ
3639  uint dummy_errors;
3640  if (!(res= args[0]->val_str(str)) ||
3641  tmp_value.copy(res->ptr(), res->length(), from_cs,
3642  cast_cs, &dummy_errors))
3643  {
3644  null_value= 1;
3645  return 0;
3646  }
3647  res= &tmp_value;
3648  }
3649 
3650  res->set_charset(cast_cs);
3651 
3652  /*
3653  Cut the tail if cast with length
3654  and the result is longer than cast length, e.g.
3655  CAST('string' AS CHAR(1))
3656  */
3657  if (cast_length >= 0)
3658  {
3659  if (res->length() > (length= (uint32) res->charpos(cast_length)))
3660  { // Safe even if const arg
3661  char char_type[40];
3662  my_snprintf(char_type, sizeof(char_type), "%s(%lu)",
3663  cast_cs == &my_charset_bin ? "BINARY" : "CHAR",
3664  (ulong) length);
3665 
3666  if (!res->alloced_length())
3667  { // Don't change const str
3668  str_value= *res; // Not malloced string
3669  res= &str_value;
3670  }
3671  ErrConvString err(res);
3672  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3673  ER_TRUNCATED_WRONG_VALUE,
3674  ER(ER_TRUNCATED_WRONG_VALUE), char_type,
3675  err.ptr());
3676  res->length((uint) length);
3677  }
3678  else if (cast_cs == &my_charset_bin && res->length() < (uint) cast_length)
3679  {
3680  if (res->alloced_length() < (uint) cast_length)
3681  {
3682  str_value.alloc(cast_length);
3683  str_value.copy(*res);
3684  res= &str_value;
3685  }
3686  memset(const_cast<char*>(res->ptr() + res->length()), 0,
3687  cast_length - res->length());
3688  res->length(cast_length);
3689  }
3690  }
3691  null_value= 0;
3692  return res;
3693 }
3694 
3695 
3696 void Item_char_typecast::fix_length_and_dec()
3697 {
3698  /*
3699  If we convert between two ASCII compatible character sets and the
3700  argument repertoire is MY_REPERTOIRE_ASCII then from_cs is set to cast_cs.
3701  This allows just to take over the args[0]->val_str() result
3702  and thus avoid unnecessary character set conversion.
3703  */
3704  from_cs= args[0]->collation.repertoire == MY_REPERTOIRE_ASCII &&
3705  my_charset_is_ascii_based(cast_cs) &&
3706  my_charset_is_ascii_based(args[0]->collation.collation) ?
3707  cast_cs : args[0]->collation.collation;
3708 
3709 
3710  collation.set(cast_cs, DERIVATION_IMPLICIT);
3711  fix_char_length(cast_length >= 0 ? cast_length :
3712  cast_cs == &my_charset_bin ? args[0]->max_length :
3713  args[0]->max_char_length());
3714 
3715  /*
3716  We always force character set conversion if cast_cs
3717  is a multi-byte character set. It garantees that the
3718  result of CAST is a well-formed string.
3719  For single-byte character sets we allow just to copy from the argument.
3720  A single-byte character sets string is always well-formed.
3721  */
3722  charset_conversion= (cast_cs->mbmaxlen > 1) ||
3723  (!my_charset_same(from_cs, cast_cs) &&
3724  from_cs != &my_charset_bin &&
3725  cast_cs != &my_charset_bin);
3726 }
3727 
3728 
3729 void Item_func_binary::print(String *str, enum_query_type query_type)
3730 {
3731  str->append(STRING_WITH_LEN("cast("));
3732  args[0]->print(str, query_type);
3733  str->append(STRING_WITH_LEN(" as binary)"));
3734 }
3735 
3736 
3737 #include <my_dir.h> // For my_stat
3738 
3739 String *Item_load_file::val_str(String *str)
3740 {
3741  DBUG_ASSERT(fixed == 1);
3742  String *file_name;
3743  File file;
3744  MY_STAT stat_info;
3745  char path[FN_REFLEN];
3746  DBUG_ENTER("load_file");
3747 
3748  if (!(file_name= args[0]->val_str(str))
3749 #ifndef NO_EMBEDDED_ACCESS_CHECKS
3750  || !(current_thd->security_ctx->master_access & FILE_ACL)
3751 #endif
3752  )
3753  goto err;
3754 
3755  (void) fn_format(path, file_name->c_ptr_safe(), mysql_real_data_home, "",
3756  MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
3757 
3758  /* Read only allowed from within dir specified by secure_file_priv */
3759  if (!is_secure_file_path(path))
3760  goto err;
3761 
3762  if (!mysql_file_stat(key_file_loadfile, path, &stat_info, MYF(0)))
3763  goto err;
3764 
3765  if (!(stat_info.st_mode & S_IROTH))
3766  {
3767  /* my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr()); */
3768  goto err;
3769  }
3770  if (stat_info.st_size > (long) current_thd->variables.max_allowed_packet)
3771  {
3772  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3773  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3774  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3775  func_name(), current_thd->variables.max_allowed_packet);
3776  goto err;
3777  }
3778  if (tmp_value.alloc(stat_info.st_size))
3779  goto err;
3780  if ((file= mysql_file_open(key_file_loadfile,
3781  file_name->ptr(), O_RDONLY, MYF(0))) < 0)
3782  goto err;
3783  if (mysql_file_read(file, (uchar*) tmp_value.ptr(), stat_info.st_size,
3784  MYF(MY_NABP)))
3785  {
3786  mysql_file_close(file, MYF(0));
3787  goto err;
3788  }
3789  tmp_value.length(stat_info.st_size);
3790  mysql_file_close(file, MYF(0));
3791  null_value = 0;
3792  DBUG_RETURN(&tmp_value);
3793 
3794 err:
3795  null_value = 1;
3796  DBUG_RETURN(0);
3797 }
3798 
3799 
3800 String* Item_func_export_set::val_str(String* str)
3801 {
3802  DBUG_ASSERT(fixed == 1);
3803  String yes_buf, no_buf, sep_buf;
3804  const ulonglong the_set = (ulonglong) args[0]->val_int();
3805  const String *yes= args[1]->val_str(&yes_buf);
3806  const String *no= args[2]->val_str(&no_buf);
3807  const String *sep= NULL;
3808 
3809  uint num_set_values = 64;
3810  str->length(0);
3811  str->set_charset(collation.collation);
3812 
3813  /* Check if some argument is a NULL value */
3814  if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
3815  {
3816  null_value= true;
3817  return NULL;
3818  }
3819  /*
3820  Arg count can only be 3, 4 or 5 here. This is guaranteed from the
3821  grammar for EXPORT_SET()
3822  */
3823  switch(arg_count) {
3824  case 5:
3825  num_set_values = (uint) args[4]->val_int();
3826  if (num_set_values > 64)
3827  num_set_values=64;
3828  if (args[4]->null_value)
3829  {
3830  null_value= true;
3831  return NULL;
3832  }
3833  /* Fall through */
3834  case 4:
3835  if (!(sep = args[3]->val_str(&sep_buf))) // Only true if NULL
3836  {
3837  null_value= true;
3838  return NULL;
3839  }
3840  break;
3841  case 3:
3842  {
3843  /* errors is not checked - assume "," can always be converted */
3844  uint errors;
3845  sep_buf.copy(STRING_WITH_LEN(","), &my_charset_bin,
3846  collation.collation, &errors);
3847  sep = &sep_buf;
3848  }
3849  break;
3850  default:
3851  DBUG_ASSERT(0); // cannot happen
3852  }
3853  null_value= false;
3854 
3855  const ulong max_allowed_packet= current_thd->variables.max_allowed_packet;
3856  const uint num_separators= num_set_values > 0 ? num_set_values - 1 : 0;
3857  const ulonglong max_total_length=
3858  num_set_values * max(yes->length(), no->length()) +
3859  num_separators * sep->length();
3860 
3861  if (unlikely(max_total_length > max_allowed_packet))
3862  {
3863  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3864  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3865  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3866  func_name(), max_allowed_packet);
3867  null_value= true;
3868  return NULL;
3869  }
3870 
3871  uint ix;
3872  ulonglong mask;
3873  for (ix= 0, mask=0x1; ix < num_set_values; ++ix, mask = (mask << 1))
3874  {
3875  if (the_set & mask)
3876  str->append(*yes);
3877  else
3878  str->append(*no);
3879  if (ix != num_separators)
3880  str->append(*sep);
3881  }
3882  return str;
3883 }
3884 
3885 void Item_func_export_set::fix_length_and_dec()
3886 {
3887  uint32 length= max(args[1]->max_char_length(), args[2]->max_char_length());
3888  uint32 sep_length= (arg_count > 3 ? args[3]->max_char_length() : 1);
3889 
3890  if (agg_arg_charsets_for_string_result(collation,
3891  args + 1, min(4U, arg_count) - 1))
3892  return;
3893  fix_char_length(length * 64 + sep_length * 63);
3894 }
3895 
3896 
3897 #define get_esc_bit(mask, num) (1 & (*((mask) + ((num) >> 3))) >> ((num) & 7))
3898 
3919 {
3920  DBUG_ASSERT(fixed == 1);
3921  /*
3922  Bit mask that has 1 for set for the position of the following characters:
3923  0, \, ' and ^Z
3924  */
3925 
3926  static uchar escmask[32]=
3927  {
3928  0x01, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00,
3929  0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,
3930  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3931  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
3932  };
3933 
3934  char *from, *to, *end, *start;
3935  String *arg= args[0]->val_str(str);
3936  uint arg_length, new_length;
3937  if (!arg) // Null argument
3938  {
3939  /* Return the string 'NULL' */
3940  str->copy(STRING_WITH_LEN("NULL"), collation.collation);
3941  null_value= 0;
3942  return str;
3943  }
3944 
3945  arg_length= arg->length();
3946 
3947  if (collation.collation->mbmaxlen == 1)
3948  {
3949  new_length= arg_length + 2; /* for beginning and ending ' signs */
3950  for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
3951  new_length+= get_esc_bit(escmask, (uchar) *from);
3952  }
3953  else
3954  {
3955  new_length= (arg_length * 2) + /* For string characters */
3956  (2 * collation.collation->mbmaxlen); /* For quotes */
3957  }
3958 
3959  if (tmp_value.alloc(new_length))
3960  goto null;
3961 
3962  if (collation.collation->mbmaxlen > 1)
3963  {
3964  const CHARSET_INFO *cs= collation.collation;
3965  int mblen;
3966  uchar *to_end;
3967  to= (char*) tmp_value.ptr();
3968  to_end= (uchar*) to + new_length;
3969 
3970  /* Put leading quote */
3971  if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
3972  goto null;
3973  to+= mblen;
3974 
3975  for (start= (char*) arg->ptr(), end= start + arg_length; start < end; )
3976  {
3977  my_wc_t wc;
3978  bool escape;
3979  if ((mblen= cs->cset->mb_wc(cs, &wc, (uchar*) start, (uchar*) end)) <= 0)
3980  goto null;
3981  start+= mblen;
3982  switch (wc) {
3983  case 0: escape= 1; wc= '0'; break;
3984  case '\032': escape= 1; wc= 'Z'; break;
3985  case '\'': escape= 1; break;
3986  case '\\': escape= 1; break;
3987  default: escape= 0; break;
3988  }
3989  if (escape)
3990  {
3991  if ((mblen= cs->cset->wc_mb(cs, '\\', (uchar*) to, to_end)) <= 0)
3992  goto null;
3993  to+= mblen;
3994  }
3995  if ((mblen= cs->cset->wc_mb(cs, wc, (uchar*) to, to_end)) <= 0)
3996  goto null;
3997  to+= mblen;
3998  }
3999 
4000  /* Put trailing quote */
4001  if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
4002  goto null;
4003  to+= mblen;
4004  new_length= to - tmp_value.ptr();
4005  goto ret;
4006  }
4007 
4008  /*
4009  We replace characters from the end to the beginning
4010  */
4011  to= (char*) tmp_value.ptr() + new_length - 1;
4012  *to--= '\'';
4013  for (start= (char*) arg->ptr(),end= start + arg_length; end-- != start; to--)
4014  {
4015  /*
4016  We can't use the bitmask here as we want to replace \O and ^Z with 0
4017  and Z
4018  */
4019  switch (*end) {
4020  case 0:
4021  *to--= '0';
4022  *to= '\\';
4023  break;
4024  case '\032':
4025  *to--= 'Z';
4026  *to= '\\';
4027  break;
4028  case '\'':
4029  case '\\':
4030  *to--= *end;
4031  *to= '\\';
4032  break;
4033  default:
4034  *to= *end;
4035  break;
4036  }
4037  }
4038  *to= '\'';
4039 
4040 ret:
4041  tmp_value.length(new_length);
4042  tmp_value.set_charset(collation.collation);
4043  null_value= 0;
4044  return &tmp_value;
4045 
4046 null:
4047  null_value= 1;
4048  return 0;
4049 }
4050 
4051 longlong Item_func_uncompressed_length::val_int()
4052 {
4053  DBUG_ASSERT(fixed == 1);
4054  String *res= args[0]->val_str(&value);
4055  if (!res)
4056  {
4057  null_value=1;
4058  return 0; /* purecov: inspected */
4059  }
4060  null_value=0;
4061  if (res->is_empty()) return 0;
4062 
4063  /*
4064  If length is <= 4 bytes, data is corrupt. This is the best we can do
4065  to detect garbage input without decompressing it.
4066  */
4067  if (res->length() <= 4)
4068  {
4069  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
4070  ER_ZLIB_Z_DATA_ERROR,
4071  ER(ER_ZLIB_Z_DATA_ERROR));
4072  null_value= 1;
4073  return 0;
4074  }
4075 
4076  /*
4077  res->ptr() using is safe because we have tested that string is at least
4078  5 bytes long.
4079  res->c_ptr() is not used because:
4080  - we do not need \0 terminated string to get first 4 bytes
4081  - c_ptr() tests simbol after string end (uninitialiozed memory) which
4082  confuse valgrind
4083  */
4084  return uint4korr(res->ptr()) & 0x3FFFFFFF;
4085 }
4086 
4087 longlong Item_func_crc32::val_int()
4088 {
4089  DBUG_ASSERT(fixed == 1);
4090  String *res=args[0]->val_str(&value);
4091  if (!res)
4092  {
4093  null_value=1;
4094  return 0; /* purecov: inspected */
4095  }
4096  null_value=0;
4097  return (longlong) crc32(0L, (uchar*)res->ptr(), res->length());
4098 }
4099 
4100 #ifdef HAVE_COMPRESS
4101 #include "zlib.h"
4102 
4103 String *Item_func_compress::val_str(String *str)
4104 {
4105  int err= Z_OK, code;
4106  ulong new_size;
4107  String *res;
4108  Byte *body;
4109  char *tmp, *last_char;
4110  DBUG_ASSERT(fixed == 1);
4111 
4112  if (!(res= args[0]->val_str(str)))
4113  {
4114  null_value= 1;
4115  return 0;
4116  }
4117  null_value= 0;
4118  if (res->is_empty()) return res;
4119 
4120  /*
4121  Citation from zlib.h (comment for compress function):
4122 
4123  Compresses the source buffer into the destination buffer. sourceLen is
4124  the byte length of the source buffer. Upon entry, destLen is the total
4125  size of the destination buffer, which must be at least 0.1% larger than
4126  sourceLen plus 12 bytes.
4127  We assume here that the buffer can't grow more than .25 %.
4128  */
4129  new_size= res->length() + res->length() / 5 + 12;
4130 
4131  // Check new_size overflow: new_size <= res->length()
4132  if (((uint32) (new_size+5) <= res->length()) ||
4133  buffer.realloc((uint32) new_size + 4 + 1))
4134  {
4135  null_value= 1;
4136  return 0;
4137  }
4138 
4139  body= ((Byte*)buffer.ptr()) + 4;
4140 
4141  // As far as we have checked res->is_empty() we can use ptr()
4142  if ((err= compress(body, &new_size,
4143  (const Bytef*)res->ptr(), res->length())) != Z_OK)
4144  {
4145  code= err==Z_MEM_ERROR ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_BUF_ERROR;
4146  push_warning(current_thd,Sql_condition::WARN_LEVEL_WARN,code,ER(code));
4147  null_value= 1;
4148  return 0;
4149  }
4150 
4151  tmp= (char*)buffer.ptr(); // int4store is a macro; avoid side effects
4152  int4store(tmp, res->length() & 0x3FFFFFFF);
4153 
4154  /* This is to ensure that things works for CHAR fields, which trim ' ': */
4155  last_char= ((char*)body)+new_size-1;
4156  if (*last_char == ' ')
4157  {
4158  *++last_char= '.';
4159  new_size++;
4160  }
4161 
4162  buffer.length((uint32)new_size + 4);
4163  return &buffer;
4164 }
4165 
4166 
4167 String *Item_func_uncompress::val_str(String *str)
4168 {
4169  DBUG_ASSERT(fixed == 1);
4170  String *res= args[0]->val_str(str);
4171  ulong new_size;
4172  int err;
4173  uint code;
4174 
4175  if (!res)
4176  goto err;
4177  null_value= 0;
4178  if (res->is_empty())
4179  return res;
4180 
4181  /* If length is less than 4 bytes, data is corrupt */
4182  if (res->length() <= 4)
4183  {
4184  push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
4185  ER_ZLIB_Z_DATA_ERROR,
4186  ER(ER_ZLIB_Z_DATA_ERROR));
4187  goto err;
4188  }
4189 
4190  /* Size of uncompressed data is stored as first 4 bytes of field */
4191  new_size= uint4korr(res->ptr()) & 0x3FFFFFFF;
4192  if (new_size > current_thd->variables.max_allowed_packet)
4193  {
4194  push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
4195  ER_TOO_BIG_FOR_UNCOMPRESS,
4196  ER(ER_TOO_BIG_FOR_UNCOMPRESS),
4197  static_cast<int>(current_thd->variables.
4198  max_allowed_packet));
4199  goto err;
4200  }
4201  if (buffer.realloc((uint32)new_size))
4202  goto err;
4203 
4204  if ((err= uncompress((Byte*)buffer.ptr(), &new_size,
4205  ((const Bytef*)res->ptr())+4,res->length())) == Z_OK)
4206  {
4207  buffer.length((uint32) new_size);
4208  return &buffer;
4209  }
4210 
4211  code= ((err == Z_BUF_ERROR) ? ER_ZLIB_Z_BUF_ERROR :
4212  ((err == Z_MEM_ERROR) ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_DATA_ERROR));
4213  push_warning(current_thd,Sql_condition::WARN_LEVEL_WARN,code,ER(code));
4214 
4215 err:
4216  null_value= 1;
4217  return 0;
4218 }
4219 #endif
4220 
4221 /*
4222  UUID, as in
4223  DCE 1.1: Remote Procedure Call,
4224  Open Group Technical Standard Document Number C706, October 1997,
4225  (supersedes C309 DCE: Remote Procedure Call 8/1994,
4226  which was basis for ISO/IEC 11578:1996 specification)
4227 */
4228 
4229 static struct rand_struct uuid_rand;
4230 static uint nanoseq;
4231 static ulonglong uuid_time=0;
4232 static char clock_seq_and_node_str[]="-0000-000000000000";
4233 
4238 #define UUID_TIME_OFFSET ((ulonglong) 141427 * 24 * 60 * 60 * \
4239  1000 * 1000 * 10)
4240 
4241 #define UUID_VERSION 0x1000
4242 #define UUID_VARIANT 0x8000
4243 
4244 static void tohex(char *to, uint from, uint len)
4245 {
4246  to+= len;
4247  while (len--)
4248  {
4249  *--to= _dig_vec_lower[from & 15];
4250  from >>= 4;
4251  }
4252 }
4253 
4254 static void set_clock_seq_str()
4255 {
4256  uint16 clock_seq= ((uint)(my_rnd(&uuid_rand)*16383)) | UUID_VARIANT;
4257  tohex(clock_seq_and_node_str+1, clock_seq, 4);
4258  nanoseq= 0;
4259 }
4260 
4261 String *Item_func_uuid::val_str(String *str)
4262 {
4263  DBUG_ASSERT(fixed == 1);
4264  char *s;
4265  THD *thd= current_thd;
4266 
4267  mysql_mutex_lock(&LOCK_uuid_generator);
4268  if (! uuid_time) /* first UUID() call. initializing data */
4269  {
4270  ulong tmp=sql_rnd_with_mutex();
4271  uchar mac[6];
4272  int i;
4273  if (my_gethwaddr(mac))
4274  {
4275  /* purecov: begin inspected */
4276  /*
4277  generating random "hardware addr"
4278  and because specs explicitly specify that it should NOT correlate
4279  with a clock_seq value (initialized random below), we use a separate
4280  randominit() here
4281  */
4282  randominit(&uuid_rand, tmp + (ulong) thd, tmp + (ulong)global_query_id);
4283  for (i=0; i < (int)sizeof(mac); i++)
4284  mac[i]=(uchar)(my_rnd(&uuid_rand)*255);
4285  /* purecov: end */
4286  }
4287  s=clock_seq_and_node_str+sizeof(clock_seq_and_node_str)-1;
4288  for (i=sizeof(mac)-1 ; i>=0 ; i--)
4289  {
4290  *--s=_dig_vec_lower[mac[i] & 15];
4291  *--s=_dig_vec_lower[mac[i] >> 4];
4292  }
4293  randominit(&uuid_rand, tmp + (ulong) server_start_time,
4294  tmp + (ulong) thd->status_var.bytes_sent);
4295  set_clock_seq_str();
4296  }
4297 
4298  ulonglong tv= my_getsystime() + UUID_TIME_OFFSET + nanoseq;
4299 
4300  if (likely(tv > uuid_time))
4301  {
4302  /*
4303  Current time is ahead of last timestamp, as it should be.
4304  If we "borrowed time", give it back, just as long as we
4305  stay ahead of the previous timestamp.
4306  */
4307  if (nanoseq)
4308  {
4309  DBUG_ASSERT((tv > uuid_time) && (nanoseq > 0));
4310  /*
4311  -1 so we won't make tv= uuid_time for nanoseq >= (tv - uuid_time)
4312  */
4313  ulong delta= min<ulong>(nanoseq, (ulong) (tv - uuid_time -1));
4314  tv-= delta;
4315  nanoseq-= delta;
4316  }
4317  }
4318  else
4319  {
4320  if (unlikely(tv == uuid_time))
4321  {
4322  /*
4323  For low-res system clocks. If several requests for UUIDs
4324  end up on the same tick, we add a nano-second to make them
4325  different.
4326  ( current_timestamp + nanoseq * calls_in_this_period )
4327  may end up > next_timestamp; this is OK. Nonetheless, we'll
4328  try to unwind nanoseq when we get a chance to.
4329  If nanoseq overflows, we'll start over with a new numberspace
4330  (so the if() below is needed so we can avoid the ++tv and thus
4331  match the follow-up if() if nanoseq overflows!).
4332  */
4333  if (likely(++nanoseq))
4334  ++tv;
4335  }
4336 
4337  if (unlikely(tv <= uuid_time))
4338  {
4339  /*
4340  If the admin changes the system clock (or due to Daylight
4341  Saving Time), the system clock may be turned *back* so we
4342  go through a period once more for which we already gave out
4343  UUIDs. To avoid duplicate UUIDs despite potentially identical
4344  times, we make a new random component.
4345  We also come here if the nanoseq "borrowing" overflows.
4346  In either case, we throw away any nanoseq borrowing since it's
4347  irrelevant in the new numberspace.
4348  */
4349  set_clock_seq_str();
4350  tv= my_getsystime() + UUID_TIME_OFFSET;
4351  nanoseq= 0;
4352  DBUG_PRINT("uuid",("making new numberspace"));
4353  }
4354  }
4355 
4356  uuid_time=tv;
4357  mysql_mutex_unlock(&LOCK_uuid_generator);
4358 
4359  uint32 time_low= (uint32) (tv & 0xFFFFFFFF);
4360  uint16 time_mid= (uint16) ((tv >> 32) & 0xFFFF);
4361  uint16 time_hi_and_version= (uint16) ((tv >> 48) | UUID_VERSION);
4362 
4363  str->realloc(UUID_LENGTH+1);
4364  str->length(UUID_LENGTH);
4365  str->set_charset(system_charset_info);
4366  s=(char *) str->ptr();
4367  s[8]=s[13]='-';
4368  tohex(s, time_low, 8);
4369  tohex(s+9, time_mid, 4);
4370  tohex(s+14, time_hi_and_version, 4);
4371  strmov(s+18, clock_seq_and_node_str);
4372  return str;
4373 }
4374 
4375 
4376 void Item_func_gtid_subtract::fix_length_and_dec()
4377 {
4378  maybe_null= args[0]->maybe_null || args[1]->maybe_null;
4379  collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII);
4380  /*
4381  In the worst case, the string grows after subtraction. This
4382  happens when a GTID in args[0] is split by a GTID in args[1],
4383  e.g., UUID:1-6 minus UUID:3-4 becomes UUID:1-2,5-6. The worst
4384  case is UUID:1-100 minus UUID:9, where the two characters ":9" in
4385  args[1] yield the five characters "-8,10" in the result.
4386  */
4387  fix_char_length_ulonglong(args[0]->max_length +
4388  max<ulonglong>(args[1]->max_length -
4389  Uuid::TEXT_LENGTH, 0) * 5 / 2);
4390 }
4391 
4392 
4393 String *Item_func_gtid_subtract::val_str_ascii(String *str)
4394 {
4395  DBUG_ENTER("Item_func_gtid_subtract::val_str_ascii");
4396  String *str1, *str2;
4397  const char *charp1, *charp2;
4398  enum_return_status status;
4399  /*
4400  We must execute args[*]->val_str_ascii() before checking
4401  args[*]->null_value to ensure that them are updated when
4402  this function is executed inside a stored procedure.
4403  */
4404  if ((str1= args[0]->val_str_ascii(&buf1)) != NULL &&
4405  (charp1= str1->c_ptr_safe()) != NULL &&
4406  (str2= args[1]->val_str_ascii(&buf2)) != NULL &&
4407  (charp2= str2->c_ptr_safe()) != NULL &&
4408  !args[0]->null_value && !args[1]->null_value)
4409  {
4410  Sid_map sid_map(NULL/*no rwlock*/);
4411  // compute sets while holding locks
4412  Gtid_set set1(&sid_map, charp1, &status);
4413  if (status == RETURN_STATUS_OK)
4414  {
4415  Gtid_set set2(&sid_map, charp2, &status);
4416  int length;
4417  // subtract, save result, return result
4418  if (status == RETURN_STATUS_OK &&
4419  set1.remove_gtid_set(&set2) == 0 &&
4420  !str->realloc((length= set1.get_string_length()) + 1))
4421  {
4422  null_value= false;
4423  set1.to_string((char *)str->ptr());
4424  str->length(length);
4425  DBUG_RETURN(str);
4426  }
4427  }
4428  }
4429  null_value= true;
4430  DBUG_RETURN(NULL);
4431 }