File: srv_session.cc

package info (click to toggle)
mysql-8.0 8.0.43-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,924 kB
  • sloc: cpp: 4,684,605; ansic: 412,450; pascal: 108,398; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; sh: 24,181; python: 21,816; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,076; makefile: 2,194; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (1287 lines) | stat: -rw-r--r-- 35,893 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
/*  Copyright (c) 2015, 2025, Oracle and/or its affiliates.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License, version 2.0,
   as published by the Free Software Foundation.

   This program is designed to work with certain software (including
   but not limited to OpenSSL) that is licensed under separate terms,
   as designated in a particular file or component or in included license
   documentation.  The authors of MySQL hereby grant you an additional
   permission to link the program and your derivative works with the
   separately licensed software that they have either included with
   the program or referenced in the documentation.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License, version 2.0, for more details.

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

#include "sql/srv_session.h"

#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <atomic>
#include <list>
#include <map>
#include <new>
#include <utility>

#include "lex_string.h"
#include "m_ctype.h"
#include "m_string.h"
#include "mutex_lock.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_loglevel.h"
#include "my_macros.h"
#include "my_psi_config.h"
#include "my_thread.h"
#include "my_thread_local.h"  // my_get_thread_local & my_set_thread_local
#include "mysql.h"
#include "mysql/components/my_service.h"
#include "mysql/components/services/bits/mysql_mutex_bits.h"
#include "mysql/components/services/bits/mysql_rwlock_bits.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/components/services/bits/psi_mutex_bits.h"
#include "mysql/components/services/bits/psi_rwlock_bits.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/plugin_audit.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql/psi/mysql_rwlock.h"
#include "mysql/psi/mysql_statement.h"
#include "mysql_time.h"
#include "mysqld_error.h"
#include "pfs_thread_provider.h"
#include "rwlock_scoped_lock.h"
#include "sql/auth/sql_security_ctx.h"
#include "sql/conn_handler/connection_handler_manager.h"
#include "sql/current_thd.h"
#include "sql/debug_sync.h"          // DEBUG_SYNC
#include "sql/derror.h"              // ER_DEFAULT
#include "sql/log.h"                 // Query log
#include "sql/mysqld.h"              // current_thd
#include "sql/mysqld_thd_manager.h"  // Global_THD_manager
#include "sql/sql_audit.h"           // MYSQL_AUDIT_NOTIFY_CONNECTION_CONNECT
#include "sql/sql_base.h"            // close_mysql_tables
#include "sql/sql_class.h"
#include "sql/sql_connect.h"  // thd_init_client_charset
#include "sql/sql_list.h"
#include "sql/sql_parse.h"  // dispatch_command()
#include "sql/sql_plugin_ref.h"
#include "sql/sql_thd_internal_api.h"  // thd_set_thread_stack
#include "sql/system_variables.h"
#include "thr_mutex.h"

struct decimal_t;

/**
  @file
  class Srv_session implementation. See the method comments for more. Please,
  check also srv_session.h for more information.
*/

extern void thd_clear_errors(THD *thd);

static thread_local const char *THR_stack_start_address = nullptr;
static thread_local const st_plugin_int *THR_srv_session_thread = nullptr;
static bool srv_session_THRs_initialized = false;

class Thread_to_plugin_map {
 private:
  bool initted;
  bool psi_initted;
  mysql_mutex_t LOCK_collection;

#ifdef HAVE_PSI_INTERFACE
  PSI_mutex_key key_LOCK_collection;
#endif
  std::map<my_thread_t, const void *> collection;

 public:
  /**
    Initializes the map

    @return
      false  success
      true   failure
  */
  bool init() {
    const char *category = "session";
    PSI_mutex_info all_mutexes[] = {{&key_LOCK_collection,
                                     "LOCK_srv_session_threads",
                                     PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME}};

    initted = true;
#ifdef HAVE_PSI_INTERFACE
    psi_initted = true;

    mysql_mutex_register(category, all_mutexes,
                         static_cast<int>(array_elements(all_mutexes)));
#endif
    mysql_mutex_init(key_LOCK_collection, &LOCK_collection, MY_MUTEX_INIT_FAST);

    return false;
  }

  /**
    Deinitializes the map

    @return
      false  success
      true   failure
  */
  bool deinit() {
    initted = false;
    mysql_mutex_destroy(&LOCK_collection);

    return false;
  }

  /**
    Adds a pthread to the list

    @return
      false  success
      true   failure
  */
  bool add(my_thread_t thread, const void *plugin) {
    MUTEX_LOCK(lock, &LOCK_collection);
    try {
      std::map<my_thread_t, const void *>::iterator it =
          collection.find(thread);
      if (it == collection.end()) collection[thread] = plugin;
    } catch (const std::bad_alloc &) {
      return true;
    }
    return false;
  }

  /**
    Removes a pthread from the list

    @param thread  Thread to remove from the list

    @return
      false  success
      true   failure
  */
  unsigned int remove(my_thread_t thread) {
    MUTEX_LOCK(lock, &LOCK_collection);
    std::map<my_thread_t, const void *>::iterator it = collection.find(thread);
    if (it != collection.end()) {
      collection.erase(it);
      return false;
    }
    return true;
  }

  /**
    Empties the map

    @return
      false  success
      true   failure
  */
  bool clear() {
    MUTEX_LOCK(lock, &LOCK_collection);
    collection.clear();
    return false;
  }

  /**
    Returns the number of all threads
  */
  unsigned int size() {
    MUTEX_LOCK(lock, &LOCK_collection);
    return collection.size();
  }

  /**
    Returns the number threads for a plugin

    @param plugin The plugin for which we need info.
  */
  unsigned int count(const void *plugin) {
    if (!plugin) return size();

    unsigned int ret = 0;
    MUTEX_LOCK(lock, &LOCK_collection);
    std::map<my_thread_t, const void *>::iterator it = collection.begin();
    for (; it != collection.end(); ++it) {
      if (it->second == plugin) ++ret;
    }
    return ret;
  }

  /**
    Kills all threads associated with a plugin

    @param plugin The plugin for which we need info.
  */
  unsigned int kill(const void *plugin) {
    std::list<my_thread_t> to_remove;

    MUTEX_LOCK(lock, &LOCK_collection);

    for (std::map<my_thread_t, const void *>::iterator it = collection.begin();
         it != collection.end(); ++it) {
      if (!plugin || (it->second == plugin)) {
        to_remove.push_back(it->first);

#ifndef _WIN32
        my_thread_handle thread;
        /*
           On Windows we need HANDLE to cancel a thread.
           Win32 API's GetCurrentThread() returns something which seems the
           same in every thread, thus unusable as a key.
           GetCurrentThreadId returns an ID (DWORD), but it can't be used with
           my_thread_cancel() which calls TerminateThread() on Windows.
           TerminateThread() needs a Handle.
           Therefore this killing functionality is now only for Posix Threads
           until there is a solution for Windows.
        */
        thread.thread = it->first;
        LogErr(ERROR_LEVEL, ER_KILLING_THREAD, (unsigned long)it->first);
        if (!my_thread_cancel(&thread)) {
          void *dummy_retval;
          my_thread_join(&thread, &dummy_retval);
        }
#endif
      }
    }
    if (to_remove.size()) {
      for (std::list<my_thread_t>::iterator it = to_remove.begin();
           it != to_remove.end(); ++it)
        collection.erase(*it);
    }
    return to_remove.size();
  }
};

/**
 std::map of THD* as key and Srv_session* as value guarded by a read-write lock.
 RW lock is used instead of a mutex, as find() is a hot spot due to the sanity
 checks it is used for - when a pointer to a closed session is passed.
*/
class Mutexed_map_thd_srv_session {
 public:
  class Do_Impl {
   public:
    virtual ~Do_Impl() = default;
    /**
      Work on the session

      @return
        false  Leave the session in the map
        true   Remove the session from the map
    */
    virtual bool operator()(Srv_session *) = 0;
  };

 private:
  /*
    The first type in the tuple should be the key type of
    Thread_to_plugin_map
  */
  typedef std::pair<const void *, Srv_session *> map_value_t;

  std::map<const THD *, map_value_t> collection;

  bool initted;
  bool psi_initted;

  mysql_rwlock_t LOCK_collection;

#ifdef HAVE_PSI_INTERFACE
  PSI_rwlock_key key_LOCK_collection;
#endif

 public:
  /**
    Initializes the map

    @return
      false  success
      true   failure
  */
  bool init() {
    const char *category = "session";
    PSI_rwlock_info all_rwlocks[] = {{&key_LOCK_collection,
                                      "LOCK_srv_session_collection",
                                      PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME}};

    initted = true;
#ifdef HAVE_PSI_INTERFACE
    psi_initted = true;

    mysql_rwlock_register(category, all_rwlocks,
                          static_cast<int>(array_elements(all_rwlocks)));
#endif
    mysql_rwlock_init(key_LOCK_collection, &LOCK_collection);

    return false;
  }

  /**
    Deinitializes the map

    @return
      false  success
      true   failure
  */
  bool deinit() {
    initted = false;
    mysql_rwlock_destroy(&LOCK_collection);

    return false;
  }

  /**
    Searches for an element with in the map

    @param key Key of the element

    @return value of the element
    @retval NULL  if not found
  */
  Srv_session *find(const THD *key) {
    rwlock_scoped_lock lock(&LOCK_collection, false, __FILE__, __LINE__);

    std::map<const THD *, map_value_t>::iterator it = collection.find(key);
    return (it != collection.end()) ? it->second.second : NULL;
  }

  /**
    Add an element to the map

    @param key     key
    @param plugin  secondary key
    @param session object to be added to the collection

    @retval false  success
    @retval true   failure
  */
  bool add(const THD *key, const void *plugin, Srv_session *session) {
    rwlock_scoped_lock lock(&LOCK_collection, true, __FILE__, __LINE__);
    try {
      collection[key] = std::make_pair(plugin, session);
    } catch (const std::bad_alloc &) {
      return true;
    }
    return false;
  }

  /**
    Removes an element from the map.

    @param key  key

    @return
      false  success
      true   failure
  */
  bool remove(const THD *key) {
    rwlock_scoped_lock lock(&LOCK_collection, true, __FILE__, __LINE__);
    /*
      If we use erase with the key directly an exception could be thrown. The
      find method never throws. erase() with iterator as parameter also never
      throws.
    */
    std::map<const THD *, map_value_t>::iterator it = collection.find(key);
    if (it != collection.end()) collection.erase(it);
    return false;
  }

  /**
    Removes all elements which have been added with plugin as plugin name.

    @param plugin key
    @param removed OUT Number of removed elements
  */
  void remove_all_of_plugin(const void *plugin, unsigned int &removed) {
    std::list<Srv_session *> to_close;
    removed = 0;

    {
      rwlock_scoped_lock lock(&LOCK_collection, true, __FILE__, __LINE__);

      for (std::map<const THD *, map_value_t>::iterator it = collection.begin();
           it != collection.end(); ++it) {
        if (it->second.first == plugin) to_close.push_back(it->second.second);
      }
    }

    /* Outside of the lock as Srv_session::close() will try to
      remove itself from the list*/
    if ((removed = to_close.size())) {
      for (std::list<Srv_session *>::iterator it = to_close.begin();
           it != to_close.end(); ++it) {
        Srv_session *session = *it;
        session->detach();
        session->close();
        delete session;
      }
    }
  }

  /**
    Empties the map

    @return
      false  success
      true   failure
  */
  bool clear() {
    rwlock_scoped_lock lock(&LOCK_collection, true, __FILE__, __LINE__);
    collection.clear();
    return false;
  }

  /**
    Returns the number of elements in the maps
  */
  unsigned int size() {
    rwlock_scoped_lock lock(&LOCK_collection, false, __FILE__, __LINE__);
    return collection.size();
  }
};

static Mutexed_map_thd_srv_session server_session_list;
static Thread_to_plugin_map server_session_threads;

Srv_session::Session_backup_and_attach::Session_backup_and_attach(
    Srv_session *sess, bool is_in_close_session)
    : session(sess),
      old_session(nullptr),
      in_close_session(is_in_close_session) {
  THD *c_thd = current_thd;
  backup_thd = c_thd;
  bool is_plugin = false;

  if (session->is_associate()) {
    attach_error = session->associate();
    return;
  }

  /*
    Check whether the current thread and the one we're going to switch to,
    belong to a plugin and if the plugin is the same (so we can reuse the thd).
  */
  if (THR_srv_session_thread && c_thd &&
      c_thd->get_plugin() == session->m_thd->get_plugin()) {
    is_plugin = true;
    backup_thd = nullptr;
  }

  if (is_plugin && c_thd != session->m_thd &&
      (old_session = server_session_list.find(c_thd))) {
    old_session->detach();
  } else if (is_plugin) {
    assert(session->is_attached());
  }

  attach_error = session->attach();
}

Srv_session::Session_backup_and_attach::~Session_backup_and_attach() {
  if (session->is_associated()) {
    session->disassociate();
    if (backup_thd && backup_thd != session->m_thd) backup_thd->store_globals();
  } else if (backup_thd) {
    session->detach();
    backup_thd->store_globals();
#ifdef HAVE_PSI_THREAD_INTERFACE
    enum_vio_type vio_type = backup_thd->get_vio_type();
    if (vio_type != NO_VIO_TYPE) PSI_THREAD_CALL(set_connection_type)(vio_type);
#endif /* HAVE_PSI_THREAD_INTERFACE */
  } else if (in_close_session) {
    /*
      We should restore the old session only in case of close.
      In case of execute we should stay attached.
    */
    session->detach();
    if (old_session) {
      old_session->attach();
    }
  }
}

static int err_start_result_metadata(void *, uint, uint, const CHARSET_INFO *) {
  return 1;
}

static int err_field_metadata(void *, struct st_send_field *,
                              const CHARSET_INFO *) {
  return 1;
}

static int err_end_result_metadata(void *, uint, uint) { return 1; }

static int err_start_row(void *) { return 1; }

static int err_end_row(void *) { return 1; }

static void err_abort_row(void *) {}

static ulong err_get_client_capabilities(void *) { return 0; }

static int err_get_null(void *) { return 1; }

static int err_get_integer(void *, longlong) { return 1; }

static int err_get_longlong(void *, longlong, uint) { return 1; }

static int err_get_decimal(void *, const decimal_t *) { return 1; }

static int err_get_double(void *, double, uint32) { return 1; }

static int err_get_date(void *, const MYSQL_TIME *) { return 1; }

static int err_get_time(void *, const MYSQL_TIME *, uint) { return 1; }

static int err_get_datetime(void *, const MYSQL_TIME *, uint) { return 1; }

static int err_get_string(void *, const char *, size_t, const CHARSET_INFO *) {
  return 1;
}

static void err_handle_ok(void *ctx, uint server_status, uint warn_count,
                          ulonglong affected_rows, ulonglong last_insert_id,
                          const char *const) {
  Srv_session::st_err_protocol_ctx *pctx =
      static_cast<Srv_session::st_err_protocol_ctx *>(ctx);
  if (pctx && pctx->handler) {
    char buf[256];
    snprintf(buf, sizeof(buf),
             "OK status=%u warnings=%u affected=%llu last_id=%llu",
             server_status, warn_count, affected_rows, last_insert_id);
    pctx->handler(pctx->handler_context, 0, buf);
  }
}

static void err_handle_error(void *ctx, uint err_errno, const char *err_msg,
                             const char *) {
  Srv_session::st_err_protocol_ctx *pctx =
      static_cast<Srv_session::st_err_protocol_ctx *>(ctx);
  if (pctx && pctx->handler)
    pctx->handler(pctx->handler_context, err_errno, err_msg);
}

static void err_shutdown(void *, int) {}

static bool err_alive(void *) { return true; }

const struct st_command_service_cbs error_protocol_callbacks = {
    err_start_result_metadata,
    err_field_metadata,
    err_end_result_metadata,
    err_start_row,
    err_end_row,
    err_abort_row,
    err_get_client_capabilities,
    err_get_null,
    err_get_integer,
    err_get_longlong,
    err_get_decimal,
    err_get_double,
    err_get_date,
    err_get_time,
    err_get_datetime,
    err_get_string,
    err_handle_ok,
    err_handle_error,
    err_shutdown,
    err_alive};

/**
  Modifies the PSI structures to (de)install a THD

  @param thd THD
*/
#ifdef HAVE_PSI_THREAD_INTERFACE
static void set_psi(THD *thd) {
  struct PSI_thread *psi = PSI_THREAD_CALL(get_thread)();
  PSI_THREAD_CALL(set_thread_id)(psi, thd ? thd->thread_id() : 0);
  PSI_THREAD_CALL(set_thread_THD)(psi, thd);
}
#endif

/**
  Initializes physical thread to use with session service.

  @param plugin Pointer to the plugin structure, passed to the plugin over
                the plugin init function.

  @return
    false  success
    true   failure
*/
bool Srv_session::init_thread(const void *plugin) {
  char stack_start;

  /* If not null, means its already initialized, so return success*/
  if (THR_srv_session_thread != nullptr) return false;

  if (my_thread_init()) {
    connection_errors_internal++;
    return true;
  }

  THR_srv_session_thread =
      reinterpret_cast<st_plugin_int *>(const_cast<void *>(plugin));
  THR_stack_start_address = &stack_start;

  server_session_threads.add(my_thread_self(), plugin);

  return false;
}

/**
  Looks if there is currently attached session and detaches it.

  @param plugin  The plugin to be checked
*/
static void close_currently_attached_session_if_any(
    const st_plugin_int *plugin) {
  THD *c_thd = current_thd;
  if (!c_thd) return;

  Srv_session *current_session = server_session_list.find(c_thd);

  if (current_session) {
    LogErr(ERROR_LEVEL, ER_DETACHING_SESSION_LEFT_BY_PLUGIN, plugin->name.str);

    if (current_session->detach())
      LogErr(ERROR_LEVEL, ER_CANT_DETACH_SESSION_LEFT_BY_PLUGIN);
  }
}

/**
  Looks if the plugin has any non-closed sessions and closes them forcefully

  @param plugin  The plugin to be checked
*/
static void close_all_sessions_of_plugin_if_any(const st_plugin_int *plugin) {
  unsigned int removed_count;

  server_session_list.remove_all_of_plugin(plugin, removed_count);

  if (removed_count)
    LogErr(ERROR_LEVEL, ER_DETACHED_SESSIONS_LEFT_BY_PLUGIN, removed_count,
           (removed_count > 1) ? "s" : "",
           plugin ? plugin->name.str : "SERVER_INTERNAL");
}

/**
  Deinitializes physical thread to use with session service
*/
void Srv_session::deinit_thread() {
  const st_plugin_int *plugin = THR_srv_session_thread;
  if (plugin)
    close_currently_attached_session_if_any(plugin);
  else
    return;

  if (server_session_threads.remove(my_thread_self()))
    LogErr(ERROR_LEVEL, ER_FAILED_TO_DECREMENT_NUMBER_OF_THREADS);

  if (!server_session_threads.count(plugin))
    close_all_sessions_of_plugin_if_any(plugin);

  THR_srv_session_thread = nullptr;

  assert(THR_stack_start_address);
  THR_stack_start_address = nullptr;
  my_thread_end();
}

/**
  Checks if a plugin has left threads and sessions

  @param plugin  The plugin to be checked
*/
void Srv_session::check_for_stale_threads(const st_plugin_int *plugin) {
  if (!plugin) return;

  unsigned int thread_count = server_session_threads.count(plugin);
  if (thread_count) {
    close_all_sessions_of_plugin_if_any(plugin);

    LogErr(ERROR_LEVEL, ER_PLUGIN_DID_NOT_DEINITIALIZE_THREADS,
           plugin->name.str, thread_count);

    unsigned int killed_count = server_session_threads.kill(plugin);
    LogErr(ERROR_LEVEL, ER_KILLED_THREADS_OF_PLUGIN, killed_count,
           plugin->name.str);
  }
}

/**
  Inits the module

  @return
    false  success
    true   failure
*/
bool Srv_session::module_init() {
  if (srv_session_THRs_initialized) return false;
  srv_session_THRs_initialized = true;
  THR_stack_start_address = nullptr;
  THR_srv_session_thread = nullptr;

  server_session_list.init();
  server_session_threads.init();

  return false;
}

/**
  Deinits the module.

  Never fails

  @return
    false  success
*/
bool Srv_session::module_deinit() {
  if (srv_session_THRs_initialized) {
    THR_stack_start_address = nullptr;
    THR_srv_session_thread = nullptr;

    server_session_list.clear();
    server_session_list.deinit();

    server_session_threads.clear();
    server_session_threads.deinit();

    srv_session_THRs_initialized = false;
  }
  return false;
}

/**
  Checks if the session is valid.

  Checked is if session is NULL, or the state of the session is
  SRV_SESSION_OPENED, SRV_SESSION_ATTACHED or SRV_SESSION_DETACHED.

  @return
    true  valid
    false not valid
*/
bool Srv_session::is_valid(const Srv_session *session) {
  assert(session != nullptr);
  const bool is_valid_session = ((session->m_state > SRV_SESSION_CREATED) &&
                                 (session->m_state < SRV_SESSION_CLOSED));

  if (session->is_associate() || session->is_associated()) return true;

  /*
    Make sure valid session exists and invalid sessions doesn't exists in the
    list of opened sessions.
  */
  assert((is_valid_session && server_session_list.find(session->m_thd)) ||
         (!is_valid_session && !server_session_list.find(session->m_thd)));

  return is_valid_session;
}

/**
  Constructs a server session
*/
Srv_session::Srv_session(srv_session_error_cb err_cb, void *err_cb_ctx)
    : Srv_session(err_cb, err_cb_ctx, SRV_SESSION_CREATED, true, nullptr) {
  m_thd->mark_as_srv_session();
  m_thd->m_audited = false;
}

Srv_session::Srv_session(srv_session_error_cb err_cb, void *err_cb_ctx,
                         THD *thd)
    : Srv_session(err_cb, err_cb_ctx, SRV_SESSION_ASSOCIATE, false, thd) {
  assert(thd);  // A valid thd must be passed.
  m_thd->push_protocol(&m_protocol_error);
  m_thd->push_diagnostics_area(&m_da);
}

/** Delegated constructor to intialize the members. */
Srv_session::Srv_session(srv_session_error_cb err_cb, void *err_cb_ctx,
                         srv_session_state state, bool free_resources, THD *thd)
    : m_da(false),
      m_err_protocol_ctx(err_cb, err_cb_ctx),
      m_protocol_error(&error_protocol_callbacks, CS_TEXT_REPRESENTATION,
                       (void *)&m_err_protocol_ctx),
      m_state(state),
      m_vio_type(NO_VIO_TYPE),
      m_thd(thd),
      m_free_resources(free_resources) {
  try {
    if (m_thd == nullptr) m_thd = new THD();
  } catch (...) {
    DBUG_PRINT("error", ("Can't allocate the THD object"));
    throw;
  }
}

Srv_session::~Srv_session() {
  if (m_free_resources) {
    delete m_thd;
  } else {
    mysql_mutex_lock(&m_thd->LOCK_thd_protocol);
    m_thd->pop_protocol();
    mysql_mutex_unlock(&m_thd->LOCK_thd_protocol);
    m_thd->pop_diagnostics_area();
  }
}

/**
Opens a server session

@return
false  on success
true   on failure
*/
bool Srv_session::open() {
  char stack_start;
  DBUG_TRACE;

  DBUG_PRINT("info", ("Session=%p  THD=%p  DA=%p", this, m_thd, &m_da));
  assert(m_state == SRV_SESSION_CREATED || m_state == SRV_SESSION_CLOSED);

  m_thd->push_protocol(&m_protocol_error);
  m_thd->push_diagnostics_area(&m_da);
  /*
    m_thd.stack_start will be set once we start attempt to attach.
    store_globals() will check for it, so we will set it beforehand.

    No store_globals() here as the session is always created in a detached
    state. Attachment with store_globals() will happen on demand.
  */
  if (thd_init_client_charset(m_thd, my_charset_utf8mb3_general_ci.number)) {
    connection_errors_internal++;
    if (m_err_protocol_ctx.handler)
      m_err_protocol_ctx.handler(m_err_protocol_ctx.handler_context,
                                 ER_OUT_OF_RESOURCES,
                                 ER_DEFAULT(ER_OUT_OF_RESOURCES));
    Connection_handler_manager::dec_connection_count();
    return true;
  }

  m_thd->update_charset();

  m_thd->set_new_thread_id();

  DBUG_PRINT("info", ("thread_id=%d", m_thd->thread_id()));

  m_thd->set_command(COM_SLEEP);
  m_thd->init_query_mem_roots();

  /*
    Set current_thd so that it can be used during authentication,
    before attach() is called. Note that this kind of breaks the
    separation between open() and attach() so it is likely that
    a conceptually better solution is required long-term.
  */
  thd_set_thread_stack(m_thd, &stack_start);
  m_thd->store_globals();

  Global_THD_manager::get_instance()->add_thd(m_thd);

  const st_plugin_int *plugin = THR_srv_session_thread;
  m_thd->set_plugin(plugin);

  server_session_list.add(m_thd, plugin, this);

  m_state = SRV_SESSION_OPENED;

  return false;
}

/**
  Attaches the session to the current physical thread

  @returns
    false   success
    true    failure
*/
bool Srv_session::attach() {
  const bool first_attach = (m_state == SRV_SESSION_OPENED);
  DBUG_TRACE;
  DBUG_PRINT("info", ("current_thd=%p", current_thd));
  assert(m_state > SRV_SESSION_CREATED && m_state < SRV_SESSION_CLOSED);

  if (is_attached()) {
    if (!my_thread_equal(m_thd->real_id, my_thread_self())) {
      DBUG_PRINT("error", ("Attached to different thread. Detach in it"));
      return true;
    }
    /* As it is attached, no need to do anything */
    return false;
  }

  // Since we now set current_thd during open(), we need to do complete
  // attach the first time in any case.
  if (!first_attach && m_thd == current_thd) return false;

  THD *old_thd = current_thd;
  DBUG_PRINT("info", ("current_thd=%p", current_thd));

  if (old_thd) old_thd->restore_globals();

  DBUG_PRINT("info", ("current_thd=%p", current_thd));

  const char *new_stack = THR_srv_session_thread
                              ? THR_stack_start_address
                              : (old_thd ? old_thd->thread_stack : nullptr);
  /*
    Attach optimistically, as this will set thread_stack,
    which needed by store_globals()
  */
  set_attached(new_stack);

  // This will install our new THD object as current_thd
  m_thd->store_globals();

  Srv_session *old_session = server_session_list.find(old_thd);

  /* Really detach only if we are sure everything went fine */
  if (old_session) old_session->set_detached();

  thd_clear_errors(m_thd);

#ifdef HAVE_PSI_THREAD_INTERFACE
  set_psi(m_thd);

  PSI_THREAD_CALL(set_connection_type)
  (m_vio_type != NO_VIO_TYPE ? m_vio_type : m_thd->get_vio_type());
#endif /* HAVE_PSI_THREAD_INTERFACE */

  if (first_attach) {
    /*
      At first attach the security context should have been already set and
      and this will report correct information.
    */
#ifdef HAVE_PSI_THREAD_INTERFACE
    PSI_THREAD_CALL(notify_session_connect)(m_thd->get_psi());
#endif /* HAVE_PSI_THREAD_INTERFACE */

    query_logger.general_log_print(m_thd, COM_CONNECT, NullS);
  }

  return false;
}

/**
  Detaches the session from the current physical thread.

  @returns
    false success
    true  failure
*/
bool Srv_session::detach() {
  DBUG_TRACE;

  if (!is_attached()) return false;

  if (!my_thread_equal(m_thd->real_id, my_thread_self())) {
    DBUG_PRINT("error", ("Attached to a different thread. Detach in it"));
    return true;
  }

  DBUG_PRINT("info",
             ("Session=%p THD=%p current_thd=%p", this, m_thd, current_thd));

  assert(m_thd == current_thd);

  m_thd->restore_globals();

#ifdef HAVE_PSI_THREAD_INTERFACE
  set_psi(nullptr);
#endif
  /*
    We can't call PSI_THREAD_CALL(set_connection_type)(NO_VIO_TYPE) here because
    it will assert. Thus, it will be possible to have a physical thread, which
    has no session attached to it but have cached vio type.
    This only will happen in a spawned thread initialized by this service.
    If a server initialized thread is used, just after detach the previous
    current_thd will be re-attached again (not created by our service) and
    the vio type will be set correctly.
    Please see: Session_backup_and_attach::~Session_backup_and_attach()
  */

  /*
    Call after restore_globals() as it will check the stack_addr, which is
    nulled by set_detached()
  */
  set_detached();
  return false;
}

/**
  Closes the session

  @returns
    false Session successfully closed
    true  No such session exists / Session is attached to a different thread
*/
bool Srv_session::close() {
  DBUG_TRACE;

  DBUG_PRINT("info",
             ("Session=%p THD=%p current_thd=%p", this, m_thd, current_thd));

  assert(m_state < SRV_SESSION_CLOSED);

  /*
    RAII
    We store the state (the currently attached session, if different than
    our and then attach our.
    The destructor will attach the session we detached.
  */

  Srv_session::Session_backup_and_attach backup(this, true);

  if (backup.attach_error) return true;

  m_state = SRV_SESSION_CLOSED;

  server_session_list.remove(m_thd);

  /*
    Log to general log must happen before release_resources() as
    current_thd will be different then.
  */
  query_logger.general_log_print(m_thd, COM_QUIT, NullS);

#ifdef HAVE_PSI_THREAD_INTERFACE
  PSI_THREAD_CALL(notify_session_disconnect)(m_thd->get_psi());
#endif /* HAVE_PSI_THREAD_INTERFACE */

  m_thd->security_context()->logout();
  m_thd->m_view_ctx_list.clear();
  close_mysql_tables(m_thd);

  m_thd->set_plugin(nullptr);
  m_thd->pop_diagnostics_area();

  m_thd->get_stmt_da()->reset_diagnostics_area();

  // DEBUG_SYNC control block is released under call to
  // `m_thd->release_resource`, thus we can't put this sync
  // point directly before `pop_protocol`.
  // Second constrain is that `THD::disconnect` marks
  // this connection as killed, which disables DEBUG_SYNC.
  DEBUG_SYNC(m_thd, "srv_session_close");

  m_thd->disconnect();

#ifdef HAVE_PSI_THREAD_INTERFACE
  set_psi(nullptr);
#endif

  m_thd->release_resources();

  Global_THD_manager::get_instance()->remove_thd(m_thd);

  mysql_mutex_lock(&m_thd->LOCK_thd_protocol);
  m_thd->pop_protocol();
  mysql_mutex_unlock(&m_thd->LOCK_thd_protocol);

  Connection_handler_manager::dec_connection_count();

  return false;
}

/**
  Sets session's state to attached

  @param stack  New stack address
*/
void Srv_session::set_attached(const char *stack) {
  m_state = SRV_SESSION_ATTACHED;
  thd_set_thread_stack(m_thd, stack);
}

/**
  Changes the state of a session to detached
*/
void Srv_session::set_detached() {
  m_state = SRV_SESSION_DETACHED;
  thd_set_thread_stack(m_thd, nullptr);
}

int Srv_session::execute_command(enum enum_server_command command,
                                 const union COM_DATA *data,
                                 const CHARSET_INFO *client_cs,
                                 const struct st_command_service_cbs *callbacks,
                                 enum cs_text_or_binary text_or_binary,
                                 void *callbacks_context) {
  DBUG_TRACE;

  if (!srv_session_server_is_available()) {
    if (m_err_protocol_ctx.handler)
      m_err_protocol_ctx.handler(m_err_protocol_ctx.handler_context,
                                 ER_SESSION_WAS_KILLED,
                                 ER_DEFAULT(ER_SESSION_WAS_KILLED));
    return 1;
  }

  if (m_thd->killed) {
    if (m_err_protocol_ctx.handler)
      m_err_protocol_ctx.handler(m_err_protocol_ctx.handler_context,
                                 ER_SESSION_WAS_KILLED,
                                 ER_DEFAULT(ER_SESSION_WAS_KILLED));
    return 1;
  }

  assert(m_thd->get_protocol() == &m_protocol_error);

  // RAII:the destructor restores the state
  Srv_session::Session_backup_and_attach backup(this, false);

  if (backup.attach_error) return 1;

  if (client_cs && m_thd->variables.character_set_results != client_cs &&
      thd_init_client_charset(m_thd, client_cs->number))
    return 1;

  /* Switch to different callbacks */
  Protocol_callback client_proto(callbacks, text_or_binary, callbacks_context);

  m_thd->push_protocol(&client_proto);

  mysql_audit_release(m_thd);

  /*
    The server does it for COM_QUERY in dispatch_sql_command() but not for
    COM_INIT_DB, for example
  */
  if (command != COM_QUERY) m_thd->reset_for_next_command();

  /* For per-query performance counters with log_slow_statement */
  struct System_status_var query_start_status;
  m_thd->clear_copy_status_var();
  if (opt_log_slow_extra) {
    m_thd->copy_status_var(&query_start_status);
  }

  mysql_thread_set_secondary_engine(false);

  if (m_state != SRV_SESSION_ASSOCIATED) {
    assert(m_thd->m_statement_psi == nullptr);
    m_thd->m_statement_psi = MYSQL_START_STATEMENT(
        &m_thd->m_statement_state, stmt_info_new_packet.m_key, m_thd->db().str,
        m_thd->db().length, m_thd->charset(), nullptr);
  }
  int ret = dispatch_command(m_thd, data, command);

  DEBUG_SYNC(m_thd, "wait_before_popping_protocol");
  m_thd->pop_protocol();
  assert(m_thd->get_protocol() == &m_protocol_error);
  return ret;
}

/**
  Sets the connection type.

  @see enum_vio_type

  @return
    false success
    true  failure
*/
bool Srv_session::set_connection_type(enum_vio_type v_type) {
  if (v_type < FIRST_VIO_TYPE || v_type > LAST_VIO_TYPE) return true;

  m_vio_type = v_type;
#ifdef HAVE_PSI_THREAD_INTERFACE
  if (is_attached()) PSI_THREAD_CALL(set_connection_type)(m_vio_type);
#endif /* HAVE_PSI_THREAD_INTERFACE */
  return false;
}

void Srv_session::set_associate() { m_state = SRV_SESSION_ASSOCIATED; }

void Srv_session::set_disassociate() { m_state = SRV_SESSION_DISASSOCIATED; }

bool Srv_session::is_associate() const {
  return m_state == SRV_SESSION_ASSOCIATE;
}

bool Srv_session::is_associated() const {
  return m_state == SRV_SESSION_ASSOCIATED;
}

bool Srv_session::associate() {
  if (!is_associate()) return true;
  const char *stack_start = m_thd->thread_stack ? m_thd->thread_stack : nullptr;
  thd_set_thread_stack(m_thd, stack_start);
  // This will install our new THD object as current_thd
  m_thd->store_globals();
  thd_clear_errors(m_thd);
  set_associate();
  return false;
}

bool Srv_session::disassociate() {
  if (!is_associated()) return true;

  if (!my_thread_equal(m_thd->real_id, my_thread_self())) {
    DBUG_PRINT("error", ("Attached to a different thread. Detach in it"));
    return true;
  }

  DBUG_PRINT("info",
             ("Session=%p THD=%p current_thd=%p", this, m_thd, current_thd));

  m_thd->restore_globals();
  set_disassociate();
  return false;
}

/**
  Callback for inspecting a THD object and modifying the peer_port member
*/
static void set_client_port_in_thd(THD *thd, uint16_t *input) {
  thd->peer_port = *input;
}

/**
  Sets the client port.

  @note The client port in SHOW PROCESSLIST, INFORMATION_SCHEMA.PROCESSLIST.
  This port is NOT shown in PERFORMANCE_SCHEMA.THREADS.

  @param port  Port number
*/
void Srv_session::set_client_port(uint16_t port) {
  Find_thd_with_id find_thd_with_id(m_thd->thread_id());
  THD_ptr thd_ptr =
      Global_THD_manager::get_instance()->find_thd(&find_thd_with_id);
  if (thd_ptr) set_client_port_in_thd(thd_ptr.get(), &port);
}

/**
  Returns the number opened sessions in thread initialized by this class.
*/
unsigned int Srv_session::session_count() { return server_session_list.size(); }

/**
  Returns the number currently running threads initialized by this class.
*/
unsigned int Srv_session::thread_count(const void *plugin) {
  return server_session_threads.count(plugin);
}

/**
  Check if current physical thread was created to be used with this class.
*/
bool Srv_session::is_srv_session_thread() {
  return nullptr != THR_srv_session_thread;
}