• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2021 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Injects pre main init to ST startup scripts."""
15
16from typing import Optional
17
18import pathlib
19import re
20
21
22def add_pre_main_init(startup: str) -> str:
23    """Add pw_stm32cube_Init call to startup file
24
25    The stm32cube startup files directly call main(), while pigweed expects to
26    do some setup before main is called. This could include sys_io or system
27    clock initialization.
28
29    This adds a call to `pw_stm32cube_Init()` immediately before the call to
30    `main()`
31
32    Args:
33        startup: The startup script read into a string
34
35    Returns:
36        A new startup script with the `pw_stm32cube_Init()` call added.
37
38    Raises:
39        ValueError if the `main()` call is not found in `startup`
40    """
41    match = re.search(r'\s*bl\s+main', startup)
42    if match is None:
43        raise ValueError("`bl main` not found in startup script")
44
45    return startup[:match.start(
46    )] + '\nbl pw_stm32cube_Init' + startup[match.start():]
47
48
49def inject_init(startup_in: pathlib.Path, startup_out: Optional[pathlib.Path]):
50    """Injects pw_stm32cube_Init before main in given ST startup script.
51
52    Args:
53        startup_in: path to startup_*.s file
54        startup_out: path to write generated startup file or None.
55                    If None, output startup script printed to stdout
56    """
57    with open(startup_in, 'rb') as startup_in_file:
58        startup_in_str = startup_in_file.read().decode('utf-8',
59                                                       errors='ignore')
60
61    startup_out_str = add_pre_main_init(startup_in_str)
62
63    if startup_out:
64        with open(startup_out, 'w') as startup_out_file:
65            startup_out_file.write(startup_out_str)
66    else:
67        print(startup_out_str)
68