File: libthread_db.c

package info (click to toggle)
libi8x 0.0.5-1
  • links: PTS
  • area: main
  • in suites: sid
  • size: 7,192 kB
  • ctags: 1,365
  • sloc: ansic: 6,874; python: 1,339; makefile: 146; sh: 102
file content (1144 lines) | stat: -rw-r--r-- 28,613 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
/* Copyright (C) 2016-17 Red Hat, Inc.
   This file is part of the Infinity Note Execution Library.

   The Infinity Note Execution Library is free software; you can
   redistribute it and/or modify it under the terms of the GNU Lesser
   General Public License as published by the Free Software
   Foundation; either version 2.1 of the License, or (at your option)
   any later version.

   The Infinity Note Execution Library 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 Lesser General Public License for more
   details.

   You should have received a copy of the GNU Lesser General Public
   License along with the Infinity Note Execution Library; if not, see
   <http://www.gnu.org/licenses/>.  */

#include <libi8x.h>

#include <thread_db.h>
#include "proc_service.h"

#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
#include <libelf.h>
#include <gelf.h>
#include <gnu/lib-names.h>
#include <link.h>

#ifndef NT_GNU_INFINITY
# define NT_GNU_INFINITY 8995  /* XXX NOT FINAL!  */
#endif

static td_err_e td_ta_init (td_thragent_t *ta);
static td_err_e td_ta_init_libi8x (td_thragent_t *ta);
static i8x_err_e td_ta_thr_iter_cb (struct i8x_xctx *xctx,
				    struct i8x_inf *inf,
				    struct i8x_func *func,
				    union i8x_value *args,
				    union i8x_value *rets);

/* Handle for a process, created by td_ta_new and passed as
   the first argument to all other libthread_db functions.  */

struct td_thragent
{
  /* Handle for a process supplied by the debugger to be
     passed to the as the first argument to the various
     callbacks defined in proc_service.h.  */
  struct ps_prochandle *ph;

  /* Main executable ELF header and wordsize.
     Only filled in if we initialized via r_debug.  */
  GElf_Ehdr exec_ehdr_mem;
  GElf_Ehdr *exec_ehdr;
  size_t ptrbytes;

  /* libi8x context.  */
  struct i8x_ctx *ctx;

  /* The process we are accessing.  */
  struct i8x_inf *inf;

  /* Execution context.  */
  struct i8x_xctx *xctx;

  /* References to functions we use.  */
  struct i8x_funcref *link_map_get_tls_modid;
  struct i8x_funcref *thread_from_lwpid;
  struct i8x_funcref *thread_iterate;
  struct i8x_funcref *thread_get_event;
  struct i8x_funcref *thread_get_lwpid;
  struct i8x_funcref *thread_get_priority;
  struct i8x_funcref *thread_get_report_events;
  struct i8x_funcref *thread_get_specific;
  struct i8x_funcref *thread_get_start_routine;
  struct i8x_funcref *thread_get_state;
  struct i8x_funcref *thread_get_tlsbase;

  /* Callback for td_ta_thr_iter.  */
  struct i8x_funcref *thr_iter_cb;
  td_thr_iter_f *thr_iter_cb_impl;
};

/* Callback for td_ta_self_test.  */

static int
td_ta_selftest_cb (const td_thrhandle_t *th, void *arg)
{
  union i8x_value args[1], rets[2];
  i8x_err_e err;

  fputs ("   ", stderr);

  if (th == NULL)
    goto fail;
  fputc ('*', stderr);

  if (th->th_ta_p != arg)
    goto fail;
  fprintf (stderr, " %p", th->th_unique);

  args[0].p = th->th_unique;
  err = i8x_xctx_call (th->th_ta_p->xctx,
		       th->th_ta_p->thread_get_lwpid,
		       th->th_ta_p->inf, args, rets);
  if (err != I8X_OK)
    goto fail;
  fputs (" =>", stderr);

  if (rets[1].i != TD_OK)
    goto fail;
  lwpid_t lwpid = rets[0].i;
  fprintf (stderr, " %d", lwpid);

  args[0].i = lwpid;
  err = i8x_xctx_call (th->th_ta_p->xctx,
		       th->th_ta_p->thread_from_lwpid,
		       th->th_ta_p->inf, args, rets);

  if (err != I8X_OK)
    goto fail;
  fputs (" =>", stderr);

  if (rets[1].i != TD_OK)
    goto fail;
  psaddr_t th_unique = rets[0].p;
  fprintf (stderr, " %p", th_unique);

  if (th_unique != th->th_unique)
    goto fail;

  fputc ('\n', stderr);
  return 0;

 fail:
  fputs (" FAIL!\n", stderr);
  return -1;
}

/* Check that thread::get_lwpid and thread::from_lwpid are the inverse
   of each other for each thread.  This gives some assurance that the
   platform-specific libpthread::__lookup_th_unique is working.  */

static td_err_e
td_ta_self_test (td_thragent_t *ta)
{
  td_err_e result;

  fputs (
"==================================================================\n"
"\n"
"  WELCOME to INFINITY!\n"
"\n"
"  >>> This libthread_db is a DEMONSTRATION,\n"
"  >>> DO NOT USE IN PRODUCTION IT WILL EAT YOUR BABIES!!!\n"
"\n"
"  Note that many functions in this library are not present,\n"
"  and some functions that are present always return TD_NOCAPAB.\n"
"\n"
"  SELF-TEST:\n", stderr);

  result = td_ta_thr_iter (ta, td_ta_selftest_cb, ta,
			   TD_THR_ANY_STATE,
			   TD_THR_LOWEST_PRIORITY,
			   TD_SIGNO_MASK,
			   TD_THR_ANY_USER_FLAGS);
  if (result == TD_OK)
    fputs ("\n  OK HAVE FUN!\n", stderr);
  else
    result = TD_DBERR;

  fputs (
"\n"
"==================================================================\n",
	 stderr);

  return result;
}

/* Map an i8x error code to a libthread_db one.  */

static td_err_e
td_err_from_i8x_err (i8x_err_e err)
{
  switch (err)
    {
    case I8X_OK:
      return TD_OK;

    case I8X_ENOMEM:
      return TD_MALLOC;

    case I8X_UNRESOLVED_FUNC:
      return TD_NOCAPAB;

    default:
      return TD_ERR;
    }
}

/* Relocation information for a note.  */

struct td_relocinfo
{
  ps_infinity_reloc_f *reloc_func;
  void *reloc_func_arg;
};

/* Basic relocation function that adds a base address.  */

static ps_err_e
td_basic_relocate (void *base_addr_p, psaddr_t unrelocated_p,
		   psaddr_t *result)
{
  uintptr_t base_addr = (uintptr_t) (psaddr_t) base_addr_p;
  uintptr_t unrelocated = (uintptr_t) (psaddr_t) unrelocated_p;

  *result = (psaddr_t) (base_addr + unrelocated);

  return PS_OK;
}

/* Import a single note, creating the context if necessary.  */

static ps_err_e
td_import_note (void *ta_p, const char *buf, size_t bufsiz,
		const char *srcname, ssize_t srcoffset,
		ps_infinity_reloc_f *rf, void *rf_arg)
{
  td_thragent_t *ta = (td_thragent_t *) ta_p;
  i8x_err_e err;

  if (ta->ctx == NULL)
    {
      err = i8x_ctx_new (0, NULL, &ta->ctx);

      if (err != I8X_OK)
	return PS_ERR;
    }

  struct td_relocinfo *ri = calloc (1, sizeof (struct td_relocinfo));
  if (ri == NULL)
    return PS_ERR;

  struct i8x_func *func;
  err = i8x_ctx_import_bytecode (ta->ctx, buf, bufsiz, srcname,
				 srcoffset, &func);
  if (err != I8X_OK)
    {
      free (ri);

      if (err == I8X_NOTE_CORRUPT
	  || err == I8X_NOTE_UNHANDLED
	  || err == I8X_NOTE_INVALID)
	return PS_OK;

      return PS_ERR;
    }

  ri->reloc_func = rf;
  ri->reloc_func_arg = rf_arg;
  i8x_func_set_userdata (func, ri, free);

  func = i8x_func_unref (func);

  return PS_OK;
}

/* Load and register Infinity notes from an ELF.  */

static td_err_e
td_import_notes_from_elf (td_thragent_t *ta, const char *filename,
			  psaddr_t base_address, Elf *elf)
{
  Elf_Scn *scn = NULL;

  while ((scn = elf_nextscn (elf, scn)) != NULL)
    {
      GElf_Shdr shdr_mem;
      GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);

      if (shdr == NULL || shdr->sh_type != SHT_NOTE)
	continue;

      Elf_Data *data = elf_getdata (scn, NULL);
      if (data == NULL)
	continue;

      size_t offset = 0;
      GElf_Nhdr nhdr;
      size_t name_offset;
      size_t desc_offset;

      while (offset < data->d_size
	     && (offset = gelf_getnote (data, offset,
					&nhdr, &name_offset,
					&desc_offset)) > 0)
	{
	  if (nhdr.n_type != NT_GNU_INFINITY)
	    continue;

	  const char *name = (const char *) data->d_buf + name_offset;
	  if (strncmp (name, "GNU", 4) != 0)
	    continue;

	  /* We have an Infinity note!  */

	  if (td_import_note (ta,
			      (const char *) data->d_buf + desc_offset,
			      nhdr.n_descsz, filename,
			      shdr->sh_offset + desc_offset,
			      td_basic_relocate, base_address) != PS_OK)
	    return TD_ERR;
	}
    }

  return TD_OK;
}

/* Load and register Infinity notes from a local file.  */

static td_err_e
td_import_notes_from_file (td_thragent_t *ta, const char *filename,
			   psaddr_t base_address)
{
  int fd = open (filename, O_RDONLY);
  if (fd == -1)
    return TD_OK;  /* Silently skip files we can't read.  */

  Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
  td_err_e err;

  switch (elf_kind (elf))
    {
    case ELF_K_ELF:
      err = td_import_notes_from_elf (ta, filename, base_address, elf);
      break;

    default:
      err = TD_ERR;
    }

  elf_end (elf);
  close (fd);

  return err;
}

/* Word offsets into r_debug and link_map.  */

#define WORD_OFFSET(strct, field) \
  (offsetof (struct strct, field) / sizeof (void *))

#define R_VERSION_WORD	WORD_OFFSET (r_debug, r_version)
#define R_MAP_WORD	WORD_OFFSET (r_debug, r_map)
#define R_LDBASE_WORD	WORD_OFFSET (r_debug, r_ldbase)

#define L_NEXT_WORD	WORD_OFFSET (link_map, l_next)
#define L_NAME_WORD	WORD_OFFSET (link_map, l_name)
#define L_ADDR_WORD	WORD_OFFSET (link_map, l_addr)

#define MAX(a, b) ((a) > (b) ? (a) : (b))

#define R_DEBUG_WORDS \
  (MAX (MAX (R_VERSION_WORD, R_MAP_WORD), R_LDBASE_WORD) + 1)

#define LINK_MAP_WORDS \
  (MAX (MAX (L_NEXT_WORD, L_NAME_WORD), L_ADDR_WORD) + 1)

/* Read an array of words from the inferior.  */

static ps_err_e
td_pdread_words (td_thragent_t *ta, psaddr_t src, char *dst, size_t nw)
{
  return ps_pdread (ta->ph, src, dst, nw * ta->ptrbytes);
}

/* Access word arrays.  */

static int
td_int_at (td_thragent_t *ta, const char *buf, size_t word)
{
  return *(int *) (buf + word * ta->ptrbytes);
}

static psaddr_t
td_ptr_at (td_thragent_t *ta, const char *buf, size_t word)
{
  intptr_t result;

  buf += word * ta->ptrbytes;
  switch (ta->ptrbytes * 8)
    {
#define CASE(SIZE)							\
    case SIZE:								\
      result = *(uint ## SIZE ## _t *) buf;				\
      break

    CASE(32);
#if __WORDSIZE >= 64
    CASE(64);
#endif /* __WORDSIZE >= 64 */

#undef CASE

    default:
      /* td_ta_init ta->ptrbytes check broken.  */
      abort ();
    }

  return (psaddr_t) result;
}

/* Read a NUL-terminated string from the inferior.  */

static ps_err_e
td_pdreadstr (td_thragent_t *ta, psaddr_t srcp, char *dst, size_t len)
{
  char *src = srcp;

  for (char *limit = dst + len; dst < limit; dst++, src++)
    {
      ps_err_e err = ps_pdread (ta->ph, src, dst, sizeof (char));

      if (err != PS_OK || *dst == '\0')
	return err;
    }

  return PS_ERR;
}

/* Load and register Infinity notes from a local process.  */

static td_err_e
td_import_notes_from_r_debug (td_thragent_t *ta)
{
  char exec_filename[32];
  char r_debug[R_DEBUG_WORDS * sizeof(void *)];
  char lm[LINK_MAP_WORDS * sizeof(void *)];
  psaddr_t addr;
  td_err_e err;

  /* Build the main executable filename.  */
  size_t len = snprintf (exec_filename,
			 sizeof (exec_filename),
			 "/proc/%d/exe", ps_getpid (ta->ph));
  if (len > sizeof (exec_filename))
    return TD_DBERR;  /* Should be enough for longest PID.  */

  /* Read the main executable's ELF header.  */
  int fd = open (exec_filename, O_RDONLY);
  if (fd != -1)
    {
      Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
      if (elf_kind (elf) == ELF_K_ELF)
	ta->exec_ehdr = gelf_getehdr (elf, &ta->exec_ehdr_mem);

      elf_end (elf);
      close (fd);
    }
  if (ta->exec_ehdr == NULL)
    return TD_VERSION;

  /* Set the wordsize we'll use.  */
  switch (ta->exec_ehdr->e_ident[EI_CLASS])
    {
    case ELFCLASS32:
      ta->ptrbytes = 4;
      break;

#if __WORDSIZE >= 64
    case ELFCLASS64:
      ta->ptrbytes = 8;
      break;
#endif /* __WORDSIZE >= 64 */

    default:
      return TD_VERSION;
    }

  /* GDB tries to load libthread_db every time a new object file is
     added to the inferior until td_ta_new completes successfully.
     It expects these early calls to fail with TD_NOLIBTHREAD or
     TD_VERSION, two errors which it silently ignores, which is why
     this function returns those codes for the first few failures.  */

  if (ps_pglobal_lookup (ta->ph, LD_SO, "_r_debug", &addr) != PS_OK)
    return TD_NOLIBTHREAD;

  if (td_pdread_words (ta, addr, r_debug, R_DEBUG_WORDS) != PS_OK)
    return TD_NOLIBTHREAD;

  if (td_int_at (ta, r_debug, R_VERSION_WORD) != 1)
    return TD_VERSION;

  /* Scan each ELF in the link map for notes.  */
  for (addr = td_ptr_at (ta, r_debug, R_MAP_WORD);
       addr != NULL;
       addr = td_ptr_at (ta, lm, L_NEXT_WORD))
    {
      if (td_pdread_words (ta, addr, lm, LINK_MAP_WORDS) != PS_OK)
	return TD_ERR;

      /* No idea if this might happen.  */
      addr = td_ptr_at (ta, lm, L_NAME_WORD);
      if (addr == NULL)
	continue;

      char filename[PATH_MAX];
      if (td_pdreadstr (ta, addr, filename, sizeof (filename)) != PS_OK)
	return TD_ERR;

      /* Skip both empty filenames and linux-vdso.so.1.  */
      if (filename[0] != '/')
	continue;

      err = td_import_notes_from_file (ta, filename,
				       td_ptr_at (ta, lm, L_ADDR_WORD));
      if (err != TD_OK)
	return err;
    }

  /* If we have no context then no notes were found.  It's possible
     this is a static executable so we try the main executable to
     cover that case.  */
  if (ta->ctx == NULL)
    {
      err = td_import_notes_from_file (ta, exec_filename,
				       td_ptr_at (ta, r_debug,
						  R_LDBASE_WORD));
      if (err != TD_OK)
	return err;
    }

  return TD_OK;
}

/* Address relocation function.  */

static i8x_err_e
td_relocate_address (struct i8x_inf *inf, struct i8x_reloc *reloc,
		     uintptr_t *result)
{
  struct i8x_func *func = i8x_reloc_get_func (reloc);
  struct td_relocinfo *ri
    = (struct td_relocinfo *) i8x_func_get_userdata (func);

  if (ri->reloc_func (ri->reloc_func_arg,
		      (psaddr_t) i8x_reloc_get_unrelocated (reloc),
		      (psaddr_t *) result) != PS_OK)
    return I8X_RELOC_FAILED;

  return I8X_OK;
}

/* Memory reader function.  */

static i8x_err_e
td_read_memory (struct i8x_inf *inf, uintptr_t addr, size_t len,
		void *result)
{
  td_thragent_t *ta = (td_thragent_t *) i8x_inf_get_userdata (inf);

  if (ps_pdread (ta->ph, (psaddr_t) addr, result, len) != PS_OK)
    return I8X_READ_MEM_FAILED;

  return I8X_OK;
}

/* Infinity native function wrapper for ps_getpid.  */

static i8x_err_e
td_ps_getpid (struct i8x_xctx *xctx, struct i8x_inf *inf,
	      struct i8x_func *func, union i8x_value *args,
	      union i8x_value *rets)
{
  td_thragent_t *ta = (td_thragent_t *) i8x_inf_get_userdata (inf);

  rets[0].i = ps_getpid (ta->ph);

  return I8X_OK;
}

/* Convert DWARF register number to prgregset_t offset.  */

static int
td_decode_regnum (td_thragent_t *ta, int regnum,
		  size_t *regset_off, size_t *size_bytes)
{
  switch (ta->exec_ehdr->e_machine)
    {
    case EM_386:
      /* REGISTER_THREAD_AREA (32, 10 * 4, 3)
	 REGISTER_THREAD_AREA (64, 26 * 8, 3)  */
      if (regnum == 45)  /* %gs */
	{
	  *regset_off = (__WORDSIZE == 64 ? 26 : 10) * sizeof (void *);
	  *size_bytes = sizeof (void *);

	  return 0;
	}
      break;

    case EM_PPC:
    case EM_PPC64:
      /* REGISTER (32, 32, PT_THREAD_POINTER * 4, I8_TS_REG_BIAS)
         REGISTER (64, 64, PT_THREAD_POINTER * 8, I8_TS_REG_BIAS)  */
      if (regnum >= 0 && regnum < 32)  /* GPR.  */
	{
	  *regset_off = regnum * sizeof (void *);
	  *size_bytes = sizeof (void *);

	  return 0;
	}
      break;

    case EM_S390:
      /* REGISTER (32, 32, 18 * 4, I8_TS_REG_BIAS)
         REGISTER (64, __WORDSIZE, 18 * 8, I8_TS_REG_BIAS)  */
      if (regnum >= 48 && regnum < 64)  /* Access register.  */
	{
	  *regset_off = (2 * sizeof (void *)    /* PSW.  */
			 + 16 * sizeof (void *) /* GPRs.  */
			 + (regnum - 48) * sizeof (int));
	  *size_bytes = sizeof (int);

	  return 0;
	}
      break;
    }

  fprintf (stderr,
	   "\nerror: Unknown DWARF register %d for ELF e_machine %d\n",
	   regnum, ta->exec_ehdr->e_machine);
  return -1;
}

/* Infinity native function wrapper for ps_get_register.  */

#pragma weak ps_get_register
#pragma weak ps_get_thread_area

static i8x_err_e
td_ps_get_register (struct i8x_xctx *xctx, struct i8x_inf *inf,
		    struct i8x_func *func, union i8x_value *args,
		    union i8x_value *rets)
{
  td_thragent_t *ta = (td_thragent_t *) i8x_inf_get_userdata (inf);
  lwpid_t lwpid = args[0].i;
  int regnum = args[1].i;

  if (&ps_get_register != NULL)
    {
      rets[1].i = ps_get_register (ta->ph, lwpid, regnum, &rets[0].p);

      return I8X_OK;
    }

  /* The remainder of this function is a semi-hacky fallback case for
     clients without ps_get_register.  We can only use it if we know
     what hardware the target process is running on.  */
  if (ta->exec_ehdr == NULL)
    {
      rets[1].i = PS_ERR;

      return I8X_OK;
    }

  /* GDB currently does not fill in fs_base or gs_base on x86_64,
     though it might in future and other clients might right now.
     If possible We'll use ps_get_thread_area to access these.  */
  if (ta->exec_ehdr->e_machine == EM_X86_64
      && (regnum == 58 || regnum == 59)
      && &ps_get_thread_area != NULL)
    {
      rets[1].i = ps_get_thread_area (ta->ph, lwpid, regnum - 33,
				      &rets[0].p);
      return I8X_OK;
    }

  size_t offset, size;
  if (td_decode_regnum (ta, regnum, &offset, &size) != 0)
    return I8X_NOTE_UNHANDLED;

  /* We cannot use prgregset_t here because we may be accessing a
     process on an architecture with a larger prgregset_t than our
     own.  I will probably eat my words later, but here goes: 1024
     registers should be suitably vast.  */
  elf_greg_t regs[1024];
  rets[1].i = ps_lgetregs (ta->ph, lwpid, regs);
  if (rets[1].i != PS_OK)
    return I8X_OK;

  switch (size * 8)
    {
#define CASE(SIZE)							\
    case SIZE:								\
      rets[0].u =							\
	*(uint ## SIZE ## _t *) ((uint8_t *) regs + offset);		\
      break

    CASE(32);
#if __WORDSIZE >= 64
    CASE(64);
#endif /* __WORDSIZE >= 64 */

#undef CASE

    default:
      rets[1].i = PS_ERR;
      return I8X_OK;
    }

  return I8X_OK;
}

/* Infinity native function wrapper for ps_get_thread_area.  */

static i8x_err_e
td_ps_get_thread_area (struct i8x_xctx *xctx, struct i8x_inf *inf,
		       struct i8x_func *func, union i8x_value *args,
		       union i8x_value *rets)
{
  td_thragent_t *ta = (td_thragent_t *) i8x_inf_get_userdata (inf);

  rets[1].i = ps_get_thread_area (ta->ph, args[0].i, args[1].i,
				  &rets[0].p);

  return I8X_OK;
}

/* Initialize the thread debug support library.  */

td_err_e
td_init (void)
{
  /* Initialize libelf.  */
  elf_version (EV_CURRENT);

  return TD_OK;
}

/* Generate new thread debug library handle for process PS.  */

td_err_e
td_ta_new (struct ps_prochandle *ps, td_thragent_t **__ta)
{
  td_thragent_t *ta;
  td_err_e err;

  ta = calloc (1, sizeof (td_thragent_t));
  if (ta == NULL)
    return TD_MALLOC;

  ta->ph = ps;

  err = td_ta_init (ta);
  if (err == TD_OK)
    *__ta = ta;
  else
    td_ta_delete (ta);

  return err;
}

/* Helper for td_ta_new.  */

#pragma weak ps_foreach_infinity_note

static td_err_e
td_ta_init (td_thragent_t *ta)
{
  td_err_e err;

  /* Load and register any Infinity notes from the process we've been
     created on.  This will initialize ta->ctx if notes are found.  */
  if (&ps_foreach_infinity_note != NULL)
    {
      if (ps_foreach_infinity_note (ta->ph, td_import_note, ta) != PS_OK)
	return TD_ERR;
    }
  else
    {
      err = td_import_notes_from_r_debug (ta);
      if (err != TD_OK)
	return err;
    }

  if (ta->ctx == NULL)
    return TD_VERSION;  /* The process contained no notes.  */

  /* Initialize all libi8x bits except ta->ctx which is done already.  */
  err = td_ta_init_libi8x (ta);
  if (err != TD_OK)
    return err;

  /* Run a quick self-test and print the warning banner.  */
  err = td_ta_self_test (ta);
  if (err != TD_OK)
    return err;

  return TD_OK;
}

/* Helper for td_ta_init.  */

static td_err_e
td_ta_init_libi8x (td_thragent_t *ta)
{
  i8x_err_e err;

  /* Register the native functions we provide.  */
#define REGISTER(name, args, rets, impl)			    \
  do {								    \
    err = i8x_ctx_import_native (ta->ctx,			    \
				 "procservice", #name,		    \
				 args, rets,			    \
				 impl, NULL);			    \
    if (err != I8X_OK)						    \
      return td_err_from_i8x_err (err);				    \
  } while (0)

  REGISTER (getpid,       "",   "i",  td_ps_getpid);
  /* XXX this should be "if (&ps_get_register != NULL)"
     once the ELF and r_debug fallback code is removed. */
  REGISTER (get_register, "ii", "ii", td_ps_get_register);

  if (&ps_get_thread_area != NULL)
    REGISTER (get_thread_area, "ii", "ip", td_ps_get_thread_area);

#undef REGISTER

  /* Store references to the functions we use.  */
#define GET_FUNCREF(provider, name, args, rets)			    \
  do {								    \
    err = i8x_ctx_get_funcref (ta->ctx,				    \
			       #provider, #name, args, rets,	    \
			       &ta->provider ## _ ## name);	    \
    if (err != I8X_OK)						    \
      return td_err_from_i8x_err (err);				    \
								    \
    if (!i8x_funcref_is_resolved (ta->provider ## _ ## name))	    \
      return TD_VERSION;					    \
  } while (0)

  GET_FUNCREF (link_map, get_tls_modid,		"p",		"i");
  GET_FUNCREF (thread, from_lwpid,		"i",		"ip");
  GET_FUNCREF (thread, iterate,			"Fi(po)oi",	"i");
  GET_FUNCREF (thread, get_event,		"pi",		"ii");
  GET_FUNCREF (thread, get_lwpid,		"p",		"ii");
  GET_FUNCREF (thread, get_priority,		"p",		"ii");
  GET_FUNCREF (thread, get_report_events,	"p",		"ii");
  GET_FUNCREF (thread, get_specific,		"p",		"ip");
  GET_FUNCREF (thread, get_start_routine,	"p",		"ip");
  GET_FUNCREF (thread, get_state,		"p",		"ii");
  GET_FUNCREF (thread, get_tlsbase,		"pi",		"ip");

#undef GET_FUNCREF

  /* Register the callback wrapper for td_ta_thr_iter.  */
  struct i8x_func *func;

  err = i8x_ctx_import_native (ta->ctx,
			       "libthread_db", "thr_iter_cb",
			       "po", "i",
			       td_ta_thr_iter_cb, &func);
  if (err != I8X_OK)
    return td_err_from_i8x_err (err);

  ta->thr_iter_cb = i8x_funcref_ref (i8x_func_get_funcref (func));
  func = i8x_func_unref (func);

  /* Create the inferior.  */
  err = i8x_inf_new (ta->ctx, &ta->inf);
  if (err != I8X_OK)
    return td_err_from_i8x_err (err);

  i8x_inf_set_userdata (ta->inf, ta, NULL);
  i8x_inf_set_relocate_fn (ta->inf, td_relocate_address);
  i8x_inf_set_read_mem_fn (ta->inf, td_read_memory);

  /* Create an execution context.  */
  err = i8x_xctx_new (ta->ctx, 512, &ta->xctx);
  if (err != I8X_OK)
    return td_err_from_i8x_err (err);

  return TD_OK;
}

/* Free resources allocated for TA.  */

td_err_e
td_ta_delete (td_thragent_t *ta)
{
  i8x_funcref_unref (ta->link_map_get_tls_modid);
  i8x_funcref_unref (ta->thread_from_lwpid);
  i8x_funcref_unref (ta->thread_iterate);
  i8x_funcref_unref (ta->thread_get_event);
  i8x_funcref_unref (ta->thread_get_lwpid);
  i8x_funcref_unref (ta->thread_get_priority);
  i8x_funcref_unref (ta->thread_get_report_events);
  i8x_funcref_unref (ta->thread_get_specific);
  i8x_funcref_unref (ta->thread_get_start_routine);
  i8x_funcref_unref (ta->thread_get_state);
  i8x_funcref_unref (ta->thread_get_tlsbase);

  i8x_funcref_unref (ta->thr_iter_cb);

  i8x_inf_unref (ta->inf);
  i8x_xctx_unref (ta->xctx);

  i8x_ctx_unref (ta->ctx);

  free (ta);

  return TD_OK;
}

/* Map thread library handle PT to thread debug library handle for
   process associated with TA and store result in *TH.  */

td_err_e
td_ta_map_id2thr (const td_thragent_t *ta, pthread_t pt,
		  td_thrhandle_t *th)
{
  return TD_NOCAPAB;
}

/* Map process ID LWPID to thread debug library handle for process
   associated with TA and store result in *TH.  */

td_err_e
td_ta_map_lwp2thr (const td_thragent_t *ta, lwpid_t lwpid,
		   td_thrhandle_t *th)
{
  union i8x_value args[1], rets[2];
  i8x_err_e err;

  args[0].i = lwpid;

  err = i8x_xctx_call (ta->xctx, ta->thread_from_lwpid, ta->inf,
		       args, rets);
  if (err != I8X_OK)
    return td_err_from_i8x_err (err);

  if (rets[1].i != TD_OK)
    return rets[1].i;

  th->th_ta_p = (td_thragent_t *) ta;
  th->th_unique = rets[0].p;

  return TD_OK;
}

/* Call for each thread in a process associated with TA the callback
   function CALLBACK.  */

td_err_e
td_ta_thr_iter (const td_thragent_t *ta, td_thr_iter_f *callback,
		void *cbdata_p, td_thr_state_e state, int ti_pri,
		sigset_t *ti_sigmask_p, unsigned int ti_user_flags)
{
  /* glibc's libthread_db completely ignores these two, but that
     seems wrong.  We're going to bail with a meaningful error.  */
  if (ti_sigmask_p != TD_SIGNO_MASK
      || ti_user_flags != TD_THR_ANY_USER_FLAGS)
    return TD_NOCAPAB;

  /* glibc's libthread_db doesn't ignore this one but maybe it
     should; what it actually does is return TD_OK without
     iterating the thread list.  That's totally misleading so
     again we're going to bail with a meaningful error.  */
  if (state != TD_THR_ANY_STATE)
    return TD_NOCAPAB;

  /* We have something glibc's thread::iterate can handle.  */
  union i8x_value args[3], rets[1];
  i8x_err_e err;

  args[0].f = ta->thr_iter_cb;
  args[1].p = cbdata_p;
  args[2].i = ti_pri;

  ((td_thragent_t *) ta)->thr_iter_cb_impl = callback;

  err = i8x_xctx_call (ta->xctx, ta->thread_iterate, ta->inf, args, rets);
  if (err != I8X_OK)
    return td_err_from_i8x_err (err);

  return rets[0].i;
}

/* Helper for td_ta_thr_iter.  */

static i8x_err_e
td_ta_thr_iter_cb (struct i8x_xctx *xctx, struct i8x_inf *inf,
		   struct i8x_func *func, union i8x_value *args,
		   union i8x_value *rets)
{
  td_thragent_t *ta = (td_thragent_t *) i8x_inf_get_userdata (inf);
  struct td_thrhandle th = {ta, args[0].p};

  rets[0].i = ta->thr_iter_cb_impl (&th, args[1].p);

  return I8X_OK;
}

/* Validate that TH is a thread handle.  */

td_err_e
td_thr_validate (const td_thrhandle_t *th)
{
  return TD_NOCAPAB;
}

/* Return information about thread TH.  */

td_err_e
td_thr_get_info (const td_thrhandle_t *th, td_thrinfo_t *infop)
{
  td_thragent_t *ta = th->th_ta_p;

  /* Clear first to provide reproducable results.  */
  memset (infop, 0, sizeof (td_thrinfo_t));

  /* Fill in information.  */
  infop->ti_tid = (thread_t) th->th_unique;
  infop->ti_ta_p = th->th_ta_p;
  infop->ti_type = TD_THR_USER;

  /* Fill in the fields we handle.  */
  union i8x_value args[2], rets[2];
  i8x_err_e err;

  args[0].p = th->th_unique;

#define GET_FIELD(fn, field, rtype)				    \
  do {								    \
    err = i8x_xctx_call (ta->xctx, ta->fn, ta->inf, args, rets);    \
    if (err != I8X_OK)						    \
      return td_err_from_i8x_err (err);				    \
								    \
    if (rets[1].i != TD_OK)					    \
      return rets[1].i;						    \
								    \
    infop->field = (typeof (infop->field)) rets[0].rtype;	    \
  } while (0)

  GET_FIELD (thread_get_lwpid, ti_lid, i);
  GET_FIELD (thread_get_priority, ti_pri, i);
  GET_FIELD (thread_get_report_events, ti_traceme, u);
  GET_FIELD (thread_get_specific, ti_tls, p);
  GET_FIELD (thread_get_start_routine, ti_startfunc, p);
  GET_FIELD (thread_get_state, ti_state, i);

#undef GET_FIELD

  for (int i = 0; i < TD_EVENTSIZE; i++)
    {
      args[1].i = i;

      err = i8x_xctx_call (ta->xctx, ta->thread_get_event, ta->inf,
			   args, rets);
      if (err != I8X_OK)
	return td_err_from_i8x_err (err);

      if (rets[1].i != TD_OK)
	return err;

      infop->ti_events.event_bits[i] = rets[0].u;
    }

  return TD_OK;
}

/* Get address of the given module's TLS storage area for the given
   thread.  */

td_err_e
td_thr_tlsbase (const td_thrhandle_t *th, unsigned long int modid,
		psaddr_t *base)
{
  td_thragent_t *ta = th->th_ta_p;

  union i8x_value args[2], rets[2];
  i8x_err_e err;

  args[0].p = th->th_unique;
  args[1].u = modid;

  err = i8x_xctx_call (ta->xctx, ta->thread_get_tlsbase, ta->inf,
		       args, rets);
  if (err != I8X_OK)
    return td_err_from_i8x_err (err);

  if (rets[1].i != TD_OK)
    return rets[1].i;

  *base = rets[0].p;

  return TD_OK;
}

/* Get address of thread local variable.  */

extern td_err_e
td_thr_tls_get_addr (const td_thrhandle_t *th, psaddr_t map_address,
		     size_t offset, psaddr_t *address)
{
  td_thragent_t *ta = th->th_ta_p;

  union i8x_value arg, ret;
  i8x_err_e err;

  arg.p = map_address;

  err = i8x_xctx_call (ta->xctx, ta->link_map_get_tls_modid, ta->inf,
		       &arg, &ret);

  if (err != I8X_OK)
    return td_err_from_i8x_err (err);

  err = td_thr_tlsbase (th, ret.u, address);
  if (err == TD_OK)
    *address += offset;

  return err;
}

/* Enable reporting for EVENT for thread TH.  */
extern td_err_e
td_thr_event_enable (const td_thrhandle_t *th, int event)
{
  return TD_NOCAPAB;
}