scripts/functions
author "Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
Mon Jul 14 15:22:53 2008 +0000 (2008-07-14)
changeset 658 3e590fb8f1a6
parent 657 6eb39aec2d07
child 668 65e27c3bcf99
permissions -rw-r--r--
Don't print double-faults.

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