scripts/functions
author "Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
Fri Jul 25 09:52:52 2008 +0000 (2008-07-25)
changeset 718 da8af0237e78
parent 695 320862b2d6f1
child 719 dcb9bea1e09b
permissions -rw-r--r--
Re-instatethe fortran forntend for this sample.

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