scripts/functions
author "Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
Sun May 27 20:22:06 2007 +0000 (2007-05-27)
changeset 136 22b5ef41df97
parent 135 b2695c2f1919
child 141 860f8380538d
permissions -rw-r--r--
Merge the NPTL stuff.
That still leaves the linuxthreads stuff broken, but it was just before. I don't care anyway. Time to fix that later...
     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 # The different log levels:
    39 CT_LOG_LEVEL_ERROR=0
    40 CT_LOG_LEVEL_WARN=1
    41 CT_LOG_LEVEL_INFO=2
    42 CT_LOG_LEVEL_EXTRA=3
    43 CT_LOG_LEVEL_DEBUG=4
    44 CT_LOG_LEVEL_ALL=5
    45 
    46 # A function to log what is happening
    47 # Different log level are available:
    48 #   - ERROR:   A serious, fatal error occurred
    49 #   - WARN:    A non fatal, non serious error occurred, take your responsbility with the generated build
    50 #   - INFO:    Informational messages
    51 #   - EXTRA:   Extra informational messages
    52 #   - DEBUG:   Debug messages
    53 #   - ALL:     Component's build messages
    54 # Usage: CT_DoLog <level> [message]
    55 # If message is empty, then stdin will be logged.
    56 CT_DoLog() {
    57     local max_level LEVEL level cur_l cur_L
    58     local l
    59     eval max_level="\${CT_LOG_LEVEL_${CT_LOG_LEVEL_MAX}}"
    60     # Set the maximum log level to DEBUG if we have none
    61     [ -z "${max_level}" ] && max_level=${CT_LOG_LEVEL_DEBUG}
    62 
    63     LEVEL="$1"; shift
    64     eval level="\${CT_LOG_LEVEL_${LEVEL}}"
    65 
    66     if [ $# -eq 0 ]; then
    67         cat -
    68     else
    69         echo "${1}"
    70     fi |( offset=$((`CT_DoDate +%s`+(CT_STAR_DATE/(1000*1000*1000))))
    71           IFS="\n" # We want the full lines, even leading spaces
    72           CT_PROG_BAR_CPT=0
    73           indent=$((2*CT_STEP_COUNT))
    74           while read line; do
    75               case "${CT_LOG_SEE_TOOLS_WARN},${line}" in
    76                 y,*"warning:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
    77                 y,*"WARNING:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
    78                 *"error:"*)             cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
    79                 *"make["?*"]:"*"Stop.") cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
    80                 *)                      cur_L="${LEVEL}"; cur_l="${level}";;
    81               esac
    82               l="`printf \"[%-5s]%*s%s%s\" \"${cur_L}\" \"${indent}\" \" \" \"${line}\"`"
    83               # There will always be a log file, be it /dev/null
    84               echo -e "${l}"
    85               if [ ${cur_l} -le ${max_level} ]; then
    86                   echo -e "\r${l}" >&6
    87               fi
    88               if [ "${CT_LOG_PROGRESS_BAR}" = "y" ]; then
    89                   elapsed=$((SECONDS+OFFSET))
    90                   [ ${CT_PROG_BAR_CPT} -eq 0  ] && bar="/"
    91                   [ ${CT_PROG_BAR_CPT} -eq 10 ] && bar="-"
    92                   [ ${CT_PROG_BAR_CPT} -eq 20 ] && bar="\\"
    93                   [ ${CT_PROG_BAR_CPT} -eq 30 ] && bar="|"
    94                   printf "\r[%02d:%02d] %s " $((elapsed/60)) $((elapsed%60)) "${bar}" >&6
    95                   CT_PROG_BAR_CPT=$(((CT_PROG_BAR_CPT+1)%40))
    96               fi
    97           done
    98         )
    99 
   100     return 0
   101 }
   102 
   103 # Tail message to be logged whatever happens
   104 # Usage: CT_DoEnd <level>
   105 CT_DoEnd()
   106 {
   107     CT_STOP_DATE=`CT_DoDate +%s%N`
   108     CT_STOP_DATE_HUMAN=`CT_DoDate +%Y%m%d.%H%M%S`
   109     CT_DoLog INFO "Build completed at ${CT_STOP_DATE_HUMAN}"
   110     elapsed=$((CT_STOP_DATE-CT_STAR_DATE))
   111     elapsed_min=$((elapsed/(60*1000*1000*1000)))
   112     elapsed_sec=`printf "%02d" $(((elapsed%(60*1000*1000*1000))/(1000*1000*1000)))`
   113     elapsed_csec=`printf "%02d" $(((elapsed%(1000*1000*1000))/(10*1000*1000)))`
   114     CT_DoLog ${1:-INFO} "(elapsed: ${elapsed_min}:${elapsed_sec}.${elapsed_csec})"
   115 }
   116 
   117 # Abort the execution with an error message
   118 # Usage: CT_Abort <message>
   119 CT_Abort() {
   120     CT_DoLog ERROR "$1"
   121     exit 1
   122 }
   123 
   124 # Test a condition, and print a message if satisfied
   125 # Usage: CT_Test <message> <tests>
   126 CT_Test() {
   127     local ret
   128     local m="$1"
   129     shift
   130     test "$@" && CT_DoLog WARN "$m"
   131     return 0
   132 }
   133 
   134 # Test a condition, and abort with an error message if satisfied
   135 # Usage: CT_TestAndAbort <message> <tests>
   136 CT_TestAndAbort() {
   137     local m="$1"
   138     shift
   139     test "$@" && CT_Abort "$m"
   140     return 0
   141 }
   142 
   143 # Test a condition, and abort with an error message if not satisfied
   144 # Usage: CT_TestAndAbort <message> <tests>
   145 CT_TestOrAbort() {
   146     local m="$1"
   147     shift
   148     test "$@" || CT_Abort "$m"
   149     return 0
   150 }
   151 
   152 # Test the presence of a tool, or abort if not found
   153 # Usage: CT_HasOrAbort <tool>
   154 CT_HasOrAbort() {
   155     CT_TestAndAbort "\"${1}\" not found and needed for successfull toolchain build." -z "`which \"${1}\"`"
   156     return 0
   157 }
   158 
   159 # Get current date with nanosecond precision
   160 # On those system not supporting nanosecond precision, faked with rounding down
   161 # to the highest entire second
   162 # Usage: CT_DoDate <fmt>
   163 CT_DoDate() {
   164     date "$1" |sed -r -e 's/%N$/000000000/;'
   165 }
   166 
   167 CT_STEP_COUNT=1
   168 CT_STEP_MESSAGE[${CT_STEP_COUNT}]="<none>"
   169 # Memorise a step being done so that any error is caught
   170 # Usage: CT_DoStep <loglevel> <message>
   171 CT_DoStep() {
   172     local start=`CT_DoDate +%s%N`
   173     CT_DoLog "$1" "================================================================="
   174     CT_DoLog "$1" "$2"
   175     CT_STEP_COUNT=$((CT_STEP_COUNT+1))
   176     CT_STEP_LEVEL[${CT_STEP_COUNT}]="$1"; shift
   177     CT_STEP_START[${CT_STEP_COUNT}]="${start}"
   178     CT_STEP_MESSAGE[${CT_STEP_COUNT}]="$1"
   179     return 0
   180 }
   181 
   182 # End the step just being done
   183 # Usage: CT_EndStep
   184 CT_EndStep() {
   185     local stop=`CT_DoDate +%s%N`
   186     local duration=`printf "%032d" $((stop-${CT_STEP_START[${CT_STEP_COUNT}]})) |sed -r -e 's/([[:digit:]]{2})[[:digit:]]{7}$/\.\1/; s/^0+//; s/^\./0\./;'`
   187     local level="${CT_STEP_LEVEL[${CT_STEP_COUNT}]}"
   188     local message="${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}"
   189     CT_STEP_COUNT=$((CT_STEP_COUNT-1))
   190     CT_DoLog "${level}" "${message}: done in ${duration}s"
   191     return 0
   192 }
   193 
   194 # Pushes into a directory, and pops back
   195 CT_Pushd() {
   196     pushd "$1" >/dev/null 2>&1
   197 }
   198 CT_Popd() {
   199     popd >/dev/null 2>&1
   200 }
   201 
   202 # Makes a path absolute
   203 # Usage: CT_MakeAbsolutePath path
   204 CT_MakeAbsolutePath() {
   205     # Try to cd in that directory
   206     if [ -d "$1" ]; then
   207         CT_Pushd "$1"
   208         pwd
   209         CT_Popd
   210     else
   211         # No such directory, fail back to guessing
   212         case "$1" in
   213             /*)  echo "$1";;
   214             *)   echo "`pwd`/$1";;
   215         esac
   216     fi
   217     
   218     return 0
   219 }
   220 
   221 # Creates a temporary directory
   222 # $1: variable to assign to
   223 # Usage: CT_MktempDir foo
   224 CT_MktempDir() {
   225     # Some mktemp do not allow more than 6 Xs
   226     eval "$1"="`mktemp -q -d \"${CT_BUILD_DIR}/.XXXXXX\"`"
   227     CT_TestOrAbort "Could not make temporary directory" -n "${!1}" -a -d "${!1}"
   228 }
   229 
   230 # Echoes the specified string on stdout until the pipe breaks.
   231 # Doesn't fail
   232 # $1: string to echo
   233 # Usage: CT_DoYes "" |make oldconfig
   234 CT_DoYes() {
   235     yes "$1" || true
   236 }
   237 
   238 # Get the file name extension of a component
   239 # Usage: CT_GetFileExtension <component_name-component_version>
   240 # If found, echoes the extension to stdout
   241 # If not found, echoes nothing on stdout.
   242 CT_GetFileExtension() {
   243     local ext
   244     local file="$1"
   245     local got_it=1
   246 
   247     CT_Pushd "${CT_TARBALLS_DIR}"
   248     for ext in .tar.gz .tar.bz2 .tgz .tar; do
   249         if [ -f "${file}${ext}" ]; then
   250             echo "${ext}"
   251             got_it=0
   252             break
   253         fi
   254     done
   255     CT_Popd
   256 
   257     return 0
   258 }
   259 
   260 # Download an URL using wget
   261 # Usage: CT_DoGetFileWget <URL>
   262 CT_DoGetFileWget() {
   263     # Need to return true because it is legitimate to not find the tarball at
   264     # some of the provided URLs (think about snapshots, different layouts for
   265     # different gcc versions, etc...)
   266     # Some (very old!) FTP server might not support the passive mode, thus
   267     # retry without
   268     # With automated download as we are doing, it can be very dangerous to use
   269     # -c to continue the downloads. It's far better to simply overwrite the
   270     # destination file
   271     wget -nc --progress=dot:binary --tries=3 --passive-ftp "$1" || wget -nc --progress=dot:binary --tries=3 "$1" || true
   272 }
   273 
   274 # Download an URL using curl
   275 # Usage: CT_DoGetFileCurl <URL>
   276 CT_DoGetFileCurl() {
   277 	# Note: comments about wget method are also valid here
   278 	# Plus: no good progreess indicator is available with curl,
   279 	#       so output is consigned to oblivion
   280 	curl --ftp-pasv -O --retry 3 "$1" >/dev/null || curl -O --retry 3 "$1" >/dev/null || true
   281 }
   282 
   283 # Wrapper function to call one of curl or wget
   284 # Usage: CT_DoGetFile <URL>
   285 CT_DoGetFile() {
   286     local _wget=`which wget`
   287     local _curl=`which curl`
   288     case "${_wget},${_curl}" in
   289         ,)  CT_DoError "Could find neither wget nor curl";;
   290         ,*) CT_DoGetFileCurl "$1" 2>&1 |CT_DoLog DEBUG;;
   291         *)  CT_DoGetFileWget "$1" 2>&1 |CT_DoLog DEBUG;;
   292     esac
   293 }
   294 
   295 # Download the file from one of the URLs passed as argument
   296 # Usage: CT_GetFile <filename> <url> [<url> ...]
   297 CT_GetFile() {
   298     local got_it
   299     local ext
   300     local url
   301     local file="$1"
   302     shift
   303 
   304     # Do we already have it?
   305     ext=`CT_GetFileExtension "${file}"`
   306     if [ -n "${ext}" ]; then
   307         CT_DoLog DEBUG "Already have \"${file}\""
   308         return 0
   309     fi
   310 
   311     CT_Pushd "${CT_TARBALLS_DIR}"
   312     # File not yet downloaded, try to get it
   313     got_it=0
   314     # We'd rather have a bzip2'ed tarball, then gzipped, and finally plain tar.
   315     # Try local copy first, if it exists
   316     for ext in .tar.bz2 .tar.gz .tgz .tar; do
   317         if [ -r "${CT_LOCAL_TARBALLS_DIR}/${file}${ext}" -a \
   318              "${CT_FORCE_DOWNLOAD}" != "y" ]; then
   319             CT_DoLog EXTRA "Copying \"${file}\" from local copy"
   320             cp -v "${CT_LOCAL_TARBALLS_DIR}/${file}${ext}" "${file}${ext}" |CT_DoLog ALL
   321             return 0
   322         fi
   323     done
   324     # Try to download it
   325     CT_DoLog EXTRA "Retrieving \"${file}\""
   326     for ext in .tar.bz2 .tar.gz .tgz .tar; do
   327         # Try all urls in turn
   328         for url in "$@"; do
   329             case "${url}" in
   330                 *)  CT_DoLog DEBUG "Trying \"${url}/${file}${ext}\""
   331                     CT_DoGetFile "${url}/${file}${ext}"
   332                     ;;
   333             esac
   334             [ -f "${file}${ext}" ] && return 0 || true
   335         done
   336     done
   337     CT_Popd
   338 
   339     CT_Abort "Could not download \"${file}\", and not present in \"${CT_LOCAL_TARBALLS_DIR}\""
   340 }
   341 
   342 # Extract a tarball and patch the resulting sources if necessary.
   343 # Some tarballs need to be extracted in specific places. Eg.: glibc addons
   344 # must be extracted in the glibc directory; uCLibc locales must be extracted
   345 # in the extra/locale sub-directory of uClibc.
   346 CT_ExtractAndPatch() {
   347     local file="$1"
   348     local base_file=`echo "${file}" |cut -d - -f 1`
   349     local ver_file=`echo "${file}" |cut -d - -f 2-`
   350     local official_patch_dir
   351     local custom_patch_dir
   352     local libc_addon
   353     local ext=`CT_GetFileExtension "${file}"`
   354     CT_TestAndAbort "\"${file}\" not found in \"${CT_TARBALLS_DIR}\"" -z "${ext}"
   355     local full_file="${CT_TARBALLS_DIR}/${file}${ext}"
   356 
   357     CT_Pushd "${CT_SRC_DIR}"
   358 
   359     # Add-ons need a little love, really.
   360     case "${file}" in
   361         glibc-[a-z]*-*)
   362             CT_TestAndAbort "Trying to extract the C-library addon/locales \"${file}\" when C-library not yet extracted" ! -d "${CT_LIBC_FILE}"
   363             cd "${CT_LIBC_FILE}"
   364             libc_addon=y
   365             [ -f ".${file}.extracted" ] && return 0
   366             touch ".${file}.extracted"
   367             ;;
   368         uClibc-locale-*)
   369             CT_TestAndAbort "Trying to extract the C-library addon/locales \"${file}\" when C-library not yet extracted" ! -d "${CT_LIBC_FILE}"
   370             cd "${CT_LIBC_FILE}/extra/locale"
   371             libc_addon=y
   372             [ -f ".${file}.extracted" ] && return 0
   373             touch ".${file}.extracted"
   374             ;;
   375     esac
   376 
   377     # If the directory exists, then consider extraction and patching done
   378     if [ -d "${file}" ]; then
   379         CT_DoLog DEBUG "Already extracted \"${file}\""
   380         return 0
   381     fi
   382 
   383     CT_DoLog EXTRA "Extracting \"${file}\""
   384     case "${ext}" in
   385         .tar.bz2)     tar xvjf "${full_file}" |CT_DoLog ALL;;
   386         .tar.gz|.tgz) tar xvzf "${full_file}" |CT_DoLog ALL;;
   387         .tar)         tar xvf  "${full_file}" |CT_DoLog ALL;;
   388         *)            CT_Abort "Don't know how to handle \"${file}\": unknown extension" ;;
   389     esac
   390 
   391     # Snapshots might not have the version number in the extracted directory
   392     # name. This is also the case for some (old) packages, such as libfloat.
   393     # Overcome this issue by symlink'ing the directory.
   394     if [ ! -d "${file}" -a "${libc_addon}" != "y" ]; then
   395         case "${ext}" in
   396             .tar.bz2)     base=`tar tjf "${full_file}" |head -n 1 |cut -d / -f 1 || true`;;
   397             .tar.gz|.tgz) base=`tar tzf "${full_file}" |head -n 1 |cut -d / -f 1 || true`;;
   398             .tar)         base=`tar tf  "${full_file}" |head -n 1 |cut -d / -f 1 || true`;;
   399         esac
   400         CT_TestOrAbort "There was a problem when extracting \"${file}\"" -d "${base}" -o "${base}" != "${file}"
   401         ln -s "${base}" "${file}"
   402     fi
   403 
   404     # Kludge: outside this function, we wouldn't know if we had just extracted
   405     # a libc addon, or a plain package. Apply patches now.
   406     CT_DoLog EXTRA "Patching \"${file}\""
   407 
   408     if [ "${libc_addon}" = "y" ]; then
   409         # Some addons tarball directly contian the correct addon directory,
   410         # while others have the addon directory named ofter the tarball.
   411         # Fix that bu always using the short name (eg: linuxthreads, ports, etc...)
   412         addon_short_name=`echo "${file}" |sed -r -e 's/^[^-]+-//; s/-[^-]+$//;'`
   413         [ -d "${addon_short_name}" ] || ln -s "${file}" "${addon_short_name}"
   414         # If libc addon, we're already in the correct place
   415     else
   416         cd "${file}"
   417     fi
   418 
   419     [ "${CUSTOM_PATCH_ONLY}" = "y" ] || official_patch_dir="${CT_TOP_DIR}/patches/${base_file}/${ver_file}"
   420     [ "${CT_CUSTOM_PATCH}" = "y" ] && custom_patch_dir="${CT_CUSTOM_PATCH_DIR}/${base_file}/${ver_file}"
   421     for patch_dir in "${official_patch_dir}" "${custom_patch_dir}"; do
   422         if [ -n "${patch_dir}" -a -d "${patch_dir}" ]; then
   423             for p in "${patch_dir}"/*.patch; do
   424                 if [ -f "${p}" ]; then
   425                     CT_DoLog DEBUG "Applying patch \"${p}\""
   426                     patch -g0 -F1 -p1 -f <"${p}" |CT_DoLog ALL
   427                     CT_TestAndAbort "Failed while applying patch file \"${p}\"" ${PIPESTATUS[0]} -ne 0
   428                 fi
   429             done
   430         fi
   431     done
   432 
   433     CT_Popd
   434 }
   435 
   436 # Compute the target triplet from what is provided by the user
   437 # Usage: CT_DoBuildTargetTriplet
   438 # In fact this function takes the environment variables to build the target
   439 # triplet. It is needed both by the normal build sequence, as well as the
   440 # sample saving sequence.
   441 CT_DoBuildTargetTriplet() {
   442     case "${CT_ARCH_BE},${CT_ARCH_LE}" in
   443         y,) target_endian_eb=eb; target_endian_el=;;
   444         ,y) target_endian_eb=; target_endian_el=el;;
   445     esac
   446     case "${CT_ARCH}" in
   447         arm)  CT_TARGET="${CT_ARCH}${target_endian_eb}";;
   448         mips) CT_TARGET="${CT_ARCH}${target_endian_el}";;
   449         x86*) # Much love for this one :-(
   450               arch="${CT_ARCH_ARCH}"
   451               [ -z "${arch}" ] && arch="${CT_ARCH_TUNE}"
   452               case "${CT_ARCH}" in
   453                   x86_64)  CT_TARGET=x86_64;;
   454               	  *)  case "${arch}" in
   455                           "")                                       CT_TARGET=i386;;
   456                           i386|i486|i586|i686)                      CT_TARGET="${arch}";;
   457                           winchip*)                                 CT_TARGET=i486;;
   458                           pentium|pentium-mmx|c3*)                  CT_TARGET=i586;;
   459                           nocona|athlon*64|k8|athlon-fx|opteron)    CT_TARGET=x86_64;;
   460                           pentiumpro|pentium*|athlon*)              CT_TARGET=i686;;
   461                           *)                                        CT_TARGET=i586;;
   462                       esac;;
   463               esac;;
   464     esac
   465     case "${CT_TARGET_VENDOR}" in
   466         "") CT_TARGET="${CT_TARGET}-unknown";;
   467         *)  CT_TARGET="${CT_TARGET}-${CT_TARGET_VENDOR}";;
   468     esac
   469     case "${CT_KERNEL}" in
   470         linux*)  CT_TARGET="${CT_TARGET}-linux";;
   471     esac
   472     case "${CT_LIBC}" in
   473         glibc)  CT_TARGET="${CT_TARGET}-gnu";;
   474         uClibc) CT_TARGET="${CT_TARGET}-uclibc";;
   475     esac
   476     CT_TARGET="`${CT_TOP_DIR}/tools/config.sub ${CT_TARGET}`"
   477 }
   478 
   479 # This function does pause the build until the user strikes "Return"
   480 # Usage: CT_DoPause [optional_message]
   481 CT_DoPause() {
   482     local foo
   483     local message="${1:-Pausing for your pleasure}"
   484     CT_DoLog INFO "${message}"
   485     read -p "Press \"Enter\" to continue, or Ctrl-C to stop..." foo >&6
   486     return 0
   487 }
   488 
   489 # This function saves the state of the toolchain to be able to restart
   490 # at any one point
   491 # Usage: CT_DoSaveState <next_step_name>
   492 CT_DoSaveState() {
   493 	[ "${CT_DEBUG_CT_SAVE_STEPS}" = "y" ] || return 0
   494     local state_name="$1"
   495     local state_dir="${CT_STATE_DIR}/${state_name}"
   496 
   497     CT_DoLog DEBUG "Saving state to restart at step \"${state_name}\"..."
   498     rm -rf "${state_dir}"
   499     mkdir -p "${state_dir}"
   500 
   501     case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   502         y)  tar_opt=czf; tar_ext=".tar.gz";;
   503         *)  tar_opt=cf;  tar_ext=".tar";;
   504     esac
   505 
   506     CT_DoLog DEBUG "  Saving environment and aliases"
   507     # We must omit shell functions
   508     # 'isgrep' is here because I don't seem to
   509     # be able to remove the functions names.
   510     set |awk '
   511          BEGIN { _p = 1; }
   512          $0~/^[^ ] ()/ { _p = 0; }
   513          _p == 1
   514          $0 == "}" { _p = 1; }
   515          ' |egrep -v '^[^ ]+ \(\)' >"${state_dir}/env.sh"
   516 
   517     CT_DoLog DEBUG "  Saving CT_CC_CORE_STATIC_PREFIX_DIR=\"${CT_CC_CORE_STATIC_PREFIX_DIR}\""
   518     CT_Pushd "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   519     tar ${tar_opt} "${state_dir}/cc_core_static_prefix_dir${tar_ext}" .
   520     CT_Popd
   521 
   522     CT_DoLog DEBUG "  Saving CT_CC_CORE_SHARED_PREFIX_DIR=\"${CT_CC_CORE_SHARED_PREFIX_DIR}\""
   523     CT_Pushd "${CT_CC_CORE_SHARED_PREFIX_DIR}"
   524     tar ${tar_opt} "${state_dir}/cc_core_shared_prefix_dir${tar_ext}" .
   525     CT_Popd
   526 
   527     CT_DoLog DEBUG "  Saving CT_PREFIX_DIR=\"${CT_PREFIX_DIR}\""
   528     CT_Pushd "${CT_PREFIX_DIR}"
   529     tar ${tar_opt} "${state_dir}/prefix_dir${tar_ext}" --exclude '*.log' .
   530     CT_Popd
   531 
   532     if [ "${CT_LOG_TO_FILE}" = "y" ]; then
   533         CT_DoLog DEBUG "  Saving log file"
   534         exec >/dev/null
   535         case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   536             y)  gzip -3 -c "${CT_LOG_FILE}"  >"${state_dir}/log.gz";;
   537             *)  cat "${CT_LOG_FILE}" >"${state_dir}/log";;
   538         esac
   539         exec >>"${CT_LOG_FILE}"
   540     fi
   541 }
   542 
   543 # This function restores a previously saved state
   544 # Usage: CT_DoLoadState <state_name>
   545 CT_DoLoadState(){
   546     local state_name="$1"
   547     local state_dir="${CT_STATE_DIR}/${state_name}"
   548     local old_RESTART="${CT_RESTART}"
   549     local old_STOP="${CT_STOP}"
   550 
   551     # We need to do something special with the log file!
   552     if [ "${CT_LOG_TO_FILE}" = "y" ]; then
   553         exec >"${state_dir}/tail.log"
   554     fi
   555     CT_DoLog INFO "Restoring state at step \"${state_name}\", as requested."
   556 
   557     case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   558         y)  tar_opt=xzf; tar_ext=".tar.gz";;
   559         *)  tar_opt=cf;  tar_ext=".tar";;
   560     esac
   561 
   562     CT_DoLog DEBUG "  Removing previous build directories"
   563     chmod -R u+rwX "${CT_PREFIX_DIR}" "${CT_CC_CORE_SHARED_PREFIX_DIR}" "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   564     rm -rf         "${CT_PREFIX_DIR}" "${CT_CC_CORE_SHARED_PREFIX_DIR}" "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   565     mkdir -p       "${CT_PREFIX_DIR}" "${CT_CC_CORE_SHARED_PREFIX_DIR}" "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   566 
   567     CT_DoLog DEBUG "  Restoring CT_PREFIX_DIR=\"${CT_PREFIX_DIR}\""
   568     CT_Pushd "${CT_PREFIX_DIR}"
   569     tar ${tar_opt} "${state_dir}/prefix_dir${tar_ext}"
   570     CT_Popd
   571 
   572     CT_DoLog DEBUG "  Restoring CT_CC_CORE_SHARED_PREFIX_DIR=\"${CT_CC_CORE_SHARED_PREFIX_DIR}\""
   573     CT_Pushd "${CT_CC_CORE_SHARED_PREFIX_DIR}"
   574     tar ${tar_opt} "${state_dir}/cc_core_shared_prefix_dir${tar_ext}"
   575     CT_Popd
   576 
   577     CT_DoLog DEBUG "  Restoring CT_CC_CORE_STATIC_PREFIX_DIR=\"${CT_CC_CORE_STATIC_PREFIX_DIR}\""
   578     CT_Pushd "${CT_CC_CORE_STATIC_PREFIX_DIR}"
   579     tar ${tar_opt} "${state_dir}/cc_core_static_prefix_dir${tar_ext}"
   580     CT_Popd
   581 
   582     # Restore the environment, discarding any error message
   583     # (for example, read-only bash internals)
   584     CT_DoLog DEBUG "  Restoring environment"
   585     . "${state_dir}/env.sh" >/dev/null 2>&1 || true
   586 
   587     # Restore the new RESTART and STOP steps
   588     CT_RESTART="${old_RESTART}"
   589     CT_STOP="${old_STOP}"
   590     unset old_stop old_restart
   591 
   592     if [ "${CT_LOG_TO_FILE}" = "y" ]; then
   593         CT_DoLog DEBUG "  Restoring log file"
   594         exec >/dev/null
   595         case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
   596             y)  zcat "${state_dir}/log.gz" >"${CT_LOG_FILE}";;
   597             *)  cat "${state_dir}/log" >"${CT_LOG_FILE}";;
   598         esac
   599         cat "${state_dir}/tail.log" >>"${CT_LOG_FILE}"
   600         exec >>"${CT_LOG_FILE}"
   601         rm -f "${state_dir}/tail.log"
   602     fi
   603 }