summaryrefslogtreecommitdiff
path: root/tools/build/src/engine/cwd.c
blob: 7ebe97045f970d880d55d6eecf627cfd7a3ffe69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
 * Copyright 2002. Vladimir Prus
 * Copyright 2005. Rene Rivera
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 */

#include "cwd.h"

#include "jam.h"
#include "mem.h"
#include "pathsys.h"

#include <assert.h>
#include <errno.h>
#include <limits.h>

/* MinGW on Windows declares PATH_MAX in limits.h */
#if defined( NT ) && !defined( __GNUC__ )
# include <direct.h>
# define PATH_MAX _MAX_PATH
#else
# include <unistd.h>
# if defined( __COMO__ )
#  include <linux/limits.h>
# endif
#endif

#ifndef PATH_MAX
# define PATH_MAX 1024
#endif


static OBJECT * cwd_;


void cwd_init( void )
{
    int buffer_size = PATH_MAX;
    char * cwd_buffer = 0;
    int error;

    assert( !cwd_ );

    do
    {
        char * const buffer = BJAM_MALLOC_RAW( buffer_size );
        cwd_buffer = getcwd( buffer, buffer_size );
        error = errno;
        if ( cwd_buffer )
        {
            /* We store the path using its canonical/long/key format. */
            OBJECT * const cwd = object_new( cwd_buffer );
            cwd_ = path_as_key( cwd );
            object_free( cwd );
        }
        buffer_size *= 2;
        BJAM_FREE_RAW( buffer );
    }
    while ( !cwd_ && error == ERANGE );

    if ( !cwd_ )
    {
        perror( "can not get current working directory" );
        exit( EXITBAD );
    }
}


OBJECT * cwd( void )
{
    assert( cwd_ );
    return cwd_;
}


void cwd_done( void )
{
    assert( cwd_ );
    object_free( cwd_ );
    cwd_ = NULL;
}