scripts/functions
author "Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
Tue Jan 27 22:27:35 2009 +0000 (2009-01-27)
branch1.3
changeset 1165 a6433a0af46e
parent 1081 10d1270080e6
permissions -rw-r--r--
Backport #1288 from /trunk:
- Fix aborting when neither wget nor curl are present

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