1#!/usr/bin/env python3
2#
3# Copyright (c) 2021 Intel Corporation
4# Copyright (c) 2024 Nordic Semiconductor ASA
5#
6# SPDX-License-Identifier: Apache-2.0
7
8"""
9Parser library for Dictionary-based Logging
10
11This library along with dictionary_parser converts the
12input binary data to the log using log database.
13"""
14
15import logging
16import sys
17
18import dictionary_parser
19from dictionary_parser.log_database import LogDatabase
20
21
22def parser(logdata, dbfile, logger):
23    """function of serial parser"""
24    # Read from database file
25    database = LogDatabase.read_json_database(dbfile)
26
27    if not isinstance(logger, logging.Logger):
28        raise ValueError("Invalid logger instance. Please configure the logger!")
29
30    if database is None:
31        logger.error("ERROR: Cannot open database file:  exiting...")
32        sys.exit(1)
33
34    if logdata is None:
35        logger.error("ERROR: cannot read log from file:  exiting...")
36        sys.exit(1)
37
38    log_parser = dictionary_parser.get_parser(database)
39    if log_parser is not None:
40        logger.debug("# Build ID: %s", database.get_build_id())
41        logger.debug("# Target: %s, %d-bit", database.get_arch(), database.get_tgt_bits())
42        if database.is_tgt_little_endian():
43            logger.debug("# Endianness: Little")
44        else:
45            logger.debug("# Endianness: Big")
46
47        ret = log_parser.parse_log_data(logdata)
48        if not ret:
49            logger.error("ERROR: there were error(s) parsing log data")
50            sys.exit(1)
51    else:
52        logger.error("ERROR: Cannot find a suitable parser matching database version!")
53