aboutsummaryrefslogtreecommitdiff
blob: 402c66e4c7a2bf63bba9545bbb84c1733c9dd442 (plain)
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
# Copyright 1999-2013 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: /var/cvsroot/gentoo-x86/eclass/multilib-build.eclass,v 1.23 2013/10/01 18:06:06 mgorny Exp $

# @ECLASS: multilib-build.eclass
# @MAINTAINER:
# Michał Górny <mgorny@gentoo.org>
# @BLURB: flags and utility functions for building multilib packages
# @DESCRIPTION:
# The multilib-build.eclass exports USE flags and utility functions
# necessary to build packages for multilib in a clean and uniform
# manner.
#
# Please note that dependency specifications for multilib-capable
# dependencies shall use the USE dependency string in ${MULTILIB_USEDEP}
# to properly request multilib enabled.

if [[ ! ${_MULTILIB_BUILD} ]]; then

# EAPI=4 is required for meaningful MULTILIB_USEDEP.
case ${EAPI:-0} in
	4|5) ;;
	*) die "EAPI=${EAPI} is not supported" ;;
esac

inherit multibuild multilib

# @ECLASS-VARIABLE: _MULTILIB_FLAGS
# @INTERNAL
# @DESCRIPTION:
# The list of multilib flags and corresponding ABI values. If the same
# flag is reused for multiple ABIs (e.g. x86 on Linux&FreeBSD), multiple
# ABIs may be separated by commas.
_MULTILIB_FLAGS=(
	abi_x86_32:x86,x86_fbsd
	abi_x86_64:amd64,amd64_fbsd
	abi_x86_x32:x32
	abi_mips_n32:n32
	abi_mips_n64:n64
	abi_mips_o32:o32
)

# @ECLASS-VARIABLE: _MULTILIB_ABI_WHITELIST
# @INTERNAL
# @DESCRIPTION:
# Sanity checking variable enumerating known ABI values.  A way to discover
# situations where this eclass and PORTDIR have fallen out-of-sync.  To update/check, use:
# find /usr/portage/profiles -type f | xargs grep '^\(DEFAULT_\)ABI\{0,1\}='
#
# Note that despite the name, these are not required to be multilib ABI's -- the complete list of ABI's
# supported by the gentoo repository is supposed to go here.
#
# TODO: add prefix ABI's here!
_MULTILIB_ABI_WHITELIST=( x86 amd64 x32 n32 n64 o32 s390 s390x sparc32 sparc64 ppc ppc64 amd64_fbsd x86_fbsd )

# @FUNCTION: get_multilib_build_abis
# @USAGE: [--dependmode]
# @DESCRIPTION:
# Returns a list of abis with multiple-abi multilib-build support
# This is a global list of all ABI values which have corresponding
# flags in the global hard-coded database of multibuild-compatible ABI's
# (_MULTILIB_FLAGS).  As of this writing, it returns at least these:
#
#   "x86 x86_fbsd amd64 amd64_fbsd x32 n32 n64 o32"
#
# Results go to standard output.  If the current DEFAULT_ABI is
# not present in the list, it will be appended; otherwise,
# it will be placed at the end of the list -- therefore,
# the standard result is not a suitable basis for the generation of
# package-manager-cached metadata.
#
# However, if the --dependmode argument is supplied, then this
# API will act as though the default ABI was "default" and therefore
# act in a completely deterministic manner suitable for this purpose.
get_multilib_build_abis() {
	[[ $# -gt 1 ]] && die "${FUNCNAME} takes at most one argument"
	local rslt=${_MULTILIB_FLAGS[*]##*:}
	rslt=" ${rslt//,/ } "
	if [[ ${1} == --dependmode ]] ; then
		rslt=$(echo ${rslt} default)
	else
		rslt=$(echo ${rslt/ ${DEFAULT_ABI:-default} / } ${DEFAULT_ABI:-default})
	fi
	echo ${rslt}
}

# @FUNCTION: multilib_abi_flag
# @USAGE: <abi>
# @DESCRIPTION:
# Return the use-flag corresponding to the specified multilib
# ABI on stdout.  If no corresponding flag is found, returns
# nothing.
multilib_abi_flag() {
	debug-print-function ${FUNCNAME} "${@}"

	local abi="$1" i found m_abis m_abi m_flag
	for i in "${_MULTILIB_FLAGS[@]}"; do
		m_abis=${i#*:}
		m_flag=${i%:*}

		# split on ,; we can't switch IFS for function scope because
		# paludis is broken (bug #486592), and switching it locally
		# for the split is more complex than cheating like this
		for m_abi in ${m_abis//,/ }; do
			if [[ ${m_abi} == ${abi} ]] ; then
				echo "${m_flag}"
				return 0
			fi
		done
	done

	debug-print "${FUNCNAME}: No multilib abi \"${abi}\" found, returning nothing"
	return 1
}

# @FUNCTION: multilib_flag_abi
# @USAGE: <flag>
# @DESCRIPTION:
# Returns, when applicable, any active multilib ABI corresponding
# to the provided abi_<arch> USE_EXPAND USE-flag, by way of
# output to standard output.
#
# Due to the recycling of use-flags in the multilib-build
# framework between ABIs, this API cannot return purely
# functional package-manager-independant information
# suitable for cacheable ebuild settings, such as those
# in generated USE dependencies.
#
# However, for many other purposes it is quite practical to
# want to map back freely from flag to ABI values.  This tries.
#
# If no such mapping is to be found, this does not fall back to
# the default ABI.  It instead will silently return a nonzero
# failure code.
multilib_flag_abi() {
	debug-print-function ${FUNCNAME} "${@}"

	local i req_flag=${1} test_flag test_abis test_abi enabled_abi
	for i in "${_MULTILIB_FLAGS[@]}"; do
		test_flag=${i%:*}
		[[ ${test_flag} == ${req_flag} ]] || continue
		test_abis=${i#*:}
		for test_abi in ${test_abis//,/ }; do
			for enabled_abi in $(get_all_abis); do
				if [[ ${enabled_abi} == ${test_abi} ]] ; then
					# a match! return it.
					echo "${test_abi}"
					return 0
				fi
			done
		done
	done
	return 1
}

# @ECLASS-VARIABLE: _MULTILIB_BUILD_CACHED_ENABLED_ABIS
# @INTERNAL
# @DEFAULT-UNSET
# @DESCRIPTION:
# Set to the result of multilib_get_enabled_abis after
# that function is invoked the first time.

# @FUNCTION: multilib_get_enabled_abis
# @DESCRIPTION:
# Return the ordered list of enabled ABIs if multilib builds
# are enabled. The best (most preferred) ABI will come last.
#
# If multilib is disabled, the default ABI will be returned
# in order to enforce consistent testing with multilib code.
multilib_get_enabled_abis() {
	debug-print-function ${FUNCNAME} "${@}"

	if [[ ${_MULTILIB_BUILD_CACHED_ENABLED_ABIS} ]]; then
		echo "${_MULTILIB_BUILD_CACHED_ENABLED_ABIS}"
		debug-print "${FUNCNAME} result (cached): \"${_MULTILIB_BUILD_CACHED_ENABLED_ABIS}\""
		return 0
	fi

	local abis=( $(get_all_abis) )

	local abi i found
	for abi in "${abis[@]}"; do
		for i in "${_MULTILIB_FLAGS[@]}"; do
			local m_abis=${i#*:} m_abi
			local m_flag=${i%:*}

			# split on ,; we can't switch IFS for function scope because
			# paludis is broken (bug #486592), and switching it locally
			# for the split is more complex than cheating like this
			for m_abi in ${m_abis//,/ }; do
				if [[ ${m_abi} == ${abi} ]] && use "${m_flag}"; then
					_MULTILIB_BUILD_CACHED_ENABLED_ABIS+="${_MULTILIB_BUILD_CACHED_ENABLED_ABIS:+ }${abi}"
					found=1
					break 2
				fi
			done
		done
	done

	if [[ ! ${found} ]]; then
		# ${ABI} can be used to override the fallback (multilib-portage),
		# ${DEFAULT_ABI} is the safe fallback.
		abi=${ABI:-${DEFAULT_ABI:-default}}

		debug-print "${FUNCNAME}: no ABIs enabled, fallback to ${abi}"
		debug-print "${FUNCNAME}: ABI=${ABI}, DEFAULT_ABI=${DEFAULT_ABI}"
		_MULTILIB_BUILD_CACHED_ENABLED_ABIS=${abi}
	fi
	echo "${_MULTILIB_BUILD_CACHED_ENABLED_ABIS}"
	debug-print "${FUNCNAME}: result (calculated): \"${_MULTILIB_BUILD_CACHED_ENABLED_ABIS}\""
}

# @ECLASS-VARIABLE: MULTILIB_USEDEP
# @DESCRIPTION:
# The USE-dependency to be used on dependencies (libraries) needing
# to support multilib as well.
#
# Example use:
# @CODE
# RDEPEND="dev-libs/libfoo[${MULTILIB_USEDEP}]
#	net-libs/libbar[ssl,${MULTILIB_USEDEP}]"
# @CODE

_multilib_build_set_globals() {
	local flags=( "${_MULTILIB_FLAGS[@]%:*}" )
	local usedeps=${flags[@]/%/(-)?}

	IUSE=${flags[*]}
	MULTILIB_USEDEP=${usedeps// /,}

	# since it tends always to be run in a subshell,
	# multilib_get_enabled_abis may fail to generate
	# the cache; run it once, here, in ${PID}. But, if
	# we are in the depend phase, folks really
	# ought not to be using it, anyhow, and it will
	# waste time.  So don't do it, in that case.
	[[ ${EBUILD_PHASE} != depend ]] && multilib_get_enabled_abis > /dev/null
}
_multilib_build_set_globals

# @FUNCTION: _multilib_multibuild_wrapper
# @USAGE: <argv>...
# @INTERNAL
# @DESCRIPTION:
# Initialize the environment for ABI selected for multibuild.
_multilib_multibuild_wrapper() {
	debug-print-function ${FUNCNAME} "${@}"

	local ABI=${MULTIBUILD_VARIANT}
	local MULTILIB_BUILD_ABI="${ABI}"
	export MULTILIB_BUILD_ABI
	multilib_toolchain_setup "${ABI}"
	"${@}"
}

# @FUNCTION: multilib-build_run_in_build_dir
# @DESCRIPTION:
# Run a command in the build dir using _multilib_multibuild_wrapper
multilib-build_run_in_build_dir() {
	debug-print-function "${FUNCNAME}" "$@"

	run_in_build_dir _multilib_multibuild_wrapper "$@"
}

# @FUNCTION: multilib_tc_export
# @DESCRIPTION:
# Code running in the context of _multilib_multibuild_wrapper cannot use tc_export
# from toolchain-funcs.eclass (at least, not without some care), as this will
# munge the settings from multilib_toolchain_setup.  This might be fixable; however,
# until some solution is arrived at to automagically do the right thing there,
# routing that code through this wrapper function should provide a reliable-ish
# solution to the problem.  The basic recipe is to replace:
# @CODE
# some_function() {
#     tc_export X Y Z
#     foo
#     bar
# }
# @CODE
# with
# @CODE
# some_function() {
#     MULTILIB_TC_EXPORT_VARS="X Y Z" multilib_tc_export _stuff_to_do
# }
#
# _stuff_to_do() {
#     foo
#     bar
# }
#
# By design, the exported variables will NOT persist in any way, so if you are
# adapting code that expects those exports to persist across phase function
# boundaries, you will have to re-wrap the exports.  This sucks but the only
# alternative is a lot of confusion.  Note that this code will also not work
# properly unless you are executing in a context where multilib_toolchain_setup
# has already run.  The principal advantage of this is that cleanup will happen
# automatically once your wrapped function completes.
multilib_tc_export() {
	for var in ${MULTILIB_TC_EXPORT_VARS} ; do
		case ${var} in
			CHOST|CBUILD|AS|CC|CXX|LD|PKG_CONFIG_LIBDIR|PKG_CONFIG_PATH)
				# if already managed by multilib_toolchain_setup, keep it.  However, to
				# ensure that callers can uniformly expect the variable to be scope-localized,
				# localize it.
				if multilib_is_native_abi ; then
					eval "local ${var}=\"$(tc-get${var})\""
				else
					eval "local ${var}=\"${!var}\""
				fi
				eval "export ${var}"
				;;
			*)
				# non multilib_toolchain_setup variables are just localized
				eval "local ${var}"
				tc-export $var
				;;
		esac
	done
	"$@"
}

# @FUNCTION: multilib_foreach_abi
# @USAGE: <argv>...
# @DESCRIPTION:
# If multilib support is enabled, sets the toolchain up for each
# supported ABI along with the ABI variable and correct BUILD_DIR,
# and runs the given commands with them.
#
# If multilib support is disabled, it just runs the commands. No setup
# is done.
multilib_foreach_abi() {
	debug-print-function ${FUNCNAME} "${@}"

	local MULTIBUILD_VARIANTS=( $(multilib_get_enabled_abis) )
	multibuild_foreach_variant _multilib_multibuild_wrapper "${@}"
}

# @FUNCTION: multilib_parallel_foreach_abi
# @USAGE: <argv>...
# @DESCRIPTION:
# If multilib support is enabled, sets the toolchain up for each
# supported ABI along with the ABI variable and correct BUILD_DIR,
# and runs the given commands with them. The commands are run
# in parallel with number of jobs being determined from MAKEOPTS.
#
# If multilib support is disabled, it just runs the commands. No setup
# is done.
#
# Useful for running configure scripts.
multilib_parallel_foreach_abi() {
	debug-print-function ${FUNCNAME} "${@}"

	local MULTIBUILD_VARIANTS=( $(multilib_get_enabled_abis) )
	multibuild_parallel_foreach_variant _multilib_multibuild_wrapper "${@}"
}

# @FUNCTION: multilib_for_best_abi
# @USAGE: <argv>...
# @DESCRIPTION:
# Runs the given command with setup for the 'best' (usually native) ABI.
multilib_for_best_abi() {
	debug-print-function ${FUNCNAME} "${@}"

	local MULTIBUILD_VARIANTS=( $(multilib_get_enabled_abis) )

	multibuild_for_best_variant _multilib_multibuild_wrapper "${@}"
}

# @ECLASS-VARIABLE: MULTILIB_UNCHECKED_HEADERS
# @DESCRIPTION:
# A list of header files to ignore when checking for header conflicts.
# If an ebuild or eclass author has implemented their own solution
# to a possible header conflict, (if appropriate, that solution may
# simply be to ignore it, which would typically result in the
# best-ABI's header being installed (see: multilib_for_best_abi)
#
# This variable has to be a bash array. Paths shall be relative to
# installation root (${ED}), and name regular files.
#
# Note that if a header appears in MULTILIB_WRAPPED_HEADERS, adding
# it to this array, as well, will not prevent the header from being
# wrapped.
#
# Example:
# @CODE
# MULTILIB_UNCHECKED_HEADERS=(
#	/usr/include/foobar/config.h
# )
# @CODE

# @FUNCTION: multilib_check_headers
# @DESCRIPTION:
# Check whether the header files are consistent between ABIs.
#
# This function needs to be called after each ABI's installation phase.
# It obtains the header file checksums and compares them with previous
# runs (if any). Dies if header files differ.
multilib_check_headers() {
	_multilib_check_header_filter()
	{
	    local exgrep="" hdr
	    for hdr in "${MULTILIB_UNCHECKED_HEADERS[@]}" ; do
	        exgrep="${exgrep}${exgrep:+|}\s${ED}${hdr#/}\$"
	    done
	    if [[ ${exgrep} ]]; then
	        egrep -v "${exgrep}"
	    else
	        tee /dev/null
	    fi
		return 0
	}
	_multilib_header_cksum() {
		[[ -d ${ED}usr/include ]] && \
			find "${ED}"usr/include -type f -exec cksum {} + | \
				_multilib_check_header_filter | \
					sort -k2
	}

	local cksum=$(_multilib_header_cksum)
	local cksum_file=${T}/.multilib_header_cksum

	if [[ -f ${cksum_file} ]]; then
		local cksum_prev=$(< "${cksum_file}")

		if [[ ${cksum} != ${cksum_prev} ]]; then
			echo "${cksum}" > "${cksum_file}.new"

			eerror "Header files have changed between ABIs."

			if type -p diff &>/dev/null; then
				eerror "$(diff -du "${cksum_file}" "${cksum_file}.new")"
			else
				eerror "Old checksums in: ${cksum_file}"
				eerror "New checksums in: ${cksum_file}.new"
			fi

			die "Header checksum mismatch, aborting."
		fi
	else
		echo "${cksum}" > "${cksum_file}"
	fi
}

# @FUNCTION: multilib_copy_sources
# @DESCRIPTION:
# Create a single copy of the package sources for each enabled ABI.
#
# The sources are always copied from initial BUILD_DIR (or S if unset)
# to ABI-specific build directory matching BUILD_DIR used by
# multilib_foreach_abi().
multilib_copy_sources() {
	debug-print-function ${FUNCNAME} "${@}"

	local MULTIBUILD_VARIANTS=( $(multilib_get_enabled_abis) )
	multibuild_copy_sources
}

# @ECLASS-VARIABLE: MULTILIB_WRAPPED_HEADERS
# @DESCRIPTION:
# A list of headers to wrap for multilib support. The listed headers
# will be moved to a non-standard location and replaced with a file
# including them conditionally to current ABI.
#
# This variable has to be a bash array. Paths shall be relative to
# installation root (${ED}), and name regular files. Recursive wrapping
# is not supported.
#
# Please note that header wrapping is *discouraged*. It is preferred to
# install all headers in a subdirectory of libdir and use pkg-config to
# locate the headers. Some C preprocessors will not work with wrapped
# headers.
#
# If a header is preceeded by a carat-symbol ('^'), then the header-
# wrapper will not be generated.  Instead, the headers are moved
# to their normal non-standard location -- specifically,
# from /usr/include/${whatever}, a header
# will be moved to /usr/include/${CHOST}/${whatever} -- and no
# wrapper is generated.
#
# This may be preferable if the header in question is likely to
# cause confusion in overzealous configure scripts and you prefer to
# force explicit acquisition of the correct header file by
# consumers.
#
# Example:
# @CODE
# MULTILIB_WRAPPED_HEADERS=(
#	/usr/include/foobar/config.h
#	^/usr/include/poof-noconfig.h
# )
# @CODE

# @ECLASS-VARIABLE: MULTILIB_WRAPPED_EXECUTABLES
# @DESCRIPTION:
# A list of executables to wrap for automatic multilib support.  Any
# executable in the list may be prefixed with an at-sign ('@'), which
# will cause the executable itself to be replaced with a generated
# wrapper executable; otherwise, the executable itself will not
# be modified (only copied) by multilib-build, which, under most
# circumstances, will result in the best ABI version being used.
#
# So, if we were to add '/usr/bin/foo' to MULTILIB_WRAPPED_EXECUTABLES,
# the expected result might be as follows:
#
#   /usr/bin/foo      : best ABI executable.
#   /usr/bin/foo-bar  : executable for the 'bar' ABI
#   /usr/bin/foo-baz  : executable for the 'baz' ABI
#
# If we were using the 'fake' multilib arch, with abi_fake_bar and abi_fake_baz
# use flags activated.  This means that if 'baz' was the best ABI, then
# /usr/bin/foo and /usr/bin/baz would be identical (perhaps hard-linked) files.
#
# The generated wrapper executables, if requested, will perform a best-effort
# search for the wrapped per-abi executable correspondinging to the current
# multilib-build ABI (if any), and invoke it, if it can be found.  Otherwise,
# it will invoke the wrapped best-abi executable.
#
# In certain plausible cases, this may not be possible; it may therefore
# be the case that '@'-wrapping a multilib executable creates more problems
# than it solves.  The wrapper works by checking for a MULTILIB_BUILD_ABI
# environment variable.
#
# The MULTILIB_WRAPPED_EXECUTABLES variable has to be a bash array. Paths
# shall be relative to the installation root (${ED}), and name regular
# executable files.  It is an error to wrap an suid executable.
#
# If at all possible, it is preferred to simply drop non-best-ABI
# executables from your installation (this will happen automatically
# in most cases, simply by omitting the executable from
# MULTILIB_WRAPPED_EXECUTABLES).
#
# If that won't do, then it is preferred to wrap without the '@' prefix
# or to place them in separate directories (a better solution than
# MULTILIB_WRAPPED_EXECUTABLES if there are a lot of them).
#
# About the only good reason to rely on '@'-wrapping is if third-party
# frameworks tend to hard-code the path to the executable in question into
# configure scripts and then to rely on the executable itself to perform
# configure-time dependency generation.
#
# Even in those rare cirucumstances, you might still investigate
# whether some prior art exists in Gentoo, or your framework, to skip
# or override that process, for example, in order to facilitate
# cross-compiles.
#
# Example:
# @CODE
# MULTILIB_WRAPPED_EXECUTABLES=(
#   /usr/bin/script-engine-config
#	@/usr/bin/script-engine
# )
# @CODE

# @FUNCTION: multilib_prepare_wrappers
# @USAGE: [<install-root>]
# @DESCRIPTION:
# Perform the preparation of all kinds of wrappers for the current ABI.
# This function shall be called once per each ABI, after installing
# the files to be wrapped.
#
# Takes an optional custom <install-root> from which files will be
# used. If no root is specified, uses ${ED}.
#
# The files to be wrapped are specified using separate variables,
# e.g. MULTILIB_WRAPPED_HEADERS. Those variables shall not be changed
# between the successive calls to multilib_prepare_wrappers
# and multilib_install_wrappers.
#
# After all wrappers are prepared, multilib_install_wrappers shall
# be called to commit them to the installation tree.
multilib_prepare_wrappers() {
	debug-print-function ${FUNCNAME} "${@}"

	[[ ${#} -le 1 ]] || die "${FUNCNAME}: too many arguments"

	local root=${1:-${ED}}
	# ensure root has a single trailing slash
	[[ ${root} =~ /+$ ]] && root="${root%${BASH_REMATCH[0]}}"
	root="${root}/"
	local f

	local generate_wrapper
	for f in "${MULTILIB_WRAPPED_HEADERS[@]}"; do
		local generate_wrapper=yes
		[[ ${f:0:1} == ^ ]] && generate_wrapper=no
		f="${f#^}"
		# drop leading slash if it's there
		[[ ${f} =~ ^/+ ]] && f="${f#${BASH_REMATCH[0]}}"

		if [[ ${f} != usr/include/* ]]; then
			die "Wrapping headers outside of /usr/include is not supported at the moment."
		fi
		# and then usr/include
		f="${f#usr/include}"

		local dir="${f%/*}"

		if [[ ${generate_wrapper} == yes && ! -f "${ED}tmp/multilib-include${f}" ]]; then
			einfo "generating multilib wrapper for header ${f}"
			dodir "/tmp/multilib-include${dir}"
			# a generic template
			cat > "${ED}tmp/multilib-include${f}" <<_EOF_
/* This file is auto-generated by multilib-build.eclass
 * as a multilib-friendly wrapper. For the original content,
 * please see the files that are #included below.
 */

#if defined(__x86_64__) /* amd64 */
#	if defined(__ILP32__) /* x32 ABI */
#		error "abi_x86_x32 not supported by the package."
#	else /* 64-bit ABI */
#		error "abi_x86_64 not supported by the package."
#	endif
#elif defined(__i386__) /* plain x86 */
#	error "abi_x86_32 not supported by the package."
#elif defined(__mips__)
#   if(_MIPS_SIM == _ABIN32) /* n32 */
#       error "abi_mips_n32 not supported by the package."
#   elif(_MIPS_SIM == _ABI64) /* n64 */
#       error "abi_mips_n64 not supported by the package."
#   elif(_MIPS_SIM == _ABIO32) /* o32 */
#       error "abi_mips_o32 not supported by the package."
#   endif
#else
#	error "No ABI matched, please report a bug to bugs.gentoo.org"
#endif
_EOF_
		fi

		# Some ABIs may have install less files than others.
		if [[ -f "${root}usr/include${f}" ]]; then
			# $CHOST shall be set by multilib_toolchain_setup
			dodir "/tmp/multilib-include/${CHOST}${dir}"
			mv "${root}usr/include${f}" "${ED}tmp/multilib-include/${CHOST}${dir}/" || die
			if [[ ${generate_wrapper} == yes ]] ; then
				# XXX: get abi_* directly
				local abi_flag
				case "${ABI}" in
					amd64|amd64_fbsd)
						abi_flag=abi_x86_64;;
					x86|x86_fbsd)
						abi_flag=abi_x86_32;;
					x32)
						abi_flag=abi_x86_x32;;
					n32)
						abi_flag=abi_mips_n32;;
					n64)
						abi_flag=abi_mips_n64;;
					o32)
						abi_flag=abi_mips_o32;;
					*)
						die "Header wrapping for ${ABI} not supported yet";;
				esac

				# Note: match a space afterwards to avoid collision potential.
				sed -e "/${abi_flag} /s&error.*&include <${CHOST}${f}>&" \
					-i "${ED}tmp/multilib-include${f}" || die
			fi
		fi
	done

	for f in "${MULTILIB_WRAPPED_EXECUTABLES[@]}" ; do
		generate_wrapper=no
		[[ ${f:0:1} == @ ]] && generate_wrapper=yes
		f="${f#@}"

		# strip leading slashes
		f="${f#/}"
		[[ ${f} =~ ^/+ ]] && f="${f#${BASH_REMATCH[0]}}"

		debug-print "${FUNCNAME}: wrapped executable check: ${root}${f}"
		[[ -e ${root}${f} ]] || continue

		# sanity checks
		[[ -f ${root}${f} ]] || die "Only regular files may be wrapped: \"${root}${f}\" is something else"
		[[ -x ${root}${f} ]] || die "Wrapped executables must be executable: \"${root}${f}\" isnt"
		[[ -u ${root}${f} ]] && die "Suid executables may not be wrapped: \"${root}${f}\""
		[[ -g ${root}${f} ]] && die "Sgid executables may not be wrapped: \"${root}${f}\""

		debug-print "${FUNCNAME}: wrapped executable \"${root}${f}\" found, wrapping."

		local dir="${f%/*}"
		# strip trailing slashes
		[[ ${dir} =~ /+$ ]] && dir="${dir%${BASH_REMATCH[0]}}"

		[[ ${generate_wrapper} == yes && ! -d "${ED}tmp/multilib-bin-wrappers/${dir}" ]] && \
			dodir "/tmp/multilib-bin-wrappers/${dir}"

		if [[ -f "${root}${f}-${ABI}" ]] ; then
			# In order to support quick-and-dirty re-installation using ebuild install,
			# we need to either (a) permit these files to be overwritten or
			# (b) not wrap them.  Here I've chosen (a), but we dump this warning
			# in case this represents a real name collision.
			ewarn
			ewarn "Name collision wrapping multilib executable \"${f}\"."
			ewarn "Destination \"${root}${f}-${ABI}\" will be over-written."
			ewarn
			rm -f "${root}${f}-${ABI}" || die
		fi

		if [[ ${generate_wrapper} == yes ]] ; then
			cp -T "${root}${f}" "${root}${f}-${ABI}" || die
			# make wrapper like original
			chown -c --reference="${root}${f}" "${root}${f}-${ABI}" || die "Cant chown \"${root}${f}-${ABI}\""
			chmod -c --reference="${root}${f}" "${root}${f}-${ABI}" || die "Cant chmod \"${root}${f}-${ABI}\""
			if has xattr ${FEATURES} ; then
				# TODO
				:
			fi
			touch --reference="${root}${f}" "${root}${f}-${ABI}" || die "Cant touch \"${root}${f}-${ABI}\""
			rm -f "${root}${f}"
		else
			ln -T "${root}${f}" "${root}${f}-${ABI}" || die
			# make wrapper like original
			chown -c --reference="${root}${f}" "${root}${f}-${ABI}" || die "Cant chown \"${root}${f}-${ABI}\""
			chmod -c --reference="${root}${f}" "${root}${f}-${ABI}" || die "Cant chmod \"${root}${f}-${ABI}\""
			if has xattr ${FEATURES} ; then
				# TODO
				:
			fi
			touch --reference="${root}${f}" "${root}${f}-${ABI}" || die "Cant touch \"${root}${f}-${ABI}\""
		fi

		if [[ ${generate_wrapper} == yes && ! -f "${ED}tmp/multilib-bin-wrappers/${f}" ]]; then
			# we need to get the enabled abis in case somehow we are invoked by an inner layer of multi-ness
			local max_abi_len=0 a enabled_abis=( $(multilib_get_enabled_abis) )
			for a in "${enabled_abis[@]}" ; do
				(( max_abi_len < ${#a} )) && max_abi_len=${#a}
			done

			local pn_random_random="${PN}_${RANDOM}_${RANDOM}"
			local fwrap_dir="${WORKDIR}/multilib-bin-wrappers/${dir}"
			local f_c="${f##*/}.c"

			mkdir -p ${fwrap_dir} || die "Cannot create \"${fwrap_dir}\"."
			cat > "${fwrap_dir}/${f_c}" <<-_EOF_
			#include <stdio.h>
			#include <stdlib.h>
			#include <string.h>
			#include <unistd.h>

			#define DEBUG() ($( if has debug ${IUSE} && use debug; then echo 1; else echo 0; fi ))
			#define dprintf if (DEBUG()) fprintf

			static const char default_abi_prefix[] = "-$(multibuild_get_best_variant)";
			static const char f[] = "${EPREFIX}/${f}";

			int main(int argc, char *argv[]) {
			    char pidstr[20], *target = NULL, env_abi_prefix[$(( ++max_abi_len + 1 ))], *env_abi;
			    const char *scratch;

			    int valid_abi(const char *abi) {
			$( for abi in "${enabled_abis[@]}"; do
	echo   "        if (strcmp(abi, \"${abi}\") == 0) return 1;"
			done )
			        return 0;
			    }
			    int attempt_exec(const char *target_base, const char *abi_prefix) {
			        /* concatenate target_base and abi_prefix, and then attempt to execvp the result */
			        if (target) free(target);
			        /* the '+1' here is for the hyphen -- room for the '\0' is provided by the constant */
			        target = (char *) malloc(strlen(target_base) + ${max_abi_len} + 1);
			        if (!target) {
			            fprintf(stderr, "${PF}-multilib-wrapper: memory allocation failure.\n");
			            exit(2);
			        }
			        strcpy(target, target_base);
			        strncat(target, abi_prefix, ${max_abi_len});
			        dprintf(stderr, "${PF}-multilib-wrapper: Searching for possible target: \"%s\".\n", target);
			        execvp(target, argv);
			        dprintf(stderr, "${PF}-multilib-wrapper: Target binary matching \"%s\" not found.\n", target);
			    }

			    dprintf(stderr, "${PF}-multilib-wrapper called as: %s\n", argv[0]);

			    /* circuit-breaker to prevent any possible self-exec() bomb */
			    if (scratch = getenv("${pn_random_random}")) {
			        if ((int) getpid() == atoi(scratch)) {
			            fprintf(stderr, "${PF}-multilib-wrapper: odd, apparent exec bomb: crashing.\n");
			            exit(2);
			        }
			    }
			    snprintf(&pidstr[0], 20, "%d", (int) getpid());
			    setenv("${pn_random_random}", &pidstr[0], 1);

			    /* Determine if we've been invoked during multilib-build ABI iteration. */
			    env_abi_prefix[0] = '-';
			    env_abi_prefix[1] = '\0';
			    env_abi = &env_abi_prefix[1];
			    scratch = getenv("MULTILIB_BUILD_ABI");
			    if (scratch) {
			        if (strlen(scratch) >= ${max_abi_len}) {
			            fprintf(stderr, "${PF}-multilib-wrapper: unexpectedly long ABI environment variable\n");
			            fprintf(stderr, "${PF}-multilib-wrapper: value detected: \"%s.$(( max_abi_len * 20 ))\".\n", scratch);
			            exit(2);
			        }
			        /* if env abi is the same as default, the fallback code does everything required, no need to continue. */
			        if (strcmp(scratch, &default_abi_prefix[1]) != 0) {
			            strncpy(env_abi, scratch, ${max_abi_len});
						if (valid_abi(env_abi)) {
			                dprintf(stderr, "${PF}-multilib-wrapper: Detected valid non-best-ABI multilib-build invocation under auspices of ABI \"%s\".\n", &env_abi[0]);
			                attempt_exec(argv[0], &env_abi_prefix[0]);
			                attempt_exec(&f[0], &env_abi_prefix[0]);
			                fprintf(stderr, "${PF}-multilib-wrapper: During multilib-build invocation context with ABI \"%s\",\n", &env_abi[0]);
			                fprintf(stderr, "${PF}-multilib-wrapper: unable to find appropriate ABI-specific target.\n");
			                fprintf(stderr, "${PF}-multilib-wrapper: Falling-back to best-abi (\"%s\") invocation targets.\n", &default_abi_prefix[1]);
			            } else
			                fprintf(stderr, "${PF}-multilib-wrapper: unknown MULTILIB_BUILD_ABI value \"%s\" ignored.\n", &env_abi[0]);
			        }
			    }
			    attempt_exec(argv[0], &default_abi_prefix[0]);
			    attempt_exec(&f[0], &default_abi_prefix[0]);
			    fprintf(stderr, "${PF}-multilib-wrapper: Invoked as \"%s\", unable to find suitable executable to invoke.  Giving up.\n", argv[0]);
			    exit(2);
			}
			_EOF_

			do_executable_wrapper_compile() {
				einfo "Performing wrapper compilation in \"${fwrap_dir}\"."
				pushd "${fwrap_dir}" > /dev/null || die
				# we can just do normal tc-getCC here and it will almost always work;
				# however, technically, the best ABI doesn't have to be the same as
				# the native ABI -- therefore we follow the standard recipe:
				local cc=${CC:-$(tc-getCC)}
				ebegin "Compiling wrapper: ${cc} ${CFLAGS} ${f_c} -c -o ${f_c%.c}.o"
				"${cc}" ${CFLAGS} "${f_c}" -c -o "${f_c%.c}.o"  || \
					{ eend $? ; die "executable wrapper compilation failed for ${f_c} in \"${fwrap_dir}\"" ; }
				einfo "Linking wrapper: ${cc} ${LDFLAGS} ${f_c%.c}.o -o ${f_c%.c}"
				"${cc}" ${LDFLAGS} "${f_c%.c}.o" -o "${f_c%.c}" || \
					{ eend $? ; die "executable wrapper linking failed for ${f_c%.c}.o in \"${fwrap_dir}\"" ; }
				einfo "Deploying compiled wrapper to staging area in \"/tmp/multilib-bin-wrappers/${dir}\"."
				mkdir -p "${ED}tmp/multilib-bin-wrappers/${dir}" || die
				cp "${f_c%.c}" "${ED}tmp/multilib-bin-wrappers/${f}" || die
				eend $?
				popd > /dev/null || die
			}
			multilib_for_best_abi do_executable_wrapper_compile
			# make wrapper-executable like -ABI wrapped executable
			chown -c --reference="${root}${f}-${ABI}" "${ED}tmp/multilib-bin-wrappers/${f}" || \
				die "Cant chown \"${ED}tmp/multilib-bin-wrappers/${f}\""
			chmod -c --reference="${root}${f}-${ABI}" "${ED}tmp/multilib-bin-wrappers/${f}" || \
				die "Cant chmod \"${ED}tmp/multilib-bin-wrappers/${f}\""
			if has xattr ${FEATURES} ; then
				# TODO
				:
			fi
			touch --reference="${root}${f}-${ABI}" "${ED}tmp/multilib-bin-wrappers/${f}" || \
				die "Cant touch \"${ED}tmp/multilib-bin-wrappers/${f}\""
		fi
	done
}

# @FUNCTION: multilib_install_wrappers
# @USAGE: [<install-root>]
# @DESCRIPTION:
# Install the previously-prepared wrappers. This function shall
# be called once, after all wrappers were prepared.
#
# Takes an optional custom <install-root> to which the wrappers will be
# installed. If no root is specified, uses ${ED}. There is no need to
# use the same root as when preparing the wrappers.
#
# The files to be wrapped are specified using separate variables,
# e.g. MULTILIB_WRAPPED_HEADERS. Those variables shall not be changed
# between the calls to multilib_prepare_wrappers
# and multilib_install_wrappers.
multilib_install_wrappers() {
	debug-print-function ${FUNCNAME} "${@}"

	[[ ${#} -le 1 ]] || die "${FUNCNAME}: too many arguments"

	local root=${1:-${ED}}
	# ensure root has a single trailing slash
	[[ ${root} =~ /+$ ]] && root="${root%${BASH_REMATCH[0]}}"
	root="${root}/"

	if [[ -d "${ED}"tmp/multilib-include ]]; then
		einfo "Merging multilib include wrappers"
		multibuild_merge_root \
			"${ED}"tmp/multilib-include "${root}"usr/include
		rmdir "${ED}"tmp &>/dev/null # can fail if something else uses /tmp
	fi

	if [[ -d "${ED}"tmp/multilib-bin-wrappers ]] ; then
		einfo "Merging multilib executable wrappers"
		multibuild_merge_root \
			"${ED}"tmp/multilib-bin-wrappers "${root%/}"
		rmdir "${ED}"tmp &>/dev/null # can fail if something else uses /tmp
	fi
}

# @FUNCTION: multilib_is_native_abi
# @DESCRIPTION:
# Determine whether the currently built ABI is the profile native.
# Return true status (0) if that is true, otherwise false (1).
#
# This is often useful for configure calls when some of the options are
# supposed to be disabled for multilib ABIs (like those used for
# executables only).
multilib_is_native_abi() {
	debug-print-function ${FUNCNAME} "${@}"

	[[ ${#} -eq 0 ]] || die "${FUNCNAME}: too many arguments"

	[[ ${ABI} == ${DEFAULT_ABI} ]]
}

# @FUNCTION: multilib_is_best_abi
# @DESCRIPTION:
# Determine whether the current ABI is the "best" abi,
# in the sense that it is the ABI we would get if we ran
# multilib_for_best_abi.  Gives the same result as
# multilib_for_native_abi, unless the native ABI is disabled.
#
# Returns true status (0) if that is true, otherwise false (1).
#
# Useful for doing something, such as generating
# documentation, which only need happen once,
# during multilib_foreach_abi iteration.
multilib_is_best_abi() {
	debug-print-function ${FUNCNAME} "${@}"
	[[ ${MULTILIB_BUILD_ABI} ]] \
		|| die "${FUNCNAME}: MULTILIB_BUILD_ABI needs to be set"

	[[ ${MULTILIB_BUILD_ABI} == $(multilib_get_best_abi) ]]
}

# @FUNCTION: multilib_get_best_abi
# @DESCRIPTION:
# Return the best abi && return it via echo to stdout
multilib_get_best_abi() {
	declare -a abis=( $(multilib_get_enabled_abis) )
	echo "${abis[$(( ${#abis[@]} - 1))]}"
	return 0
}

# @FUNCTION: abi_arch_use
# @USAGE: <[!]pseudo-flag>
# @RETURN: True (zero) if the pseudo-use-flag test is positive, similar to use helper.
# @DESCRIPTION:
# Often pre-multilib-build ebuild and eclass code contain statements like:
# @CODE
# use foo && append-flags -funroll-loops
# @CODE
# where foo is an ARCH USE_EXPAND value such as "amd64".
# When adapting such code to a multi-abi build environment based on
# multilib-build.eclass, it is convenient to be able to quickly convert
# such queries to instead check the currently activated ABI.  However,
# there is a non-trivial mapping between ARCHes and ABIs.  This function acts
# syntactically like the "use" phase-helper; however, it only works on
# ARCH USE_EXPAND values (those in ${PORTDIR}/profiles/arch.list).
#
# It operates only on whitelisted values of ${ABI}, so, if ${ABI} is unknown,
# or if ${ARCH} is known to have multilib support, but ${ABI} is not a
# known abi for ${ARCH} (according to the hard-coded whitelist) then a
# nonzero (false) value (or a zero (true) value, when
# the pseudo-flag argument is preceeded by an exclamation point) would
# be immediately returned, regardless of any underlying "truth" pertaining
# to the multilib_build framework.
#
# TODO: handle prefix ABI's
abi_arch_use() {
	debug-print-function ${FUNCNAME} "$@"

	local u=$1
	local match=0
	local notnot=1
	local eff_abi=__WTF__
	local eff_arch=__FTW__

	# if we got something like '!flag', then invert the return value
	if [[ ${u:0:1} == "!" ]] ; then
		u=${u:1}
		notnot=0
	fi

	# get eff_abi
	if [[ ${ABI:-default} == default ]] ; then
		has "${DEFAULT_ABI}" "${_MULTILIB_ABI_WHITELIST[@]}" && eff_abi="${DEFAULT_ABI}"
	else
		has ${ABI} "${_MULTILIB_ABI_WHITELIST[@]}" && eff_abi=${ABI}
	fi

	# get eff_arch
	case ${ARCH} in
		x86|amd64)
			case ${eff_abi} in
				x32|amd64) eff_arch=amd64 ;;
				x86) eff_arch=x86 ;;
			esac
			;;
		x86-fbsd|amd64-fbsd)
			case ${eff_abi} in
				x86_fbsd) eff_arch=x86-fbsd ;;
				amd64_fbsd) eff_arch=amd64-fbsd ;;
			esac
			;;
		mips)
			case ${eff_abi} in
				n32|n64|o32) eff_arch=mips ;;
			esac
			;;
		sparc)
			case ${eff_abi} in
				sparc32|sparc64) eff_arch=sparc ;;
			esac
			;;
		s390)
			case ${eff_abi} in
				s390|s390x) eff_arch=s390 ;;
			esac
			;;
		ppc)
			case ${eff_abi} in
				ppc|ppc64) eff_arch=ppc ;;
			esac
			;;
		*)
			case ${eff_abi} in
				__WTF__) : ;;
				*) eff_arch="${ARCH}"
			esac
			;;
	esac

	[[ ${eff_abi} == __WTF__ ]] && \
		ewarn "abi_arch_use could not calculate effective ABI"
	[[ ${eff_arch} == __FTW__ ]] && \
		ewarn "abi_arch_use could not calculate effective ARCH"

	[[ ${eff_arch} == ${u} ]] && match=1

	# debug-print "abi_arch_use: match=${match} notnot=${notnot} eff_abi=${eff_abi} eff_arch=${eff_arch} ABI=${ABI} ARCH=${ARCH}"

	return $(( match ^ notnot ))
}

# @FUNCTION: multilib_build_binaries
# @DESCRIPTION:
# Determine wheter to build binaries for the current build ABI.
# Returns true status (0) if the current built ABI is the profile
# native or COMPLETE_MULTILIB variable is set to yes, otherwise
# false (1).
#
# The COMPLETE_MULTILIB variable can be set by users or profiles
# when they want to build binaries for none-default ABI so e.g.
# 32bit binaries on amd64.
multilib_build_binaries() {
	debug-print-function ${FUNCNAME} "${@}"

	[[ ${#} -eq 0 ]] || die "${FUNCNAME}: too many arguments"

	[[ ${COMPLETE_MULTILIB} == yes ]] || multilib_is_native_abi
}

_MULTILIB_BUILD=1
fi