1#!/usr/bin/env perl
2# SPDX-License-Identifier: GPL-2.0-only
3# (c) 2008, Steven Rostedt <srostedt@redhat.com>
4#
5# recordmcount.pl - makes a section called __mcount_loc that holds
6#                   all the offsets to the calls to mcount.
7#
8#
9# What we want to end up with this is that each object file will have a
10# section called __mcount_loc that will hold the list of pointers to mcount
11# callers. After final linking, the vmlinux will have within .init.data the
12# list of all callers to mcount between __start_mcount_loc and __stop_mcount_loc.
13# Later on boot up, the kernel will read this list, save the locations and turn
14# them into nops. When tracing or profiling is later enabled, these locations
15# will then be converted back to pointers to some function.
16#
17# This is no easy feat. This script is called just after the original
18# object is compiled and before it is linked.
19#
20# When parse this object file using 'objdump', the references to the call
21# sites are offsets from the section that the call site is in. Hence, all
22# functions in a section that has a call site to mcount, will have the
23# offset from the beginning of the section and not the beginning of the
24# function.
25#
26# But where this section will reside finally in vmlinx is undetermined at
27# this point. So we can't use this kind of offsets to record the final
28# address of this call site.
29#
30# The trick is to change the call offset referring the start of a section to
31# referring a function symbol in this section. During the link step, 'ld' will
32# compute the final address according to the information we record.
33#
34# e.g.
35#
36#  .section ".sched.text", "ax"
37#        [...]
38#  func1:
39#        [...]
40#        call mcount  (offset: 0x10)
41#        [...]
42#        ret
43#  .globl fun2
44#  func2:             (offset: 0x20)
45#        [...]
46#        [...]
47#        ret
48#  func3:
49#        [...]
50#        call mcount (offset: 0x30)
51#        [...]
52#
53# Both relocation offsets for the mcounts in the above example will be
54# offset from .sched.text. If we choose global symbol func2 as a reference and
55# make another file called tmp.s with the new offsets:
56#
57#  .section __mcount_loc
58#  .quad  func2 - 0x10
59#  .quad  func2 + 0x10
60#
61# We can then compile this tmp.s into tmp.o, and link it back to the original
62# object.
63#
64# In our algorithm, we will choose the first global function we meet in this
65# section as the reference. But this gets hard if there is no global functions
66# in this section. In such a case we have to select a local one. E.g. func1:
67#
68#  .section ".sched.text", "ax"
69#  func1:
70#        [...]
71#        call mcount  (offset: 0x10)
72#        [...]
73#        ret
74#  func2:
75#        [...]
76#        call mcount (offset: 0x20)
77#        [...]
78#  .section "other.section"
79#
80# If we make the tmp.s the same as above, when we link together with
81# the original object, we will end up with two symbols for func1:
82# one local, one global.  After final compile, we will end up with
83# an undefined reference to func1 or a wrong reference to another global
84# func1 in other files.
85#
86# Since local objects can reference local variables, we need to find
87# a way to make tmp.o reference the local objects of the original object
88# file after it is linked together. To do this, we convert func1
89# into a global symbol before linking tmp.o. Then after we link tmp.o
90# we will only have a single symbol for func1 that is global.
91# We can convert func1 back into a local symbol and we are done.
92#
93# Here are the steps we take:
94#
95# 1) Record all the local and weak symbols by using 'nm'
96# 2) Use objdump to find all the call site offsets and sections for
97#    mcount.
98# 3) Compile the list into its own object.
99# 4) Do we have to deal with local functions? If not, go to step 8.
100# 5) Make an object that converts these local functions to global symbols
101#    with objcopy.
102# 6) Link together this new object with the list object.
103# 7) Convert the local functions back to local symbols and rename
104#    the result as the original object.
105# 8) Link the object with the list object.
106# 9) Move the result back to the original object.
107#
108
109use warnings;
110use strict;
111
112my $P = $0;
113$P =~ s@.*/@@g;
114
115my $V = '0.1';
116
117if ($#ARGV != 11) {
118	print "usage: $P arch endian bits objdump objcopy cc ld nm rm mv is_module inputfile\n";
119	print "version: $V\n";
120	exit(1);
121}
122
123my ($arch, $endian, $bits, $objdump, $objcopy, $cc,
124    $ld, $nm, $rm, $mv, $is_module, $inputfile) = @ARGV;
125
126# This file refers to mcount and shouldn't be ftraced, so lets' ignore it
127if ($inputfile =~ m,kernel/trace/ftrace\.o$,) {
128    exit(0);
129}
130
131# Acceptable sections to record.
132my %text_sections = (
133     ".text" => 1,
134     ".init.text" => 1,
135     ".ref.text" => 1,
136     ".sched.text" => 1,
137     ".spinlock.text" => 1,
138     ".irqentry.text" => 1,
139     ".softirqentry.text" => 1,
140     ".kprobes.text" => 1,
141     ".cpuidle.text" => 1,
142     ".text.unlikely" => 1,
143);
144
145# Acceptable section-prefixes to record.
146my %text_section_prefixes = (
147     ".text." => 1,
148);
149
150# Note: we are nice to C-programmers here, thus we skip the '||='-idiom.
151$objdump = 'objdump' if (!$objdump);
152$objcopy = 'objcopy' if (!$objcopy);
153$cc = 'gcc' if (!$cc);
154$ld = 'ld' if (!$ld);
155$nm = 'nm' if (!$nm);
156$rm = 'rm' if (!$rm);
157$mv = 'mv' if (!$mv);
158
159#print STDERR "running: $P '$arch' '$objdump' '$objcopy' '$cc' '$ld' " .
160#    "'$nm' '$rm' '$mv' '$inputfile'\n";
161
162my %locals;		# List of local (static) functions
163my %weak;		# List of weak functions
164my %convert;		# List of local functions used that needs conversion
165
166my $type;
167my $local_regex;	# Match a local function (return function)
168my $weak_regex; 	# Match a weak function (return function)
169my $section_regex;	# Find the start of a section
170my $function_regex;	# Find the name of a function
171			#    (return offset and func name)
172my $mcount_regex;	# Find the call site to mcount (return offset)
173my $mcount_adjust;	# Address adjustment to mcount offset
174my $alignment;		# The .align value to use for $mcount_section
175my $section_type;	# Section header plus possible alignment command
176
177if ($arch =~ /(x86(_64)?)|(i386)/) {
178    if ($bits == 64) {
179	$arch = "x86_64";
180    } else {
181	$arch = "i386";
182    }
183}
184
185#
186# We base the defaults off of i386, the other archs may
187# feel free to change them in the below if statements.
188#
189$local_regex = "^[0-9a-fA-F]+\\s+t\\s+(\\S+)";
190$weak_regex = "^[0-9a-fA-F]+\\s+([wW])\\s+(\\S+)";
191$section_regex = "Disassembly of section\\s+(\\S+):";
192$function_regex = "^([0-9a-fA-F]+)\\s+<([^^]*?)>:";
193$mcount_regex = "^\\s*([0-9a-fA-F]+):.*\\s(mcount|__fentry__)\$";
194$section_type = '@progbits';
195$mcount_adjust = 0;
196$type = ".long";
197
198if ($arch eq "x86_64") {
199    $mcount_regex = "^\\s*([0-9a-fA-F]+):.*\\s(mcount|__fentry__)([+-]0x[0-9a-zA-Z]+)?\$";
200    $type = ".quad";
201    $alignment = 8;
202    $mcount_adjust = -1;
203
204    # force flags for this arch
205    $ld .= " -m elf_x86_64";
206    $objdump .= " -M x86-64";
207    $objcopy .= " -O elf64-x86-64";
208    $cc .= " -m64";
209
210} elsif ($arch eq "i386") {
211    $alignment = 4;
212    $mcount_adjust = -1;
213
214    # force flags for this arch
215    $ld .= " -m elf_i386";
216    $objdump .= " -M i386";
217    $objcopy .= " -O elf32-i386";
218    $cc .= " -m32";
219
220} elsif ($arch eq "s390" && $bits == 64) {
221    if ($cc =~ /-DCC_USING_HOTPATCH/) {
222	$mcount_regex = "^\\s*([0-9a-fA-F]+):\\s*c0 04 00 00 00 00\\s*(brcl\\s*0,|jgnop\\s*)[0-9a-f]+ <([^\+]*)>\$";
223	$mcount_adjust = 0;
224    }
225    $alignment = 8;
226    $type = ".quad";
227    $ld .= " -m elf64_s390";
228    $cc .= " -m64";
229
230} elsif ($arch eq "sh") {
231    $alignment = 2;
232
233    # force flags for this arch
234    $ld .= " -m shlelf_linux";
235    if ($endian eq "big") {
236	$objcopy .= " -O elf32-shbig-linux";
237    } else {
238	$objcopy .= " -O elf32-sh-linux";
239    }
240
241} elsif ($arch eq "powerpc") {
242    my $ldemulation;
243
244    $local_regex = "^[0-9a-fA-F]+\\s+t\\s+(\\.?\\S+)";
245    # See comment in the sparc64 section for why we use '\w'.
246    $function_regex = "^([0-9a-fA-F]+)\\s+<(\\.?\\w*?)>:";
247    $mcount_regex = "^\\s*([0-9a-fA-F]+):.*\\s\\.?_mcount\$";
248
249    if ($endian eq "big") {
250	    $cc .= " -mbig-endian ";
251	    $ld .= " -EB ";
252	    $ldemulation = "ppc"
253    } else {
254	    $cc .= " -mlittle-endian ";
255	    $ld .= " -EL ";
256	    $ldemulation = "lppc"
257    }
258    if ($bits == 64) {
259	$type = ".quad";
260	$cc .= " -m64 ";
261	$ld .= " -m elf64".$ldemulation." ";
262    } else {
263	$cc .= " -m32 ";
264	$ld .= " -m elf32".$ldemulation." ";
265    }
266
267} elsif ($arch eq "arm") {
268    $alignment = 2;
269    $section_type = '%progbits';
270    $mcount_regex = "^\\s*([0-9a-fA-F]+):\\s*R_ARM_(CALL|PC24|THM_CALL)" .
271			"\\s+(__gnu_mcount_nc|mcount)\$";
272
273} elsif ($arch eq "arm64") {
274    $alignment = 3;
275    $section_type = '%progbits';
276    $mcount_regex = "^\\s*([0-9a-fA-F]+):\\s*R_AARCH64_CALL26\\s+_mcount\$";
277    $type = ".quad";
278} elsif ($arch eq "sparc64") {
279    # In the objdump output there are giblets like:
280    # 0000000000000000 <igmp_net_exit-0x18>:
281    # As there's some data blobs that get emitted into the
282    # text section before the first instructions and the first
283    # real symbols.  We don't want to match that, so to combat
284    # this we use '\w' so we'll match just plain symbol names,
285    # and not those that also include hex offsets inside of the
286    # '<>' brackets.  Actually the generic function_regex setting
287    # could safely use this too.
288    $function_regex = "^([0-9a-fA-F]+)\\s+<(\\w*?)>:";
289
290    # Sparc64 calls '_mcount' instead of plain 'mcount'.
291    $mcount_regex = "^\\s*([0-9a-fA-F]+):.*\\s_mcount\$";
292
293    $alignment = 8;
294    $type = ".xword";
295    $ld .= " -m elf64_sparc";
296    $cc .= " -m64";
297    $objcopy .= " -O elf64-sparc";
298} elsif ($arch eq "mips") {
299    # To enable module support, we need to enable the -mlong-calls option
300    # of gcc for module, after using this option, we can not get the real
301    # offset of the calling to _mcount, but the offset of the lui
302    # instruction or the addiu one. herein, we record the address of the
303    # first one, and then we can replace this instruction by a branch
304    # instruction to jump over the profiling function to filter the
305    # indicated functions, or switch back to the lui instruction to trace
306    # them, which means dynamic tracing.
307    #
308    #       c:	3c030000 	lui	v1,0x0
309    #			c: R_MIPS_HI16	_mcount
310    #			c: R_MIPS_NONE	*ABS*
311    #			c: R_MIPS_NONE	*ABS*
312    #      10:	64630000 	daddiu	v1,v1,0
313    #			10: R_MIPS_LO16	_mcount
314    #			10: R_MIPS_NONE	*ABS*
315    #			10: R_MIPS_NONE	*ABS*
316    #      14:	03e0082d 	move	at,ra
317    #      18:	0060f809 	jalr	v1
318    #
319    # for the kernel:
320    #
321    #     10:   03e0082d        move    at,ra
322    #	  14:   0c000000        jal     0 <loongson_halt>
323    #                    14: R_MIPS_26   _mcount
324    #                    14: R_MIPS_NONE *ABS*
325    #                    14: R_MIPS_NONE *ABS*
326    #	 18:   00020021        nop
327    if ($is_module eq "0") {
328	    $mcount_regex = "^\\s*([0-9a-fA-F]+): R_MIPS_26\\s+_mcount\$";
329    } else {
330	    $mcount_regex = "^\\s*([0-9a-fA-F]+): R_MIPS_HI16\\s+_mcount\$";
331    }
332    $objdump .= " -Melf-trad".$endian."mips ";
333
334    if ($endian eq "big") {
335	    $endian = " -EB ";
336	    $ld .= " -melf".$bits."btsmip";
337    } else {
338	    $endian = " -EL ";
339	    $ld .= " -melf".$bits."ltsmip";
340    }
341
342    $cc .= " -mno-abicalls -fno-pic -mabi=" . $bits . $endian;
343    $ld .= $endian;
344
345    if ($bits == 64) {
346	    $function_regex =
347		"^([0-9a-fA-F]+)\\s+<(.|[^\$]L.*?|\$[^L].*?|[^\$][^L].*?)>:";
348	    $type = ".dword";
349    }
350} elsif ($arch eq "microblaze") {
351    # Microblaze calls '_mcount' instead of plain 'mcount'.
352    $mcount_regex = "^\\s*([0-9a-fA-F]+):.*\\s_mcount\$";
353} elsif ($arch eq "riscv") {
354    $function_regex = "^([0-9a-fA-F]+)\\s+<([^.0-9][0-9a-zA-Z_\\.]+)>:";
355    $mcount_regex = "^\\s*([0-9a-fA-F]+):\\sR_RISCV_CALL(_PLT)?\\s_mcount\$";
356    $type = ".quad";
357    $alignment = 2;
358} elsif ($arch eq "csky") {
359    $mcount_regex = "^\\s*([0-9a-fA-F]+):\\s*R_CKCORE_PCREL_JSR_IMM26BY2\\s+_mcount\$";
360    $alignment = 2;
361} else {
362    die "Arch $arch is not supported with CONFIG_FTRACE_MCOUNT_RECORD";
363}
364
365my $text_found = 0;
366my $read_function = 0;
367my $opened = 0;
368my $mcount_section = "__mcount_loc";
369
370my $dirname;
371my $filename;
372my $prefix;
373my $ext;
374
375if ($inputfile =~ m,^(.*)/([^/]*)$,) {
376    $dirname = $1;
377    $filename = $2;
378} else {
379    $dirname = ".";
380    $filename = $inputfile;
381}
382
383if ($filename =~ m,^(.*)(\.\S),) {
384    $prefix = $1;
385    $ext = $2;
386} else {
387    $prefix = $filename;
388    $ext = "";
389}
390
391my $mcount_s = $dirname . "/.tmp_mc_" . $prefix . ".s";
392my $mcount_o = $dirname . "/.tmp_mc_" . $prefix . ".o";
393
394#
395# Step 1: find all the local (static functions) and weak symbols.
396#         't' is local, 'w/W' is weak
397#
398open (IN, "$nm $inputfile|") || die "error running $nm";
399while (<IN>) {
400    if (/$local_regex/) {
401	$locals{$1} = 1;
402    } elsif (/$weak_regex/) {
403	$weak{$2} = $1;
404    }
405}
406close(IN);
407
408my @offsets;		# Array of offsets of mcount callers
409my $ref_func;		# reference function to use for offsets
410my $offset = 0;		# offset of ref_func to section beginning
411
412##
413# update_funcs - print out the current mcount callers
414#
415#  Go through the list of offsets to callers and write them to
416#  the output file in a format that can be read by an assembler.
417#
418sub update_funcs
419{
420    return unless ($ref_func and @offsets);
421
422    # Sanity check on weak function. A weak function may be overwritten by
423    # another function of the same name, making all these offsets incorrect.
424    if (defined $weak{$ref_func}) {
425	die "$inputfile: ERROR: referencing weak function" .
426	    " $ref_func for mcount\n";
427    }
428
429    # is this function static? If so, note this fact.
430    if (defined $locals{$ref_func}) {
431	$convert{$ref_func} = 1;
432    }
433
434    # Loop through all the mcount caller offsets and print a reference
435    # to the caller based from the ref_func.
436    if (!$opened) {
437	open(FILE, ">$mcount_s") || die "can't create $mcount_s\n";
438	$opened = 1;
439	print FILE "\t.section $mcount_section,\"a\",$section_type\n";
440	print FILE "\t.align $alignment\n" if (defined($alignment));
441    }
442    foreach my $cur_offset (@offsets) {
443	printf FILE "\t%s %s + %d\n", $type, $ref_func, $cur_offset - $offset;
444    }
445}
446
447#
448# Step 2: find the sections and mcount call sites
449#
450open(IN, "LC_ALL=C $objdump -hdr $inputfile|") || die "error running $objdump";
451
452my $text;
453
454
455# read headers first
456my $read_headers = 1;
457
458while (<IN>) {
459
460    if ($read_headers && /$mcount_section/) {
461	#
462	# Somehow the make process can execute this script on an
463	# object twice. If it does, we would duplicate the mcount
464	# section and it will cause the function tracer self test
465	# to fail. Check if the mcount section exists, and if it does,
466	# warn and exit.
467	#
468	print STDERR "ERROR: $mcount_section already in $inputfile\n" .
469	    "\tThis may be an indication that your build is corrupted.\n" .
470	    "\tDelete $inputfile and try again. If the same object file\n" .
471	    "\tstill causes an issue, then disable CONFIG_DYNAMIC_FTRACE.\n";
472	exit(-1);
473    }
474
475    # is it a section?
476    if (/$section_regex/) {
477	$read_headers = 0;
478
479	# Only record text sections that we know are safe
480	$read_function = defined($text_sections{$1});
481	if (!$read_function) {
482	    foreach my $prefix (keys %text_section_prefixes) {
483		if (substr($1, 0, length $prefix) eq $prefix) {
484		    $read_function = 1;
485		    last;
486		}
487	    }
488	}
489	# print out any recorded offsets
490	update_funcs();
491
492	# reset all markers and arrays
493	$text_found = 0;
494	undef($ref_func);
495	undef(@offsets);
496
497    # section found, now is this a start of a function?
498    } elsif ($read_function && /$function_regex/) {
499	$text_found = 1;
500	$text = $2;
501
502	# if this is either a local function or a weak function
503	# keep looking for functions that are global that
504	# we can use safely.
505	if (!defined($locals{$text}) && !defined($weak{$text})) {
506	    $ref_func = $text;
507	    $read_function = 0;
508	    $offset = hex $1;
509	} else {
510	    # if we already have a function, and this is weak, skip it
511	    if (!defined($ref_func) && !defined($weak{$text}) &&
512		 # PPC64 can have symbols that start with .L and
513		 # gcc considers these special. Don't use them!
514		 $text !~ /^\.L/) {
515		$ref_func = $text;
516		$offset = hex $1;
517	    }
518	}
519    }
520    # is this a call site to mcount? If so, record it to print later
521    if ($text_found && /$mcount_regex/) {
522	push(@offsets, (hex $1) + $mcount_adjust);
523    }
524}
525
526# dump out anymore offsets that may have been found
527update_funcs();
528
529# If we did not find any mcount callers, we are done (do nothing).
530if (!$opened) {
531    exit(0);
532}
533
534close(FILE);
535
536#
537# Step 3: Compile the file that holds the list of call sites to mcount.
538#
539`$cc -o $mcount_o -c $mcount_s`;
540
541my @converts = keys %convert;
542
543#
544# Step 4: Do we have sections that started with local functions?
545#
546if ($#converts >= 0) {
547    my $globallist = "";
548    my $locallist = "";
549
550    foreach my $con (@converts) {
551	$globallist .= " --globalize-symbol $con";
552	$locallist .= " --localize-symbol $con";
553    }
554
555    my $globalobj = $dirname . "/.tmp_gl_" . $filename;
556    my $globalmix = $dirname . "/.tmp_mx_" . $filename;
557
558    #
559    # Step 5: set up each local function as a global
560    #
561    `$objcopy $globallist $inputfile $globalobj`;
562
563    #
564    # Step 6: Link the global version to our list.
565    #
566    `$ld -r $globalobj $mcount_o -o $globalmix`;
567
568    #
569    # Step 7: Convert the local functions back into local symbols
570    #
571    `$objcopy $locallist $globalmix $inputfile`;
572
573    # Remove the temp files
574    `$rm $globalobj $globalmix`;
575
576} else {
577
578    my $mix = $dirname . "/.tmp_mx_" . $filename;
579
580    #
581    # Step 8: Link the object with our list of call sites object.
582    #
583    `$ld -r $inputfile $mcount_o -o $mix`;
584
585    #
586    # Step 9: Move the result back to the original object.
587    #
588    `$mv $mix $inputfile`;
589}
590
591# Clean up the temp files
592`$rm $mcount_o $mcount_s`;
593
594exit(0);
595
596# vim: softtabstop=4
597