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