scripts/functions
author "Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
Sun Jun 15 22:02:45 2008 +0000 (2008-06-15)
changeset 564 30fbb26a83b4
parent 527 4ac12179ef23
child 582 522e4fe1ca75
permissions -rw-r--r--
Some makeinfo versions are a pain in [somewhere very painful].
Work this around with a wrapper that always succeeds, and leave incomplete files in place.

/trunk/scripts/crosstool.sh | 7 7 0 0 +++++++
1 file changed, 7 insertions(+)
     1 # This file contains some usefull common functions
     2 # Copyright 2007 Yann E. MORIN
     3 # Licensed under the GPL v2. See COPYING in the root of this package
     4 
     5 # Prepare the fault handler
     6 CT_OnError() {
     7     ret=$?
     8     CT_DoLog ERROR "Build failed in step '${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}'"
     9     for((step=(CT_STEP_COUNT-1); step>1; step--)); do
    10         CT_DoLog ERROR "      called in step '${CT_STEP_MESSAGE[${step}]}'"
    11     done
    12     CT_DoLog ERROR "Error happened in '${BASH_SOURCE[1]}' in function '${FUNCNAME[1]}' (line unknown, sorry)"
    13     for((depth=2; ${BASH_LINENO[$((${depth}-1))]}>0; depth++)); do
    14         CT_DoLog ERROR "      called from '${BASH_SOURCE[${depth}]}' at line # ${BASH_LINENO[${depth}-1]} in function '${FUNCNAME[${depth}]}'"
    15     done
    16     [ "${CT_LOG_TO_FILE}" = "y" ] && CT_DoLog ERROR "Look at '${CT_LOG_FILE}' for more info on this error."
    17     CT_STEP_COUNT=1
    18     CT_DoEnd ERROR
    19     exit $ret
    20 }
    21 
    22 # Install the fault handler
    23 trap CT_OnError ERR
    24 
    25 # Inherit the fault handler in subshells and functions
    26 set -E
    27 
    28 # Make pipes fail on the _first_ failed command
    29 # Not supported on bash < 3.x, but we need it, so drop the obsoleting bash-2.x
    30 set -o pipefail
    31 
    32 # Don't hash commands' locations, and search every time it is requested.
    33 # This is slow, but needed because of the static/shared core gcc which shall
    34 # always match to shared if it exists, and only fallback to static if the
    35 # shared is not found
    36 set +o hashall
    37 
    38 # Log policy:
    39 #  - first of all, save stdout so we can see the live logs: fd #6
    40 exec 6>&1
    41 #  - then point stdout to the log file (temporary for now)
    42 tmp_log_file="${CT_TOP_DIR}/log.$$"
    43 exec >>"${tmp_log_file}"
    44 
    45 # The different log levels:
    46 CT_LOG_LEVEL_ERROR=0
    47 CT_LOG_LEVEL_WARN=1
    48 CT_LOG_LEVEL_INFO=2
    49 CT_LOG_LEVEL_EXTRA=3
    50 CT_LOG_LEVEL_DEBUG=4
    51 CT_LOG_LEVEL_ALL=5
    52 
    53 # A function to log what is happening
    54 # Different log level are available:
    55 #   - ERROR:   A serious, fatal error occurred
    56 #   - WARN:    A non fatal, non serious error occurred, take your responsbility with the generated build
    57 #   - INFO:    Informational messages
    58 #   - EXTRA:   Extra informational messages
    59 #   - DEBUG:   Debug messages
    60 #   - ALL:     Component's build messages
    61 # Usage: CT_DoLog <level> [message]
    62 # If message is empty, then stdin will be logged.
    63 CT_DoLog() {
    64     local max_level LEVEL level cur_l cur_L
    65     local l
    66     eval max_level="\${CT_LOG_LEVEL_${CT_LOG_LEVEL_MAX}}"
    67     # Set the maximum log level to DEBUG if we have none
    68     [ -z "${max_level}" ] && max_level=${CT_LOG_LEVEL_DEBUG}
    69 
    70     LEVEL="$1"; shift
    71     eval level="\${CT_LOG_LEVEL_${LEVEL}}"
    72 
    73     if [ $# -eq 0 ]; then
    74         cat -
    75     else
    76         echo "${1}"
    77     fi |( IFS="\n" # We want the full lines, even leading spaces
    78           _prog_bar_cpt=0
    79           _prog_bar[0]='/'
    80           _prog_bar[1]='-'
    81           _prog_bar[2]='\'
    82           _prog_bar[3]='|'
    83           indent=$((2*CT_STEP_COUNT))
    84           while read line; do
    85               case "${CT_LOG_SEE_TOOLS_WARN},${line}" in
    86                 y,*"warning:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
    87                 y,*"WARNING:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
    88                 *"error:"*)             cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
    89                 *"make["?*"]:"*"Stop.") cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
    90                 *)                      cur_L="${LEVEL}"; cur_l="${level}";;
    91               esac
    92               # There will always be a log file (stdout, fd #1), be it /dev/null
    93               printf "[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}"
    94               if [ ${cur_l} -le ${max_level} ]; then
    95                   # Only print to console (fd #6) if log level is high enough.
    96                   printf "\r[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}" >&6
    97               fi
    98               if [ "${CT_LOG_PROGRESS_BAR}" = "y" ]; then
    99                   printf "\r[%02d:%02d] %s " $((SECONDS/60)) $((SECONDS%60)) "${_prog_bar[$((_prog_bar_cpt/10))]}" >&6
   100                   _prog_bar_cpt=$(((_prog_bar_cpt+1)%40))
   101               fi
   102           done
   103         )
   104 
   105     return 0
   106 }
   107 
   108 # Execute an action, and log its messages
   109 # Usage: CT_DoExecLog <level> <[VAR=val...] command [parameters...]>
   110 CT_DoExecLog() {
   111     local level="$1"
   112     shift
   113     eval "$@" 2>&1 |CT_DoLog "${level}"
   114 }
   115 
   116 # Tail message to be logged whatever happens
   117 # Usage: CT_DoEnd <level>
   118 CT_DoEnd()
   119 {
   120     local level="$1"
   121     CT_STOP_DATE=$(CT_DoDate +%s%N)
   122     CT_STOP_DATE_HUMAN=$(CT_DoDate +%Y%m%d.%H%M%S)
   123     CT_DoLog "${level:-INFO}" "Build completed at ${CT_STOP_DATE_HUMAN}"
   124     elapsed=$((CT_STOP_DATE-CT_STAR_DATE))
   125     elapsed_min=$((elapsed/(60*1000*1000*1000)))
   126     elapsed_sec=$(printf "%02d" $(((elapsed%(60*1000*1000*1000))/(1000*1000*1000))))
   127     elapsed_csec=$(printf "%02d" $(((elapsed%(1000*1000*1000))/(10*1000*1000))))
   128     CT_DoLog ${level:-INFO} "(elapsed: ${elapsed_min}:${elapsed_sec}.${elapsed_csec})"
   129 }
   130 
   131 # Abort the execution with an error message
   132 # Usage: CT_Abort <message>
   133 CT_Abort() {
   134     CT_DoLog ERROR "$1"
   135     exit 1
   136 }
   137 
   138 # Test a condition, and print a message if satisfied
   139 # Usage: CT_Test <message> <tests>
   140 CT_Test() {
   141     local ret
   142     local m="$1"
   143     shift
   144     test "$@" && CT_DoLog WARN "$m"
   145     return 0
   146 }
   147 
   148 # Test a condition, and abort with an error message if satisfied
   149 # Usage: CT_TestAndAbort <message> <tests>
   150 CT_TestAndAbort() {
   151     local m="$1"
   152     shift
   153     test "$@" && CT_Abort "$m"
   154     return 0
   155 }
   156 
   157 # Test a condition, and abort with an error message if not satisfied
   158 # Usage: CT_TestAndAbort <message> <tests>
   159 CT_TestOrAbort() {
   160     local m="$1"
   161     shift
   162     test "$@" || CT_Abort "$m"
   163     return 0
   164 }
   165 
   166 # Test the presence of a tool, or abort if not found
   167 # Usage: CT_HasOrAbort <tool>
   168 CT_HasOrAbort() {
   169     CT_TestAndAbort "'${1}' not found and needed for successful toolchain build." -z ""$(CT_Which "${1}")
   170     return 0
   171 }
   172 
   173 # Search a program: wrap "which" for those system where
   174 # "which" verbosely says there is no match (Mdk are such
   175 # suckers...)
   176 # Usage: CT_Which <filename>
   177 CT_Which() {
   178   which "$1" 2>/dev/null || true
   179 }
   180 
   181 # Get current date with nanosecond precision
   182 # On those system not supporting nanosecond precision, faked with rounding down
   183 # to the highest entire second
   184 # Usage: CT_DoDate <fmt>
   185 CT_DoDate() {
   186     date "$1" |sed -r -e 's/%N$/000000000/;'
   187 }
   188 
   189 CT_STEP_COUNT=1
   190 CT_STEP_MESSAGE[${CT_STEP_COUNT}]="<none>"
   191 # Memorise a step being done so that any error is caught
   192 # Usage: CT_DoStep <loglevel> <message>
   193 CT_DoStep() {
   194     local start=$(CT_DoDate +%s%N)
   195     CT_DoLog "$1" "================================================================="
   196     CT_DoLog "$1" "$2"
   197     CT_STEP_COUNT=$((CT_STEP_COUNT+1))
   198     CT_STEP_LEVEL[${CT_STEP_COUNT}]="$1"; shift
   199     CT_STEP_START[${CT_STEP_COUNT}]="${start}"
   200     CT_STEP_MESSAGE[${CT_STEP_COUNT}]="$1"
   201     return 0
   202 }
   203 
   204 # End the step just being done
   205 # Usage: CT_EndStep
   206 CT_EndStep() {
   207     local stop=$(CT_DoDate +%s%N)
   208     local duration=$(printf "%032d" $((stop-${CT_STEP_START[${CT_STEP_COUNT}]})) |sed -r -e 's/([[:digit:]]{2})[[:digit:]]{7}$/\.\1/; s/^0+//; s/^\./0\./;')
   209     local level="${CT_STEP_LEVEL[${CT_STEP_COUNT}]}"
   210     local message="${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}"
   211     CT_STEP_COUNT=$((CT_STEP_COUNT-1))
   212     CT_DoLog "${level}" "${message}: done in ${duration}s"
   213     return 0
   214 }
   215 
   216 # Pushes into a directory, and pops back
   217 CT_Pushd() {
   218     pushd "$1" >/dev/null 2>&1
   219 }
   220 CT_Popd() {
   221     popd >/dev/null 2>&1
   222 }
   223 
   224 # Makes a path absolute
   225 # Usage: CT_MakeAbsolutePath path
   226 CT_MakeAbsolutePath() {
   227     # Try to cd in that directory
   228     if [ -d "$1" ]; then
   229         CT_Pushd "$1"
   230         pwd
   231         CT_Popd
   232     else
   233         # No such directory, fail back to guessing
   234         case "$1" in
   235             /*)  echo "$1";;
   236             *)   echo "$(pwd)/$1";;
   237         esac
   238     fi
   239     
   240     return 0
   241 }
   242 
   243 # Creates a temporary directory
   244 # $1: variable to assign to
   245 # Usage: CT_MktempDir foo
   246 CT_MktempDir() {
   247     # Some mktemp do not allow more than 6 Xs
   248     eval "$1"=$(mktemp -q -d "${CT_BUILD_DIR}/.XXXXXX")
   249     CT_TestOrAbort "Could not make temporary directory" -n "${!1}" -a -d "${!1}"
   250 }
   251 
   252 # Echoes the specified string on stdout until the pipe breaks.
   253 # Doesn't fail
   254 # $1: string to echo
   255 # Usage: CT_DoYes "" |make oldconfig
   256 CT_DoYes() {
   257     yes "$1" || true
   258 }
   259 
   260 # Get the file name extension of a component
   261 # Usage: CT_GetFileExtension <component_name-component_version>
   262 # If found, echoes the extension to stdout
   263 # If not found, echoes nothing on stdout.
   264 CT_GetFileExtension() {
   265     local ext
   266     local file="$1"
   267 
   268     CT_Pushd "${CT_TARBALLS_DIR}"
   269     # we need to also check for an empty extension for those very
   270     # peculiar components that don't have one (such as sstrip from
   271     # buildroot).
   272     for ext in .tar.gz .tar.bz2 .tgz .tar ''; do
   273         if [ -f "${file}${ext}" ]; then
   274             echo "${ext}"
   275             break
   276         fi
   277     done
   278     CT_Popd
   279 
   280     return 0
   281 }
   282 
   283 # Download an URL using wget
   284 # Usage: CT_DoGetFileWget <URL>
   285 CT_DoGetFileWget() {
   286     # Need to return true because it is legitimate to not find the tarball at
   287     # some of the provided URLs (think about snapshots, different layouts for
   288     # different gcc versions, etc...)
   289     # Some (very old!) FTP server might not support the passive mode, thus
   290     # retry without
   291     # With automated download as we are doing, it can be very dangerous to use
   292     # -c to continue the downloads. It's far better to simply overwrite the
   293     # destination file
   294     # Some company networks have firewalls to connect to the internet, but it's
   295     # not easy to detect them, and wget does not timeout by default  while
   296     # connecting, so force a global ${CT_CONNECT_TIMEOUT}-second timeout.
   297     wget -T ${CT_CONNECT_TIMEOUT} -nc --progress=dot:binary --tries=3 --passive-ftp "$1"    \
   298     || wget -T ${CT_CONNECT_TIMEOUT} -nc --progress=dot:binary --tries=3 "$1"               \
   299     || true
   300 }
   301 
   302 # Download an URL using curl
   303 # Usage: CT_DoGetFileCurl <URL>
   304 CT_DoGetFileCurl() {
   305     # Note: comments about wget method (above) are also valid here
   306     # Plus: no good progress indicator is available with curl,
   307     #       so output is consigned to oblivion
   308     curl --ftp-pasv -O --retry 3 "$1" --connect-timeout ${CT_CONNECT_TIMEOUT} >/dev/null    \
   309     || curl -O --retry 3 "$1" --connect-timeout ${CT_CONNECT_TIMEOUT} >/dev/null            \
   310     || true
   311 }
   312 
   313 _wget=$(CT_Which wget)
   314 _curl=$(CT_Which curl)
   315 # Wrapper function to call one of curl or wget
   316 # Usage: CT_DoGetFile <URL>
   317 CT_DoGetFile() {
   318     case "${_wget},${_curl}" in
   319         ,)  CT_DoError "Could find neither wget nor curl";;
   320         ,*) CT_DoGetFileCurl "$1" 2>&1 |CT_DoLog ALL;;
   321         *)  CT_DoGetFileWget "$1" 2>&1 |CT_DoLog ALL;;
   322     esac
   323 }
   324 
   325 # Download the file from one of the URLs passed as argument
   326 # Usage: CT_GetFile <filename> [extension] <url> [url ...]
   327 CT_GetFile() {
   328     local ext
   329     local url
   330     local file="$1"
   331     local first_ext=""
   332     shift
   333     case "$1" in
   334         .tar.bz2|.tar.gz|.tgz|.tar)
   335             first_ext="$1"
   336             shift
   337             ;;
   338     esac
   339 
   340     # Do we already have it?
   341     ext=$(CT_GetFileExtension "${file}")
   342     if [ -n "${ext}" ]; then
   343         CT_DoLog DEBUG "Already have '${file}'"
   344         return 0
   345     fi
   346 
   347     CT_Pushd "${CT_TARBALLS_DIR}"
   348     # We'd rather have a bzip2'ed tarball, then gzipped tarball, plain tarball,
   349     # or, as a failover, a file without extension.
   350     # Try local copy first, if it exists
   351     for ext in ${first_ext} .tar.bz2 .tar.gz .tgz .tar ''; do
   352         CT_DoLog DEBUG "Trying '${CT_LOCAL_TARBALLS_DIR}/${file}${ext}'"
   353         if [ -r "${CT_LOCAL_TARBALLS_DIR}/${file}${ext}" -a \
   354              "${CT_FORCE_DOWNLOAD}" != "y" ]; then
   355             CT_DoLog EXTRA "Using '${file}' from local storage"
   356             ln -sv "${CT_LOCAL_TARBALLS_DIR}/${file}${ext}" "${file}${ext}" |CT_DoLog ALL
   357             return 0
   358         fi
   359     done
   360     # Try to download it
   361     CT_DoLog EXTRA "Retrieving '${file}' from network"
   362     for ext in ${first_ext} .tar.bz2 .tar.gz .tgz .tar ''; do
   363         # Try all urls in turn
   364         for url in "$@"; do
   365             CT_DoLog DEBUG "Trying '${url}/${file}${ext}'"
   366             CT_DoGetFile "${url}/${file}${ext}"
   367             if [ -f "${file}${ext}" ]; then
   368                 # No need to test if the file already exists because
   369                 # it does NOT. If it did exist, we'd have been stopped
   370                 # above, when looking for local copies.
   371                 if [ "${CT_SAVE_TARBALLS}" = "y" ]; then
   372                     CT_DoLog EXTRA "Saving '${file}' to local storage"
   373                     mv "${file}${ext}" "${CT_LOCAL_TARBALLS_DIR}" |CT_DoLog ALL
   374                     ln -sv "${CT_LOCAL_TARBALLS_DIR}/${file}${ext}" "${file}${ext}" |CT_DoLog ALL
   375                 fi
   376                 return 0
   377             fi
   378         done
   379     done
   380     CT_Popd
   381 
   382     CT_Abort "Could not download '${file}', and not present in '${CT_LOCAL_TARBALLS_DIR}'"
   383 }
   384 
   385 # Extract a tarball and patch the resulting sources if necessary.
   386 # Some tarballs need to be extracted in specific places. Eg.: glibc addons
   387 # must be extracted in the glibc directory; uCLibc locales must be extracted
   388 # in the extra/locale sub-directory of uClibc.
   389 CT_ExtractAndPatch() {
   390     local file="$1"
   391     local base_file=$(echo "${file}" |cut -d - -f 1)
   392     local ver_file=$(echo "${file}" |cut -d - -f 2-)
   393     local official_patch_dir
   394     local custom_patch_dir
   395     local libc_addon
   396     local ext=$(CT_GetFileExtension "${file}")
   397     CT_TestAndAbort "'${file}' not found in '${CT_TARBALLS_DIR}'" -z "${ext}"
   398     local full_file="${CT_TARBALLS_DIR}/${file}${ext}"
   399 
   400     CT_Pushd "${CT_SRC_DIR}"
   401 
   402     # Add-ons need a little love, really.
   403     case "${file}" in
   404         glibc-[a-z]*-*)
   405             CT_TestAndAbort "Trying to extract the C-library addon/locales '${file}' when C-library not yet extracted" ! -d "${CT_LIBC_FILE}"
   406             cd "${CT_LIBC_FILE}"
   407             libc_addon=y
   408             [ -f ".${file}.extracted" ] && return 0
   409             touch ".${file}.extracted"
   410             ;;
   411         uClibc-locale-*)
   412             CT_TestAndAbort "Trying to extract the C-library addon/locales '${file}' when C-library not yet extracted" ! -d "${CT_LIBC_FILE}"
   413             cd "${CT_LIBC_FILE}/extra/locale"
   414             libc_addon=y
   415             [ -f ".${file}.extracted" ] && return 0
   416             touch ".${file}.extracted"
   417             ;;
   418     esac
   419 
   420     # If the directory exists, then consider extraction and patching done
   421     if [ -d "${file}" ]; then
   422         CT_DoLog DEBUG "Already extracted '${file}'"
   423         return 0
   424     fi
   425 
   426     CT_DoLog EXTRA "Extracting '${file}'"
   427     case "${ext}" in
   428         .tar.bz2)     tar xvjf "${full_file}" |CT_DoLog ALL;;
   429         .tar.gz|.tgz) tar xvzf "${full_file}" |CT_DoLog ALL;;
   430         .tar)         tar xvf  "${full_file}" |CT_DoLog ALL;;
   431         *)            CT_Abort "Don't know how to handle '${file}': unknown extension" ;;
   432     esac
   433 
   434     # Snapshots might not have the version number in the extracted directory
   435     # name. This is also the case for some (odd) packages, such as D.U.M.A.
   436     # Overcome this issue by symlink'ing the directory.
   437     if [ ! -d "${file}" -a "${libc_addon}" != "y" ]; then
   438         case "${ext}" in
   439             .tar.bz2)     base=$(tar tjf "${full_file}" |head -n 1 |cut -d / -f 1 || true);;
   440             .tar.gz|.tgz) base=$(tar tzf "${full_file}" |head -n 1 |cut -d / -f 1 || true);;
   441             .tar)         base=$(tar tf  "${full_file}" |head -n 1 |cut -d / -f 1 || true);;
   442         esac
   443         CT_TestOrAbort "There was a problem when extracting '${file}'" -d "${base}" -o "${base}" != "${file}"
   444         ln -s "${base}" "${file}"
   445     fi
   446 
   447     # Kludge: outside this function, we wouldn't know if we had just extracted
   448     # a libc addon, or a plain package. Apply patches now.
   449     CT_DoLog EXTRA "Patching '${file}'"
   450 
   451     if [ "${libc_addon}" = "y" ]; then
   452         # Some addon tarballs directly contain the correct addon directory,
   453         # while others have the addon directory named after the tarball.
   454         # Fix that by always using the short name (eg: linuxthreads, ports, etc...)
   455         addon_short_name=$(echo "${file}" |sed -r -e 's/^[^-]+-//; s/-[^-]+$//;')
   456         [ -d "${addon_short_name}" ] || ln -s "${file}" "${addon_short_name}"
   457         # If libc addon, we're already in the correct place
   458     else
   459         cd "${file}"
   460     fi
   461 
   462     official_patch_dir=
   463     custom_patch_dir=
   464     [ "${CUSTOM_PATCH_ONLY}" = "y" ] || official_patch_dir="${CT_LIB_DIR}/patches/${base_file}/${ver_file}"
   465     [ "${CT_CUSTOM_PATCH}" = "y" ] && custom_patch_dir="${CT_CUSTOM_PATCH_DIR}/${base_file}/${ver_file}"
   466     for patch_dir in "${official_patch_dir}" "${custom_patch_dir}"; do
   467         if [ -n "${patch_dir}" -a -d "${patch_dir}" ]; then
   468             for p in "${patch_dir}"/*.patch; do
   469                 if [ -f "${p}" ]; then
   470                     CT_DoLog DEBUG "Applying patch '${p}'"
   471                     patch -g0 -F1 -p1 -f <"${p}" |CT_DoLog ALL
   472                     CT_TestAndAbort "Failed while applying patch file '${p}'" ${PIPESTATUS[0]} -ne 0
   473                 fi
   474             done
   475         fi
   476     done
   477 
   478     if [ "${CT_OVERIDE_CONFIG_GUESS_SUB}" = "y" ]; then
   479         CT_DoLog ALL "Overiding config.guess and config.sub"
   480         for cfg in config_guess config_sub; do
   481             eval ${cfg}="${CT_LIB_DIR}/tools/${cfg/_/.}"
   482             [ -e "${CT_TOP_DIR}/tools/${cfg/_/.}" ] && eval ${cfg}="${CT_TOP_DIR}/tools/${cfg/_/.}"
   483             find . -type f -name "${cfg/_/.}" -exec cp -v "${!cfg}" {} \; |CT_DoLog ALL
   484         done
   485     fi
   486 
   487     CT_Popd
   488 }
   489 
   490 # Two wrappers to call config.(guess|sub) either from CT_TOP_DIR or CT_LIB_DIR.
   491 # Those from CT_TOP_DIR, if they exist, will be be more recent than those from CT_LIB_DIR.
   492 CT_DoConfigGuess() {
   493     if [ -x "${CT_TOP_DIR}/tools/config.guess" ]; then
   494         "${CT_TOP_DIR}/tools/config.guess"
   495     else
   496         "${CT_LIB_DIR}/tools/config.guess"
   497     fi
   498 }
   499 
   500 CT_DoConfigSub() {
   501     if [ -x "${CT_TOP_DIR}/tools/config.sub" ]; then
   502         "${CT_TOP_DIR}/tools/config.sub" "$@"
   503     else
   504         "${CT_LIB_DIR}/tools/config.sub" "$@"
   505     fi
   506 }
   507 
   508 # Compute the target tuple from what is provided by the user
   509 # Usage: CT_DoBuildTargetTuple
   510 # In fact this function takes the environment variables to build the target
   511 # tuple. It is needed both by the normal build sequence, as well as the
   512 # sample saving sequence.
   513 CT_DoBuildTargetTuple() {
   514     # Set the endianness suffix, and the default endianness gcc option
   515     case "${CT_ARCH_BE},${CT_ARCH_LE}" in
   516         y,) target_endian_eb=eb
   517             target_endian_el=
   518             CT_ARCH_ENDIAN_CFLAG="-mbig-endian"
   519             CT_ARCH_ENDIAN_LDFLAG="-EB"
   520             ;;
   521         ,y) target_endian_eb=
   522             target_endian_el=el
   523             CT_ARCH_ENDIAN_CFLAG="-mlittle-endian"
   524             CT_ARCH_ENDIAN_LDFLAG="-EL"
   525             ;;
   526     esac
   527 
   528     # Set defaults for the system part of the tuple. Can be overriden
   529     # by architecture-specific values.
   530     case "${CT_LIBC}" in
   531         glibc)  CT_TARGET_SYS=gnu;;
   532         uClibc) CT_TARGET_SYS=uclibc;;
   533     esac
   534 
   535     # Transform the ARCH into a kernel-understandable ARCH
   536     CT_KERNEL_ARCH="${CT_ARCH}"
   537 
   538     # Set the default values for ARCH, ABI, CPU, TUNE, FPU and FLOAT
   539     unset CT_ARCH_ARCH_CFLAG CT_ARCH_ABI_CFLAG CT_ARCH_CPU_CFLAG CT_ARCH_TUNE_CFLAG CT_ARCH_FPU_CFLAG CT_ARCH_FLOAT_CFLAG
   540     unset CT_ARCH_WITH_ARCH CT_ARCH_WITH_ABI CT_ARCH_WITH_CPU CT_ARCH_WITH_TUNE CT_ARCH_WITH_FPU CT_ARCH_WITH_FLOAT
   541     [ "${CT_ARCH_ARCH}"     ] && { CT_ARCH_ARCH_CFLAG="-march=${CT_ARCH_ARCH}";  CT_ARCH_WITH_ARCH="--with-arch=${CT_ARCH_ARCH}"; }
   542     [ "${CT_ARCH_ABI}"      ] && { CT_ARCH_ABI_CFLAG="-mabi=${CT_ARCH_ABI}";     CT_ARCH_WITH_ABI="--with-abi=${CT_ARCH_ABI}";    }
   543     [ "${CT_ARCH_CPU}"      ] && { CT_ARCH_CPU_CFLAG="-mcpu=${CT_ARCH_CPU}";     CT_ARCH_WITH_CPU="--with-cpu=${CT_ARCH_CPU}";    }
   544     [ "${CT_ARCH_TUNE}"     ] && { CT_ARCH_TUNE_CFLAG="-mtune=${CT_ARCH_TUNE}";  CT_ARCH_WITH_TUNE="--with-tune=${CT_ARCH_TUNE}"; }
   545     [ "${CT_ARCH_FPU}"      ] && { CT_ARCH_FPU_CFLAG="-mfpu=${CT_ARCH_FPU}";     CT_ARCH_WITH_FPU="--with-fpu=${CT_ARCH_FPU}";    }
   546     [ "${CT_ARCH_FLOAT_SW}" ] && { CT_ARCH_FLOAT_CFLAG="-msoft-float";           CT_ARCH_WITH_FLOAT="--with-float=soft";          }
   547 
   548     # Call the architecture specific settings
   549     CT_DoArchValues
   550 
   551     # Finish the target tuple construction
   552     case "${CT_KERNEL}" in
   553         linux*)  CT_TARGET_KERNEL=linux;;
   554     esac
   555     CT_TARGET=$(CT_DoConfigSub "${CT_TARGET_ARCH}-${CT_TARGET_VENDOR:-unknown}-${CT_TARGET_KERNEL}-${CT_TARGET_SYS}")
   556 
   557     # Prepare the target CFLAGS
   558     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_ENDIAN_CFLAG}"
   559     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ARCH_CFLAG}"
   560     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ABI_CFLAG}"
   561     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_CPU_CFLAG}"
   562     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_TUNE_CFLAG}"
   563     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FPU_CFLAG}"
   564     CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FLOAT_CFLAG}"
   565 
   566     # Now on for the target LDFLAGS
   567     CT_ARCH_TARGET_LDFLAGS="${CT_ARCH_ENDIAN_LDFLAG}"
   568 }
   569 
   570 # This function does pause the build until the user strikes "Return"
   571 # Usage: CT_DoPause [optional_message]
   572 CT_DoPause() {
   573     local foo
   574     local message="${1:-Pausing for your pleasure}"
   575     CT_DoLog INFO "${message}"
   576     read -p "Press 'Enter' to continue, or Ctrl-C to stop..." foo >&6
   577     return 0
   578 }
   579 
   580 # This function saves the state of the toolchain to be able to restart
   581 # at any one point
   582 # Usage: CT_DoSaveState <next_step_name>
   583 CT_DoSaveState() {
   584 	[ "${CT_DEBUG_CT_SAVE_STEPS}" = "y" ] || return 0
   585     local state_name="$1"
   586     local state_dir="${CT_STATE_DIR}/${state_name}"
   587 
   588     CT_DoLog DEBUG "Saving state to restart at step '${state_name}'..."
   589     rm -rf "${state_dir}"
   590     mkdir -p "${state_dir}"
   591 
   592     case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   593         y)  tar_opt=z; tar_ext=.gz;;
   594         *)  tar_opt=;  tar_ext=;;
   595     esac
   596 
   597     CT_DoLog DEBUG "  Saving environment and aliases"
   598     # We must omit shell functions
   599     set |awk '
   600          BEGIN { _p = 1; }
   601          $0~/^[^ ]+ \(\)/ { _p = 0; }
   602          _p == 1
   603          $0 == "}" { _p = 1; }
   604          ' >"${state_dir}/env.sh"
   605 
   606     CT_DoLog DEBUG "  Saving CT_CC_CORE_STATIC_PREFIX_DIR='${CT_CC_CORE_STATIC_PREFIX_DIR}'"
   607     CT_Pushd "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   608     tar cv${tar_opt}f "${state_dir}/cc_core_static_prefix_dir.tar${tar_ext}" . |CT_DoLog DEBUG
   609     CT_Popd
   610 
   611     CT_DoLog DEBUG "  Saving CT_CC_CORE_SHARED_PREFIX_DIR='${CT_CC_CORE_SHARED_PREFIX_DIR}'"
   612     CT_Pushd "${CT_CC_CORE_SHARED_PREFIX_DIR}"
   613     tar cv${tar_opt}f "${state_dir}/cc_core_shared_prefix_dir.tar${tar_ext}" . |CT_DoLog DEBUG
   614     CT_Popd
   615 
   616     CT_DoLog DEBUG "  Saving CT_PREFIX_DIR='${CT_PREFIX_DIR}'"
   617     CT_Pushd "${CT_PREFIX_DIR}"
   618     tar cv${tar_opt}f "${state_dir}/prefix_dir.tar${tar_ext}" --exclude '*.log' . |CT_DoLog DEBUG
   619     CT_Popd
   620 
   621     if [ "${CT_LOG_TO_FILE}" = "y" ]; then
   622         CT_DoLog DEBUG "  Saving log file"
   623         exec >/dev/null
   624         case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   625             y)  gzip -3 -c "${CT_LOG_FILE}"  >"${state_dir}/log.gz";;
   626             *)  cat "${CT_LOG_FILE}" >"${state_dir}/log";;
   627         esac
   628         exec >>"${CT_LOG_FILE}"
   629     fi
   630 }
   631 
   632 # This function restores a previously saved state
   633 # Usage: CT_DoLoadState <state_name>
   634 CT_DoLoadState(){
   635     local state_name="$1"
   636     local state_dir="${CT_STATE_DIR}/${state_name}"
   637     local old_RESTART="${CT_RESTART}"
   638     local old_STOP="${CT_STOP}"
   639 
   640     CT_TestOrAbort "The previous build did not reach the point where it could be restarted at '${CT_RESTART}'" -d "${state_dir}"
   641 
   642     # We need to do something special with the log file!
   643     if [ "${CT_LOG_TO_FILE}" = "y" ]; then
   644         exec >"${state_dir}/tail.log"
   645     fi
   646     CT_DoLog INFO "Restoring state at step '${state_name}', as requested."
   647 
   648     case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   649         y)  tar_opt=z; tar_ext=.gz;;
   650         *)  tar_opt=;  tar_ext=;;
   651     esac
   652 
   653     CT_DoLog DEBUG "  Removing previous build directories"
   654     chmod -R u+rwX "${CT_PREFIX_DIR}" "${CT_CC_CORE_SHARED_PREFIX_DIR}" "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   655     rm -rf         "${CT_PREFIX_DIR}" "${CT_CC_CORE_SHARED_PREFIX_DIR}" "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   656     mkdir -p       "${CT_PREFIX_DIR}" "${CT_CC_CORE_SHARED_PREFIX_DIR}" "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   657 
   658     CT_DoLog DEBUG "  Restoring CT_PREFIX_DIR='${CT_PREFIX_DIR}'"
   659     CT_Pushd "${CT_PREFIX_DIR}"
   660     tar xv${tar_opt}f "${state_dir}/prefix_dir.tar${tar_ext}" |CT_DoLog DEBUG
   661     CT_Popd
   662 
   663     CT_DoLog DEBUG "  Restoring CT_CC_CORE_SHARED_PREFIX_DIR='${CT_CC_CORE_SHARED_PREFIX_DIR}'"
   664     CT_Pushd "${CT_CC_CORE_SHARED_PREFIX_DIR}"
   665     tar xv${tar_opt}f "${state_dir}/cc_core_shared_prefix_dir.tar${tar_ext}" |CT_DoLog DEBUG
   666     CT_Popd
   667 
   668     CT_DoLog DEBUG "  Restoring CT_CC_CORE_STATIC_PREFIX_DIR='${CT_CC_CORE_STATIC_PREFIX_DIR}'"
   669     CT_Pushd "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   670     tar xv${tar_opt}f "${state_dir}/cc_core_static_prefix_dir.tar${tar_ext}" |CT_DoLog DEBUG
   671     CT_Popd
   672 
   673     # Restore the environment, discarding any error message
   674     # (for example, read-only bash internals)
   675     CT_DoLog DEBUG "  Restoring environment"
   676     . "${state_dir}/env.sh" >/dev/null 2>&1 || true
   677 
   678     # Restore the new RESTART and STOP steps
   679     CT_RESTART="${old_RESTART}"
   680     CT_STOP="${old_STOP}"
   681     unset old_stop old_restart
   682 
   683     if [ "${CT_LOG_TO_FILE}" = "y" ]; then
   684         CT_DoLog DEBUG "  Restoring log file"
   685         exec >/dev/null
   686         case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   687             y)  zcat "${state_dir}/log.gz" >"${CT_LOG_FILE}";;
   688             *)  cat "${state_dir}/log" >"${CT_LOG_FILE}";;
   689         esac
   690         cat "${state_dir}/tail.log" >>"${CT_LOG_FILE}"
   691         exec >>"${CT_LOG_FILE}"
   692         rm -f "${state_dir}/tail.log"
   693     fi
   694 }