This repository has been archived by the owner on Jul 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
1357 lines (1235 loc) · 45.2 KB
/
main.go
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
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate bash -c "godoc . | sed '/COMMAND DOC/d; s/^ //' > README"
// pprof_mac_fix applies a binary patch to the OS X kernel in order to make
// pprof profiling report accurate values.
//
// Hooray Hooray Hooray
//
// The public beta of OS X 10.11 El Capitan appears to contain a fix for the
// underlying kernel bug. It therefore appears that pprof_mac_fix is unnecessary
// on that system: pprof will just work out of the box.
//
// If run on an OS X 10.11 system, pprof_mac_fix will report that the kernel
// is already correct without any patch.
//
// Warning Warning Warning
//
// This program is meant to modify the operating system kernel, the program
// that runs your computer and makes it safe for all the other programs to run.
// If you damage the kernel, your computer will not be able to boot.
//
// Before using this program, ensure you can boot into ``recovery mode.''
// Many recent Macs make this possible by holding down Alt/Option when you
// hear the boot chime and selecting the ``Recovery HD.'' Otherwise, you can boot
// to the opening screen of an install DVD or thumb drive.
//
// You have been warned.
//
// Compatibility
//
// This program has been used successfully on the following systems:
//
// OS X 10.6 Snow Leopard / Darwin 10.8 / i386 only
// OS X 10.7 Lion / Darwin 11.4 / i386 and x86_64
// OS X 10.8 Mountain Lion / Darwin 12.4 / x86_64 only
// OS X 10.9 Mavericks / Darwin 13.0 / x86_64 only
// OS X 10.10 Yosemite / Darwin 14.0 / x86_64 only
//
// Snow Leopard x86_64 may work too but is untried.
//
// An earlier version of this program shipped with a buggy patch
// for OS X 10.9 Mavericks/Darwin 13.0. If you used the old patch
// you are encouraged to restore your old kernel and patch using
// an updated copy of this program:
//
// go get -u rsc.io/pprof_mac_fix
//
// If running http://swtch.com/~rsc/macbug.c crashes your system,
// you have the buggy patch applied.
//
// Installation
//
// First, read the warning above.
//
// Next, install this program and run it. If the program finds that it knows
// how to patch your kernel, it will reinvoke itself using sudo, which will
// prompt for your password and install the new kernel. It saves the old
// kernel as a numbered file in the kernel source directory (the root directory
// or, for OS X 10.10 Yosemite, /System/Library/Kernels).
//
// go get rsc.io/pprof_mac_fix
// pprof_mac_fix
//
// Finally, cross your fingers and reboot.
//
// If all goes well, running ``uname -a'' will report the time at which you
// ran pprof_mac_fix as the kernel build time.
//
// If you have a Go tree built at tip,
//
// go test -v runtime/pprof
//
// should now say that the CPU profiling tests pass, whereas before they
// printed failure messages and were marked as skipped.
//
// Recovery
//
// If something goes wrong, you will need to restore the original kernel.
// To do this, boot into recovery mode.
// If you are using FileVault whole-disk encryption, start Disk Utility, unlock the disk,
// and then quit disk utility.
// (Disk Utility may be an option shown on the recovery mode screen or you may have to
// select it from the Utilities menu in the top-of-screen menu bar.)
// Start Terminal and then run these commands:
//
// cd /Volumes/Mac*HD*
// cp mach_kernel0 mach_kernel
// bless /Volumes/Mac*HD*/System/Library/CoreServices
//
// The Mac*HD* pattern matches "Macintosh HD" and "Macintosh HD " [sic].
// If you have changed your disk's volume name you may need to use a
// different pattern (run "mount" to see the mounted disks).
//
// I am not sure whether the bless command is strictly necessary.
//
// On OS X 10.10 Yosemite, the above command sequence changes to:
//
// cd /Volumes/Mac*HD*/System/Library/Kernels
// cp kernel0 kernel
// bless /Volumes/Mac*HD*/System/Library/CoreServices
//
// Reboot. You should be back to the original, unmodified kernel.
// Either way, you need to be able to
// start Terminal and, if you are using FileVault whole-disk encryption, Disk Utility.
//
// For details on creating a bootable recovery disk or bootable installation disk,
// see http://support.apple.com/kb/HT4848 and http://lifehacker.com/5928780/.
//
// Theory of Operation
//
// The program rewrites the kernel code that delivers the profiling signals
// SIGPROF and SIGVTALRM in response to setitimer(2) calls.
// Instead of delivering the signal to the process as a whole,
// the new code delivers the signal to the thread whose execution
// triggered the signal; that is, it delivers the signal to the thread
// that is actually running and should be profiled.
//
// The rewrite only edits code in the function named bsd_ast, which is
// in charge of little more than delivering these signals.
// It is therefore unlikely to cause problems in programs not using the
// signals. Of course, there are no safety nets when changing an operating
// system kernel; caution is warranted.
//
// A more detailed description is at http://research.swtch.com/macpprof.
//
package main // import "rsc.io/pprof_mac_fix"
import (
"bufio"
"bytes"
"debug/macho"
"encoding/binary"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
var _ time.Time
var dumpFlag = flag.Bool("dump", false, "kernel dump")
var arch = flag.String("arch", getArch(), "arch to modify")
func getArch() string {
out, _ := exec.Command("uname", "-m").CombinedOutput()
switch s := strings.TrimSpace(string(out)); s {
case "x86_64", "i386":
return s
}
return "x86_64"
}
func getOS() string {
out, _ := exec.Command("uname", "-r").CombinedOutput()
return strings.TrimSpace(string(out))
}
func main() {
log.SetFlags(0)
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [-arch ARCH] [oldkernel newkernel]\n\n", os.Args[0])
fmt.Fprintf(os.Stderr, "The -arch flag controls which kernel in a fat binary is modified.\n")
fmt.Fprintf(os.Stderr, "The default setting is the architecture reported by `uname -m`,\n")
fmt.Fprintf(os.Stderr, "on this machine %s.\n", getArch())
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, "With no kernel files specified, the behavior is to check\n")
fmt.Fprintf(os.Stderr, "that the kernel is recognized and then update the kernel\n")
fmt.Fprintf(os.Stderr, "in place, leaving a numbered backup file.\n")
fmt.Fprintf(os.Stderr, "\npprof_mac_fix version 10.10\n")
os.Exit(2)
}
flag.Parse()
if *dumpFlag {
if flag.NArg() != 1 {
fmt.Fprintf(os.Stderr, "usage: %s -dump [oldkernel]\n", os.Args[0])
os.Exit(2)
}
dump(loadKernel(flag.Arg(0)))
return
}
if flag.NArg() == 0 {
automatic()
return
}
if flag.NArg() != 2 {
flag.Usage()
}
k := loadKernel(flag.Arg(0))
fmt.Printf("old: %s\n", k.version)
fixIt(k)
// Update version string as displayed by uname -a.
copy(k.timestamp, []byte(time.Now().Format(time.UnixDate)))
fmt.Printf("new: %s\n", string(k.version))
if err := ioutil.WriteFile(flag.Arg(1), k.data, 0666); err != nil {
log.Fatal(err)
}
}
func fixIt(k *kernel) {
errs := fixAnyVersion(k)
if errs != nil {
if len(errs) == 1 && errs[0] == errPatched {
fmt.Fprintf(os.Stderr, "kernel %s already patched; not rewriting\n", k.file)
os.Exit(2)
}
if len(errs) == 1 && errs[0] == errNoBug {
fmt.Fprintf(os.Stderr, "kernel %s works without any patch; not rewriting\n", k.file)
os.Exit(2)
}
fmt.Fprintf(os.Stderr, "unrecognized kernel: %s\n", k.file)
for _, err := range errs {
fmt.Fprintf(os.Stderr, "%s\n", err)
}
fmt.Fprintf(os.Stderr, updateText, os.Args[0], k.file)
os.Exit(2)
}
}
func automatic() {
file := "/mach_kernel"
if os := getOS(); os >= "14.0" {
// Yosemite and later.
file = "/System/Library/Kernels/kernel"
}
k := loadKernel(file)
old := string(k.version)
fixIt(k)
// Now we know we can fix it. Make sure we are root.
if os.Getuid() != 0 {
fmt.Fprintf(os.Stderr, "running pprof_mac_fix using sudo for permission to rewrite kernel.\n")
self, err := exec.LookPath(os.Args[0])
if err != nil {
log.Fatal("cannot find path to binary: %v", err)
}
cmd := exec.Command("sudo", self)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "exec sudo: %v\n", err)
os.Exit(2)
}
return
}
// Make sure user wants kernel to be written.
fmt.Fprintf(os.Stderr, "ready to patch kernel: %s\n", k.file)
fmt.Fprintf(os.Stderr, "type 'yes' to continue: ")
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
os.Exit(2)
}
if line != "yes\n" {
fmt.Fprintf(os.Stderr, "aborted\n")
os.Exit(2)
}
oldBytes, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
n := 0
var newfile string
for ; ; n++ {
newfile = fmt.Sprintf("%s%d", file, n)
_, err := os.Stat(newfile)
if os.IsNotExist(err) {
break
}
if n >= 10000 {
fmt.Fprintf(os.Stderr, "cannot back up %s: cannot find suitable backup name\n", file)
}
}
err = ioutil.WriteFile(newfile, oldBytes, 0755)
if err != nil {
log.Fatalf("backing up kernel: %s", err)
}
fmt.Printf("kernel: %s\nbackup: %s\n", k.file, newfile)
if err := os.Chmod(file, 0755); err != nil {
log.Fatalf("changing kernel mode: %s", err)
}
fmt.Printf("old version: %s\n", old)
// Update version string as displayed by uname -a.
copy(k.timestamp, []byte(time.Now().Format(time.UnixDate)))
fmt.Printf("new version: %s\n", string(k.version))
if err := ioutil.WriteFile(file, k.data, 0755); err != nil {
log.Fatalf("writing new kernel: %s", err)
}
fmt.Printf("new kernel installed; reboot to use\n")
}
func fixAnyVersion(k *kernel) []error {
var errs []error
for _, f := range fixes {
err := f.apply(k.current_thread, k.bsd_ast)
if err == errPatched || err == errNoBug {
return []error{err}
}
if err != nil {
errs = append(errs, fmt.Errorf("%s: %v", f.version, err))
continue
}
return nil
}
return errs
}
var (
errPatched = fmt.Errorf("kernel already patched")
errNoBug = fmt.Errorf("kernel is correct without patch - Apple fixed the bug!")
)
var updateText = `
For an update, mail rsc@golang.org with the output printed by:
%s -dump %s
`
type kernel struct {
file string
data []byte
version []byte
timestamp []byte
current_thread []byte
bsd_ast []byte
}
type byValue []*macho.Symbol
func (x byValue) Len() int { return len(x) }
func (x byValue) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (x byValue) Less(i, j int) bool { return x[i].Value < x[j].Value }
var versionRE = regexp.MustCompile(
`Darwin Kernel Version [0-9]+\.[0-9]+\.[0-9]+: ` +
`([A-Z][a-z][a-z] [A-Z][a-z][a-z] [ 1-9][0-9] \d{2}:\d{2}:\d{2} [A-Z]{3} \d{4});[^\0]*`,
)
type fatHeader struct {
Magic uint32
NumArch uint32
Entry [4]struct {
CPUType uint32
CPUSubType uint32
Offset uint32
Size uint32
AlignBits uint32
}
}
func loadKernel(file string) *kernel {
data, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
k := &kernel{
file: file,
data: data,
}
kdata := data
var fat fatHeader
binary.Read(bytes.NewReader(data), binary.BigEndian, &fat)
if fat.Magic == 0xcafebabe {
// It is a fat binary.
n := int(fat.NumArch)
if n > len(fat.Entry) {
n = len(fat.Entry)
}
for i := range fat.Entry[:n] {
e := &fat.Entry[i]
switch {
case *arch == "x86_64" && e.CPUType == 0x01000007 && e.CPUSubType == 0x00000003,
*arch == "i386" && e.CPUType == 0x00000007 && e.CPUSubType == 0x00000003:
fmt.Printf("%s(%s) is at offset %d, size %d\n", file, *arch, e.Offset, e.Size)
kdata = data[e.Offset : e.Offset+e.Size]
goto HaveKdata
}
}
log.Fatalf("cannot find %s kernel in fat kernel binary", *arch)
HaveKdata:
}
if n := len(versionRE.FindAll(kdata, -1)); n == 0 {
log.Fatalf("cannot find kernel version string")
} else if n > 1 {
log.Printf("warning: found multiple kernel version strings")
}
m := versionRE.FindSubmatchIndex(kdata)
k.version = kdata[m[0]:m[1]]
k.timestamp = kdata[m[2]:m[3]]
// Look for current_thread body to make sure our inlining
// of it is correct.
f, err := macho.NewFile(bytes.NewReader(kdata))
if err != nil {
log.Fatal(err)
}
var syms []*macho.Symbol
for i := range f.Symtab.Syms {
syms = append(syms, &f.Symtab.Syms[i])
}
sort.Sort(byValue(syms))
for i, sym := range syms {
var save *[]byte
switch sym.Name {
case "_current_thread":
save = &k.current_thread
case "_bsd_ast":
save = &k.bsd_ast
}
if save == nil {
continue
}
sect := f.Sections[sym.Sect]
off := int(sect.Offset) + int(sym.Value-sect.Addr)
var n int
if i == len(syms)-1 {
n = int(sect.Addr + sect.Size - sym.Value)
} else {
n = int(syms[i+1].Value - sym.Value)
}
if off >= len(kdata) || off+n < off || off+n >= len(kdata) {
log.Fatalf("invalid address [%d:%d] for %s in data [:%d]", off, off+n, sym.Name, len(kdata))
}
*save = kdata[off : off+n]
}
if k.current_thread == nil {
log.Fatalf("cannot find current_thread in kernel")
}
if k.bsd_ast == nil {
log.Fatalf("cannot find bsd_ast in kernel")
}
return k
}
func dump(k *kernel) {
fmt.Printf("%s\nversion: %s\n", k.file, k.version)
dumpDisas(k, k.current_thread, "current_thread")
dumpDisas(k, k.bsd_ast, "bsd_ast")
}
var disasRE = regexp.MustCompile(`0x[0-9a-f]+\s+<\w*\+(\d+)>:`)
func dumpDisas(k *kernel, code []byte, name string) {
var args []string
if getOS() < "14." {
args = append(args, "-arch", *arch)
}
args = append(args, k.file)
cmd := exec.Command("gdb", args...)
cmd.Stdin = strings.NewReader("disas " + name + "\n")
disas, err := cmd.CombinedOutput()
fmt.Printf("$ gdb %s # disas %s\n", k.file, name)
if err != nil {
fmt.Printf("running gdb 'disas %s': %v\n", name, err)
}
lines := strings.Split(string(disas), "\n")
lastOff := -1
flush := func(off int) {
off1 := off
if lastOff >= 0 && off1 < 0 {
off1 = len(code)
}
if lastOff >= 0 && off1 > lastOff && off1 <= len(code) {
n := off1 - lastOff
if n > 20 {
n = 20
}
fmt.Printf("\t% x\n", code[lastOff:lastOff+n])
}
lastOff = off
}
for _, line := range lines {
m := disasRE.FindStringSubmatch(line)
if m == nil {
flush(-1)
} else {
n, _ := strconv.Atoi(m[1])
flush(n)
}
fmt.Printf("%s\n", line)
}
flush(-1)
}
type pattern struct {
mark []int
mask []byte
value []byte
leading []byte
}
var commentRE = regexp.MustCompile(`//[^\n]*`)
func mustCompile(text string) *pattern {
p := new(pattern)
text = commentRE.ReplaceAllString(text, "")
for _, f := range strings.Fields(text) {
if f == "*" {
p.mark = append(p.mark, len(p.value))
continue
}
val := f
mask := "0xff"
if i := strings.Index(f, "/"); i >= 0 {
val, mask = f[:i], f[i+1:]
}
v, err := strconv.ParseUint(val, 0, 8)
if err != nil {
log.Fatalf("invalid value %s", f)
}
m, err := strconv.ParseUint(mask, 0, 8)
if err != nil {
log.Fatalf("invalid value %s", f)
}
p.value = append(p.value, byte(v))
p.mask = append(p.mask, byte(m))
}
i := 0
for i < len(p.mask) && p.mask[i] == 0xff {
i++
}
p.leading = p.value[:i]
return p
}
func (p *pattern) findAll(data []byte) []int {
var out []int
for i := 0; i < len(data); i++ {
j := p.find(data[i:])
if j < 0 {
break
}
i += j
out = append(out, i)
}
return out
}
func (p *pattern) find(data []byte) int {
for i := 0; i < len(data); i++ {
j := bytes.Index(data[i:], p.leading)
if j < 0 {
return -1
}
i += j
if p.matchStart(data, i) != nil {
return i
}
}
return -1
}
func (p *pattern) matchStart(data []byte, off int) []int {
sub := data[off:]
if len(p.value) > len(sub) {
return nil
}
for i := range p.value {
if sub[i]&p.mask[i] != p.value[i] {
return nil
}
}
out := []int{}
for _, m := range p.mark {
out = append(out, off+m)
}
return out
}
type fix struct {
version string
current_thread *pattern
bsd_ast []*pattern
}
var le = binary.LittleEndian
func (f *fix) apply(current_thread []byte, bsd_ast []byte) error {
m := f.current_thread.matchStart(current_thread, 0)
if m == nil {
return fmt.Errorf("cannot match current_thread")
}
tlsOff := binary.LittleEndian.Uint32(current_thread[m[0]:])
total := 0
var timers [][]int
for _, p := range f.bsd_ast {
m := p.findAll(bsd_ast)
total += len(m)
timers = append(timers, m)
}
var replace [][]byte
if f.version >= "15." && total == 2 && len(timers) == 1 && len(timers[0]) == 2 && strings.HasSuffix(f.version, "no bug") {
return errNoBug
}
if f.version >= "14." {
if total != 2 || len(timers) != 1 || len(timers[0]) != 2 {
return fmt.Errorf("cannot match bsd_ast 14 timer call %d %d", total, len(timers[0]))
}
if strings.HasSuffix(f.version, "fixed") {
return errPatched
}
var err error
new, err := f.apply14(tlsOff, bsd_ast, timers)
if err != nil {
return err
}
if len(new) != len(bsd_ast) {
return fmt.Errorf("cannot replace bsd_ast 14 - wrong replacement length %d %d", len(bsd_ast), len(new))
}
copy(bsd_ast, new)
return nil
} else if f.version >= "13." {
if strings.HasSuffix(f.version, "fixed") && total == 2 {
return errPatched
}
if total != 3 || len(timers) != 2 || len(timers[0]) != 2 {
return fmt.Errorf("cannot match bsd_ast 13 timer call %d %d", total, len(timers[0]))
}
var err error
replace, err = f.apply13(tlsOff, bsd_ast, timers)
if err != nil {
return err
}
goto done
} else if total != 2 {
if total == 0 {
return fmt.Errorf("cannot match bsd_ast timer call")
}
if total == 1 {
return fmt.Errorf("1 match for bsd_ast timer call %v, want 2", timers)
}
return fmt.Errorf("%d matches for bsd_ast timer call %v, want 2", total, timers)
}
if strings.HasSuffix(f.version, "fixed") {
return errPatched
}
for i, timer1 := range timers {
for _, timer := range timer1 {
p := f.bsd_ast[i]
old := bsd_ast[timer:]
m = p.matchStart(old, 0)
if m == nil {
// shouldn't happen - we found the offset above
return fmt.Errorf("cannot match bsd_ast timer")
}
if !bytes.Equal(old[m[0]:m[1]], old[m[2]:m[3]]) {
return fmt.Errorf("bsd_ast timer sequences differ")
}
if old[m[0]-2]&0xF8 != 0x70 {
return fmt.Errorf("bsd_ast timer sequence missing conditional jump %x", old[m[0]-2])
}
if old[m[2]-2] != 0xeb {
return fmt.Errorf("bsd_ast timer sequence missing unconditional jump %x", old[m[2]-2])
}
var new []byte
new = append(new, old[m[0]:m[1]]...)
new = append(new, old[:m[0]]...)
// Last instruction is cond jump over call sequence.
// We moved old[m[0]:m[1]] out,
// so the jump must be shortened.
new[len(new)-1] -= byte(m[1] - m[0])
// "If" body.
// The call instruction hasn't moved, so it's still correct.
// The jmp at the end skips the else body,
// so it must be shortened.
new = append(new, old[m[1]:m[2]]...)
new[len(new)-1] -= byte(m[1] - m[0])
// "Else" body.
// The call instruction has moved, so the offset must be adjusted.
new = append(new, old[m[3]:m[4]]...)
le.PutUint32(new[len(new)-4:], le.Uint32(new[len(new)-4:])-uint32(len(new)-m[4]))
// Set up arguments to psignal_internal.
if f.version == "11.4.2 (i386)" {
// This version passes the arguments to psignal_internal
// differently than other i386 versions.
new = append(new,
// xor %ecx, %ecx
0x31, 0xc9,
// xor %edx, %edx
0x31, 0xd2,
// mov %gs:threadTLS, %eax
0x65, 0x8b, 0x04, 0x25,
byte(tlsOff), byte(tlsOff>>8), byte(tlsOff>>16), byte(tlsOff>>24),
// mov %eax, (%esp)
0x89, 0x04, 0x24,
// movl $4, 4(%esp)
0xc7, 0x44, 0x24, 0x04, 0x04, 0x00, 0x00, 0x00,
// movl $0x1a (or $0x1b), 8(%esp)
0xc7, 0x44, 0x24, 0x08, old[m[5]], 0x00, 0x00, 0x00,
)
} else if strings.Contains(f.version, "i386") {
new = append(new,
// xor %eax, %eax
0x31, 0xc0,
// xor %edx, %edx
0x31, 0xd2,
// mov %gs:threadTLS, %ecx
0x65, 0x8b, 0x0d,
byte(tlsOff), byte(tlsOff>>8), byte(tlsOff>>16), byte(tlsOff>>24),
// mov $4, (%esp)
0xc7, 0x04, 0x24, 0x04, 0x00, 0x00, 0x00,
// mov $0x1a (or $0x1b), 4(%esp)
0xc7, 0x44, 0x24, 0x04, old[m[5]], 0x00, 0x00, 0x00,
)
} else { // x86_64
new = append(new,
// xor %edi, %edi
0x31, 0xff,
// xor %esi, %esi
0x31, 0xf6,
// mov %gs:threadTLS, %rdx
0x65, 0x48, 0x8b, 0x14, 0x25,
byte(tlsOff), byte(tlsOff>>8), byte(tlsOff>>16), byte(tlsOff>>24),
// mov $4, %ecx
0xb9, 0x04, 0x00, 0x00, 0x00,
// mov $0x1a (or $0x1b), %r8d
0x41, 0xb8, old[m[5]], 0x00, 0x00, 0x00,
)
}
for len(new) < m[6] {
new = append(new, 0x90) // nop
}
if len(new) > m[6] {
return fmt.Errorf("bsd_ast timer sequence rewrite too long")
}
replace = append(replace, new)
}
}
done:
// Commit rewrite.
n := 0
for _, timer1 := range timers {
for _, timer := range timer1 {
copy(bsd_ast[timer:], replace[n])
n++
}
}
return nil
}
// Darwin 10.8.0 (Snow Leopard)
var current_thread_leave = mustCompile(`
0x55 // 0 push %rbp
0x48 0x89 0xe5 // 1 mov %rsp, %rbp
0x65 0x48 0x8b 0x04 0x25 // 4 mov %gs:0x8 %rax
* 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00
0xc9 // 13 leaveq
0xc3 // 14 retq
`)
var current_thread_leave_i386 = mustCompile(`
0x55 // 0 push %rbp
0x89 0xe5 // 1 mov %rsp, %rbp
0x65 0xa1 // 3 mov %gs:0x8, %rax
* 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00
0xc9 // 9 leaveq
0xc3 // 14 retq
`)
var bsd_ast_10_8_0_a = mustCompile(`
0x49 0x83 0xbc 0x24 0x00/0x0f 0x01 0x00 0x00 0x00 // 0 cmpq $0x0,0x1b0(%r12)
0x75 0x0c // 9 jne +12 [23]
0x41 0x8b 0x84 0x24 0x08/0x0f 0x01 0x00 0x00 // 11 mov 0x1b8(%r12),%eax
0x85 0xc0 // 19 test %eax,%eax
0x74 0x11 // 21 je +17 [40]
* 0x49 0x8b 0x7c 0x24 0x18 // 23 mov 0x18(%r12),%rdi
0xbe 0x00/0xfc 0x00 0x00 0x00 * // 28 mov $0x1,%esi
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 33 call task_vtimer_set
0xeb 0x0f // 38 jmp +15 [55]
* 0x49 0x8b 0x7c 0x24 0x18 // 40 mov 0x18(%r12),%rdi
0xbe 0x00/0xfc 0x00 0x00 0x00 * // 45 mov $0x1,%esi
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 50 call task_vtimer_clear
* 0x41 0xb8 * 0x1a/0xfe 0x00 0x00 0x00 // 55 mov $0x1a,%r8d
0x31 0xc9 // 61 xor %ecx,%ecx
0x31 0xd2 // 63 xor %edx,%edx
0x31 0xf6 // 65 xor %esi,%esi
0x4c 0x89 0xe7 * // 67 mov %r12,%rdi
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 70 call psignal_internal
`)
var bsd_ast_10_8_0_b = mustCompile(`
0x49 0x83 0xbc 0x24 0x00/0x0f 0x01 0x00 0x00 0x00 // 0 cmpq $0x0,0x1d0(%r12)
0x75 0x0d // 9 jne +13
0x45 0x8b 0x9c 0x24 0x08/0x0f 0x01 0x00 0x00 // 11 mov 0x1d8(%r12),%r11d
0x45 0x85 0xdb // 19 test %r11d,%r11d
0x74 0x11 // 21 je +17
* 0x49 0x8b 0x7c 0x24 0x18 // 23 mov 0x18(%r12),%rdi
0xbe 0x00/0xfc 0x00 0x00 0x00 * // 28 mov $0x2,%esi
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 33 call task_vtimer_set
0xeb 0x0f // 38 jmp +15
* 0x49 0x8b 0x7c 0x24 0x18 // 40 mov 0x18(%r12),%rdi
0xbe 0x00/0xfc 0x00 0x00 0x00 * // 45 mov $0x2,%esi
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 50 call task_vtimer_clear
* 0x41 0xb8 * 0x1a/0xfe 0x00 0x00 0x00 // 55 mov $0x1b,%r8d
0x31 0xc9 // 61 xor %ecx,%ecx
0x31 0xd2 // 63 xor %edx,%edx
0x31 0xf6 // 65 xor %esi,%esi
0x4c 0x89 0xe7 * // 67 mov %r12,%rdi
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 70 call psignal_internal
`)
var bsd_ast_10_8_0_i386_a = mustCompile(`
0x8b 0x8b 0xec 0x00 0x00 0x00 // 0 mov 0xec(%ebx),%ecx
0x85 0xc9 // 6 test %ecx,%ecx
0x75 0x0a // 8 jne +10
0x8b 0x93 0xf0 0x00 0x00 0x00 // 10 mov 0xf0(%ebx),%edx
0x85 0xd2 // 16 test %edx,%edx
0x74 0x15 // 18 je +21
* 0x8b 0x43 0x0c // 20 mov 0xc(%ebx),%eax
0xc7 0x44 0x24 0x04 0x01 0x00 0x00 0x00 // 23 movl $0x1,0x4(%esp)
0x89 0x04 0x24 * // 31 mov %eax,(%esp)
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 34 call task_vtimer_set
0xeb 0x13 // 39 jmp +19
* 0x8b 0x43 0x0c // 41 mov 0xc(%ebx),%eax
0xc7 0x44 0x24 0x04 0x01 0x00 0x00 0x00 // 44 movl $0x1,0x4(%esp)
0x89 0x04 0x24 * // 52 mov %eax,(%esp)
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 55 call task_vtimer_clear
* 0xc7 0x44 0x24 0x04 * 0x1a 0x00 0x00 0x00 // 60 movl $0x1a,0x4(%esp)
0xc7 0x04 0x24 0x00 0x00 0x00 0x00 // 68 movl $0x0,(%esp)
0x31 0xc9 // 75 xor %ecx,%ecx
0x31 0xd2 // 77 xor %edx,%edx
0x89 0xd8 * // 79 mov %ebx,%eax
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 81 call psignal_internal
`)
var bsd_ast_10_8_0_i386_b = mustCompile(`
0x8b 0x83 0xfc 0x00 0x00 0x00 // 0 mov 0xfc(%ebx),%eax
0x85 0xc0 // 6 test %eax,%eax
0x75 0x0a // 8 jne +10
0x8b 0x83 0x00 0x01 0x00 0x00 // 10 mov 0x100(%ebx),%eax
0x85 0xc0 // 16 test %eax,%eax
0x74 0x15 // 18 je +21
* 0x8b 0x43 0x0c // 20 mov 0xc(%ebx),%eax
0xc7 0x44 0x24 0x04 0x02 0x00 0x00 0x00 // 23 movl $0x2,0x4(%esp)
0x89 0x04 0x24 * // 31 mov %eax,(%esp)
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 34 call task_vtimer_set
0xeb 0x13 // 39 jmp +19
* 0x8b 0x43 0x0c // 41 mov 0xc(%ebx),%eax
0xc7 0x44 0x24 0x04 0x02 0x00 0x00 0x00 // 44 movl $0x2,0x4(%esp)
0x89 0x04 0x24 * // 52 mov %eax,(%esp)
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 55 call task_vtimer_clear
* 0xc7 0x44 0x24 0x04 * 0x1b 0x00 0x00 0x00 // 60 movl $0x1b,0x4(%esp)
0xc7 0x04 0x24 0x00 0x00 0x00 0x00 // 68 movl $0x0,(%esp)
0x31 0xc9 // 75 xor %ecx,%ecx
0x31 0xd2 // 77 xor %edx,%edx
0x89 0xd8 * // 79 mov %ebx,%eax
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 81 call psignal_internal
`)
var bsd_ast_10_8_0_fixed = mustCompile(`
0x31 0xff // xor %edi, %edi
0x31 0xf6 // xor %esi, %esi
0x65 0x48 0x8b 0x14 0x25 0x08 0x00 0x00 0x00 // mov %gs:0x8, %rdx
0xb9 0x04 0x00 0x00 0x00 // mov $0x4, %ecx
0x41 0xb8 0x1a/0xfe 0x00 0x00 0x00 // mov $0x1a, %r8d [or $0x1b]
0x90 // nop
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // call psignal_internal
`)
var bsd_ast_10_8_0_i386_fixed = mustCompile(`
0x31 0xc0 // xor %eax, %eax
0x31 0xd2 // xor %edx, %edx
0x65 0x8b 0x0d 0x04 0x00 0x00 0x00 // mov %gs:0x4, %ecx
0xc7 0x04 0x24 0x04 0x00 0x00 0x00 // mov $0x4, (%esp)
0xc7 0x44 0x24 0x04 0x1a/0xfe 0x00 0x00 0x00 // mov $0x1a, 0x4(%esp) [or $0x1b]
0x90 // nop
0x90 // nop
0x90 // nop
0x90 // nop
0x90 // nop
0x90 // nop
0x90 // nop
0x90 // nop
0x90 // nop
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // call psignal_internal
`)
var fix_10_8_0 = fix{
"10.8.0",
current_thread_leave,
[]*pattern{bsd_ast_10_8_0_a, bsd_ast_10_8_0_b},
}
var fix_10_8_0_fixed = fix{
"10.8.0 fixed",
current_thread_leave,
[]*pattern{bsd_ast_10_8_0_fixed},
}
var fix_10_8_0_i386 = fix{
"10.8.0 (i386)",
current_thread_leave_i386,
[]*pattern{bsd_ast_10_8_0_i386_a, bsd_ast_10_8_0_i386_b},
}
var fix_10_8_0_i386_fixed = fix{
"10.8.0 (i386) fixed",
current_thread_leave_i386,
[]*pattern{bsd_ast_10_8_0_i386_fixed},
}
// Darwin 11.4.2 (Lion)
var current_thread_pop = mustCompile(`
0x55 // 0 push %rbp
0x48 0x89 0xe5 // 1 mov %rsp, %rbp
0x65 0x48 0x8b 0x04 0x25 // 4 mov %gs:0x8 %rax
* 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00
0x5d // 13 pop %rbp
0xc3 // 14 retq
0x90 // 15 nop
`)
var current_thread_pop_i386 = mustCompile(`
0x55 // 0 push %rbp
0x89 0xe5 // 1 mov %rsp, %rbp
0x65 0xa1 // 3 mov %gs:0x4, %rax
* 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00
0x5d // 9 pop %rbp
0xc3 // 14 retq
`)
var bsd_ast_11_4_2 = mustCompile(`
0x49 0x83 0xbe 0xc0/0xdf 0x01 0x00 0x00 0x00 // 0 cmpq $0x0,0x1c0(%r14)
0x75 0x0a // 8 jne +10
0x41 0x83 0xbe 0xc8/0xdf 0x01 0x00 0x00 0x00 // 10 cmpl $0x0,0x1c8(%r14)
0x74 0x10 // 18 je +16
* 0x49 0x8b 0x7e 0x18 // 20 mov 0x18(%r14),%rdi
0xbe 0x00/0xfc 0x00 0x00 0x00 * // 24 mov $0x1,%esi
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 29 call task_vtimer_set
0xeb 0x0e // 34 jmp +15
* 0x49 0x8b 0x7e 0x18 // 36 mov 0x18(%r14),%rdi
0xbe 0x00/0xfc 0x00 0x00 0x00 * // 40 mov $0x1,%esi
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 45 call task_vtimer_clear
* 0x31 0xf6 // 50 xor %esi,%esi
0x31 0xc9 // 52 xor %ecx,%ecx
0x41 0xb8 * 0x1a/0xfe 0x00 0x00 0x00 // 54 mov $0x1a,%r8d
0x4c 0x89 0xf7 // 60 mov %r14,%rdi
0x31 0xd2 * // 63 xor %edx,%edx
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 65 call psignal_internal
`)
var bsd_ast_11_4_2_i386 = mustCompile(`
0x83 0xbe 0x04/0xef 0x01 0x00 0x00 0x00 // 0 cmpl $0x0,0x104(%esi)
0x75 0x09 // 7 jne +9
0x83 0xbe 0x08/0xef 0x01 0x00 0x00 0x00 // 9 cmpl $0x0,0x108(%esi)
0x74 0x15 // 16 je +21
* 0x8b 0x46 0x0c // 18 mov 0xc(%esi),%eax
0x89 0x04 0x24 // 21 mov %eax,(%esp)
0xc7 0x44 0x24 0x04 0x00/0xfc 0x00 0x00 0x00 * // 24 movl $0x1,0x4(%esp)
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 32 call task_vtimer_set
0xeb 0x13 // 37 jmp +19
* 0x8b 0x46 0x0c // 39 mov 0xc(%esi),%eax
0x89 0x04 0x24 // 42 mov %eax,(%esp)
0xc7 0x44 0x24 0x04 0x00/0xfc 0x00 0x00 0x00 * // 45 movl $0x1,0x4(%esp)
0xe8 0x00/0x00 0x00/0x00 0x00/0x00 0x00/0x00 // 53 call task_vtimer_clear
* 0xc7 0x44 0x24 0x08 * 0x1a/0xfe 0x00 0x00 0x00 // 58 movl $0x1a,0x8(%esp)
0xc7 0x44 0x24 0x04 0x00 0x00 0x00 0x00 // 66 movl $0x0,0x4(%esp)
0xc7 0x04 0x24 0x00 0x00 0x00 0x00 // 74 movl $0x0,(%esp)