summaryrefslogtreecommitdiff
path: root/tools/gcc.py
blob: dfcb98c617fc44cb834f1df05ffcc46721612e2f (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#
# File      : gcc.py
# This file is part of RT-Thread RTOS
# COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Change Logs:
# Date           Author       Notes
# 2018-05-22     Bernard      The first version
# 2023-11-03     idings       return file path in GetHeader

import os
import re
import platform
import subprocess

def GetGCCRoot(rtconfig):
    exec_path = rtconfig.EXEC_PATH
    prefix = rtconfig.PREFIX

    if prefix.endswith('-'):
        prefix = prefix[:-1]

    if exec_path == '/usr/bin':
        root_path = os.path.join('/usr/lib', prefix)
    else:
        root_path = os.path.join(exec_path, '..', prefix)

    return root_path

# https://stackoverflow.com/questions/4980819/what-are-the-gcc-default-include-directories
# https://stackoverflow.com/questions/53937211/how-can-i-parse-gcc-output-by-regex-to-get-default-include-paths
def match_pattern(pattern, input, start = 0, stop = -1, flags = 0):
    length = len(input)

    if length == 0:
        return None

    end_it = max(0, length - 1)

    if start >= end_it:
        return None

    if stop<0:
        stop = length

    if stop <= start:
        return None

    for it in range(max(0, start), min(stop, length)):
        elem = input[it]
        match = re.match(pattern, elem, flags)
        if match:
            return it

def GetGccDefaultSearchDirs(rtconfig):
    start_pattern = r' *#include <\.\.\.> search starts here: *'
    end_pattern = r' *End of search list\. *'

    gcc_cmd = os.path.join(rtconfig.EXEC_PATH, rtconfig.CC)
    device_flags = rtconfig.DEVICE.split()
    command = [gcc_cmd] + device_flags + ['-xc', '-E', '-v', os.devnull]

    # if gcc_cmd can not access , return empty list
    if not os.access(gcc_cmd, os.X_OK):
        return []

    if(platform.system() == 'Windows'):
        child = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    else:
        child = subprocess.Popen(' '.join(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

    stdout = child.communicate()
    stdout_string = (b''.join(stdout)).decode()
    lines = stdout_string.splitlines()

    start_it = match_pattern(start_pattern, lines)
    if start_it == None:
        return []

    end_it = match_pattern(end_pattern, lines, start_it)
    if end_it == None:
        return []

    # theres no paths between them
    if (end_it - start_it) == 1:
        return []

    return lines[start_it + 1 : end_it]

def GetHeader(rtconfig, filename):
    include_dirs = GetGccDefaultSearchDirs(rtconfig)
    for directory in include_dirs:
        fn = os.path.join(directory, filename).strip()
        if os.path.isfile(fn):
            return fn

    # fallback to use fixed method if can't autodetect
    root = GetGCCRoot(rtconfig)
    fn = os.path.join(root, 'include', filename)
    if os.path.isfile(fn):
        return fn

    # Usually the cross compiling gcc toolchain has directory as:
    #
    # bin
    # lib
    # share
    # arm-none-eabi
    #    bin
    #    include
    #    lib
    #    share
    prefix = rtconfig.PREFIX
    if prefix.endswith('-'):
        prefix = prefix[:-1]

    fn = os.path.join(root, prefix, 'include', filename)
    if os.path.isfile(fn):
        return fn

    return None

# GCC like means the toolchains which are compatible with GCC
def GetGCCLikePLATFORM():
    return ['gcc', 'armclang', 'llvm-arm']

def GetPicoLibcVersion(rtconfig):
    version = None
    try:
        rtconfig.PREFIX
    except:
        return version

    # get version from picolibc.h
    fn = GetHeader(rtconfig, 'picolibc.h')

    if fn:
        f = open(fn, 'r')
        if f:
            for line in f:
                if line.find('__PICOLIBC_VERSION__') != -1 and line.find('"') != -1:
                    version = re.search(r'\"([^"]+)\"', line).groups()[0]
            f.close()

    return version

def GetNewLibVersion(rtconfig):
    version = None

    try:
        rtconfig.PREFIX
    except:
        return version

    # if find picolibc.h, use picolibc
    fn = GetHeader(rtconfig, 'picolibc.h')
    if fn:
        return version

    # get version from _newlib_version.h file
    fn = GetHeader(rtconfig, '_newlib_version.h')

    # get version from newlib.h
    if not fn:
        fn = GetHeader(rtconfig, 'newlib.h')

    if fn:
        f = open(fn, 'r')
        for line in f:
            if line.find('_NEWLIB_VERSION') != -1 and line.find('"') != -1:
                version = re.search(r'\"([^"]+)\"', line).groups()[0]
        f.close()

    return version

# FIXME: there is no musl version or musl macros can be found officially
def GetMuslVersion(rtconfig):
    version = None

    try:
        rtconfig.PREFIX
    except:
        return version

    if 'musl' in rtconfig.PREFIX:
        version = 'unknown'
    return version

def GCCResult(rtconfig, str):
    result = ''

    def checkAndGetResult(pattern, string):
        if re.search(pattern, string):
            return re.search(pattern, string).group(0)
        return None

    gcc_cmd = os.path.join(rtconfig.EXEC_PATH, rtconfig.CC)

    # use temp file to get more information
    f = open('__tmp.c', 'w')
    if f:
        f.write(str)
        f.close()

        # '-fdirectives-only',
        if(platform.system() == 'Windows'):
            child = subprocess.Popen([gcc_cmd, '-E', '-P', '__tmp.c'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        else:
            child = subprocess.Popen(gcc_cmd + ' -E -P __tmp.c', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

        stdout, stderr = child.communicate()

        # print(stdout)
        if stderr != '' and stderr != b'':
            print(stderr)

        have_fdset = 0
        have_sigaction = 0
        have_sigevent = 0
        have_siginfo = 0
        have_sigval = 0
        version = None
        stdc = '1989'
        posix_thread = 0

        for line in stdout.split(b'\n'):
            line = line.decode()
            if re.search('fd_set', line):
                have_fdset = 1

            # check for sigal
            if re.search('struct[ \t]+sigaction', line):
                have_sigaction = 1
            if re.search('struct[ \t]+sigevent', line):
                have_sigevent = 1
            if re.search('siginfo_t', line):
                have_siginfo = 1
            if re.search('union[ \t]+sigval', line):
                have_sigval = 1

            if re.search('char\* version', line):
                version = re.search(r'\"([^"]+)\"', line).groups()[0]

            if re.findall('iso_c_visible = [\d]+', line):
                stdc = re.findall('[\d]+', line)[0]

            if re.findall('pthread_create', line):
                posix_thread = 1

        if have_fdset:
            result += '#define HAVE_FDSET 1\n'

        if have_sigaction:
            result += '#define HAVE_SIGACTION 1\n'
        if have_sigevent:
            result += '#define HAVE_SIGEVENT 1\n'
        if have_siginfo:
            result += '#define HAVE_SIGINFO 1\n'
        if have_sigval:
            result += '#define HAVE_SIGVAL 1\n'

        if version:
            result += '#define GCC_VERSION_STR "%s"\n' % version

        result += '#define STDC "%s"\n' % stdc

        if posix_thread:
            result += '#define LIBC_POSIX_THREADS 1\n'

        os.remove('__tmp.c')
    return result