summaryrefslogtreecommitdiff
path: root/components/rust/tools/build_usrapp.py
blob: 9d97a60ffeb47a455eafc83a6423df96270127e5 (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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import os
import subprocess
import toml
import shutil


# Configuration to feature mapping table
# This table defines which RT-Thread configurations should enable which Rust features
# All feature configurations are now defined in feature_config_examples.py
CONFIG_FEATURE_MAP = {}

# Application directory to Kconfig mapping table
# This table defines which Kconfig options control which application directories
APP_CONFIG_MAP = {
    'fs': 'RT_RUST_EXAMPLE_FS',
    'loadlib': 'RT_RUST_EXAMPLE_LOADLIB', 
    'mutex': 'RT_RUST_EXAMPLE_MUTEX',
    'param': 'RT_RUST_EXAMPLE_PARAM',
    'queue': 'RT_RUST_EXAMPLE_QUEUE',
    'semaphore': 'RT_RUST_EXAMPLE_SEMAPHORE',
    'thread': 'RT_RUST_EXAMPLE_THREAD'
}


def should_build_app(app_dir, has_func):
    """
    Check if an application should be built based on Kconfig configuration
    
    Args:
        app_dir: Application directory path
        has_func: Function to check if a configuration is enabled
        
    Returns:
        bool: True if the application should be built
    """
    # Get the application name from the directory
    app_name = os.path.basename(app_dir)
    
    # Check if there's a specific Kconfig option for this app
    if app_name in APP_CONFIG_MAP:
        config_option = APP_CONFIG_MAP[app_name]
        return has_func(config_option)
    
    # If no specific config found, check if applications are enabled in general
    return has_func('RT_RUST_BUILD_APPLICATIONS')


def check_app_dependencies(app_dir, required_dependencies):
    """
    Check if an application has the required dependencies
    
    Args:
        app_dir: Application directory path
        required_dependencies: List of dependency names to check
        
    Returns:
        bool: True if all required dependencies are present
    """
    if not app_dir or not required_dependencies:
        return True
    
    cargo_toml_path = os.path.join(app_dir, 'Cargo.toml')
    if not os.path.exists(cargo_toml_path):
        return False
    
    try:
        with open(cargo_toml_path, 'r') as f:
            cargo_data = toml.load(f)
        
        dependencies = cargo_data.get('dependencies', {})
        
        # Check if all required dependencies are present
        for dep in required_dependencies:
            if dep not in dependencies:
                return False
        
        return True
        
    except Exception as e:
        print(f"Warning: Failed to parse {cargo_toml_path}: {e}")
        return False


def collect_features(has_func, app_dir=None):
    """
    Collect Rust features based on RT-Thread configuration using extensible mapping table
    
    Args:
        has_func: Function to check if a configuration is enabled
        app_dir: Application directory to check dependencies (optional)
        
    Returns:
        list: List of features to enable
    """
    features = []
    
    # Iterate through all configured mappings
    for config_name, config_info in CONFIG_FEATURE_MAP.items():
        # Check if this RT-Thread configuration is enabled
        if has_func(config_name):
            feature_name = config_info['feature']
            required_deps = config_info.get('dependencies', [])
            
            # If app_dir is provided, check dependencies
            if app_dir:
                if check_app_dependencies(app_dir, required_deps):
                    features.append(feature_name)
                    print(f"Enabling feature '{feature_name}' for {config_name} in {os.path.basename(app_dir)}")
            else:
                # If no app_dir provided, enable for all (backward compatibility)
                features.append(feature_name)
                print(f"Enabling feature '{feature_name}' for {config_name}")
    
    return features





class UserAppBuildError(Exception):
    """User application build error exception"""
    pass


def parse_cargo_toml(cargo_toml_path):
    """
    Parse Cargo.toml file to extract library name and library type
    
    Args:
        cargo_toml_path: Path to Cargo.toml file
        
    Returns:
        tuple: (lib_name, is_staticlib)
    """
    try:
        with open(cargo_toml_path, 'r') as f:
            cargo_data = toml.load(f)
        
        package_name = cargo_data.get('package', {}).get('name')
        if not package_name:
            raise UserAppBuildError(f"No package name found in {cargo_toml_path}")
        
        lib_config = cargo_data.get('lib', {})
        crate_type = lib_config.get('crate-type', [])
        is_staticlib = 'staticlib' in crate_type
        
        # Use lib name if specified, otherwise use package name
        lib_name = lib_config.get('name', package_name)
        
        return lib_name, is_staticlib
        
    except Exception as e:
        raise UserAppBuildError(f"Failed to parse {cargo_toml_path}: {e}")


def discover_user_apps(base_dir):
    """
    Discover all user application directories
    
    Args:
        base_dir: Base directory path
        
    Returns:
        list: List of directories containing Cargo.toml
    """
    user_apps = []
    
    for root, dirs, files in os.walk(base_dir):
        if 'Cargo.toml' in files:
            if 'target' in root or 'build' in root:
                continue
            user_apps.append(root)
    
    return user_apps


def build_user_app(app_dir, target, debug, rustflags, build_root, features=None):
    """
    Build a single user application
    
    Args:
        app_dir: Application directory
        target: Rust target architecture
        debug: Whether this is a debug build
        rustflags: Rust compilation flags
        build_root: Build root directory
        features: List of features to enable
        
    Returns:
        tuple: (success, lib_name, lib_path)
    """
    try:
        cargo_toml_path = os.path.join(app_dir, 'Cargo.toml')
        lib_name, is_staticlib = parse_cargo_toml(cargo_toml_path)
        
        if not is_staticlib:
            return False, None, None
        
        env = os.environ.copy()
        env['RUSTFLAGS'] = rustflags
        env['CARGO_TARGET_DIR'] = build_root
        
        cmd = ['cargo', 'build', '--target', target]
        if not debug:
            cmd.append('--release')
        
        # Add features if specified
        if features:
            cmd.extend(['--features', ','.join(features)])
        
        print(f"Building example user app {lib_name} (cargo)…")
        result = subprocess.run(cmd, cwd=app_dir, env=env, 
                              capture_output=True, text=True)
        
        if result.returncode != 0:
            print(f"Failed to build user app in {app_dir}")
            print(f"Command: {' '.join(cmd)}")
            print(f"Return code: {result.returncode}")
            print(f"STDOUT: {result.stdout}")
            print(f"STDERR: {result.stderr}")
            return False, None, None
        
        lib_file = find_library_file(build_root, target, lib_name, debug)
        if lib_file:
            # Return the library name for linking
            return True, lib_name, lib_file
        else:
            print(f"Library file not found for lib {lib_name}")
            return False, None, None
            
    except Exception as e:
        print(f"Exception occurred while building user app in {app_dir}: {e}")
        return False, None, None


def find_library_file(build_root, target, lib_name, debug):
    """
    Find the generated library file
    
    Args:
        build_root: Build root directory
        target: Rust target architecture
        lib_name: Library name
        debug: Whether this is a debug build
        
    Returns:
        str: Library file path, or None if not found
    """
    profile = "debug" if debug else "release"
    
    possible_names = [
        f"lib{lib_name}.a",
        f"lib{lib_name.replace('-', '_')}.a"
    ]
    
    search_paths = [
        os.path.join(build_root, target, profile),
        os.path.join(build_root, target, profile, "deps")
    ]
    
    for search_path in search_paths:
        if not os.path.exists(search_path):
            continue
                    
        for name in possible_names:
            lib_path = os.path.join(search_path, name)
            if os.path.exists(lib_path):
                return lib_path
    
    return None


def build_all_user_apps(base_dir, target, debug, rustflags, build_root, has_func):
    """
    Build all user applications
    
    Args:
        base_dir: User applications base directory
        target: Rust target architecture
        debug: Whether this is a debug build
        rustflags: Rust compilation flags
        build_root: Build root directory
        has_func: Function to check if a configuration is enabled
        
    Returns:
        tuple: (LIBS, LIBPATH, success_count, total_count)
    """
    LIBS = []
    LIBPATH = []
    success_count = 0
    
    user_apps = discover_user_apps(base_dir)
    total_count = len(user_apps)
    
    for app_dir in user_apps:
        # Check if this application should be built based on Kconfig
        if not should_build_app(app_dir, has_func):
            app_name = os.path.basename(app_dir)
            print(f"Skipping {app_name} (disabled in Kconfig)")
            continue
            
        # Collect features for this specific app
        features = collect_features(has_func, app_dir)
        success, lib_name, lib_path = build_user_app(app_dir, target, debug, rustflags, build_root, features)
        
        if success and lib_path:
            app_name = os.path.basename(app_dir)
            print(f"Example user app {app_name} built successfully")
            LIBS.append(lib_name)
            lib_dir = os.path.dirname(lib_path)
            if lib_dir not in LIBPATH:
                LIBPATH.append(lib_dir)
            success_count += 1
    
    return LIBS, LIBPATH, success_count, total_count


def generate_linkflags(LIBS, LIBPATH):
    """
    Generate link flags
    
    Args:
        LIBS: List of library names
        LIBPATH: List of library paths
        
    Returns:
        str: Link flags string
    """
    if not LIBS or not LIBPATH:
        return ""
    
    linkflags = f" -L{LIBPATH[0]} -Wl,--whole-archive"
    for lib in LIBS:
        linkflags += f" -l{lib}"
    linkflags += " -Wl,--no-whole-archive -Wl,--allow-multiple-definition"
    
    return linkflags


def clean_user_apps_build(build_root):
    """
    Clean user applications build artifacts
    
    Args:
        build_root: Build root directory
    """
    if os.path.exists(build_root):
        shutil.rmtree(build_root)


def build_example_usrapp(cwd, has_func, rtconfig, build_root=None):
    """
    Build the example user applications.
    
    Args:
        cwd: Current working directory (usrapp directory)
        has_func: Function to check if a configuration is enabled
        rtconfig: RT-Thread configuration module
        build_root: Optional build root directory
        
    Returns:
        tuple: (LIBS, LIBPATH, LINKFLAGS) for SCons
    """
    LIBS = []
    LIBPATH = []
    LINKFLAGS = ""
    
    try:
        # Import build support functions
        import sys
        sys.path.append(os.path.join(cwd, '../rust/tools'))
        import build_support as rust_build_support
        
        target = rust_build_support.detect_rust_target(has_func, rtconfig)
        debug = bool(has_func('RUST_DEBUG_BUILD'))
        rustflags = rust_build_support.make_rustflags(rtconfig, target)
        LIBS, LIBPATH, success_count, total_count = build_all_user_apps(
            cwd, target, debug, rustflags, build_root, has_func
        )
        
        if success_count == 0 and total_count > 0:
            print(f'Warning: Failed to build all {total_count} user applications')
        elif success_count > 0:
            LINKFLAGS = generate_linkflags(LIBS, LIBPATH)
            print(f'Example user apps linked successfully')
            
    except UserAppBuildError as e:
        print(f'Error: {e}')
    except Exception as e:
        print(f'Unexpected error during user apps build: {e}')
    
    return LIBS, LIBPATH, LINKFLAGS