1#!/usr/bin/env python3
2# coding=utf-8
3
4#
5# Copyright (c) 2022 Huawei Device Co., Ltd.
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#     http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19import os
20import sys
21import subprocess
22import stat
23
24from xdevice import platform_logger
25
26FLAGS = os.O_WRONLY | os.O_CREAT | os.O_EXCL
27MODES = stat.S_IWUSR | stat.S_IRUSR
28
29LOG = platform_logger("Gen")
30
31
32class Gen(object):
33    @classmethod
34    def fuzz_dir_generation(cls, options):
35        helper_path = os.path.join("..", "libs", "fuzzlib", "fuzzer_helper.py")
36        fuzz_path = os.path.join(sys.source_code_root_path, options.dirpath)
37        LOG.info("fuzz_path = %s" % fuzz_path)
38        if not os.path.exists(fuzz_path):
39            os.makedirs(fuzz_path)
40            LOG.info("make folder %s" % fuzz_path)
41
42        command = [sys.executable, helper_path, 'generate',
43                   options.fuzzername, fuzz_path]
44        LOG.info("command %s" % command)
45        subprocess.call(command, shell=False)
46
47    def process_command_gen(self, options):
48        if (len(options.testtype) != 1) or (options.dirpath == "") or \
49                (options.fuzzername == ""):
50            LOG.error(
51                "GEN need para -t(testtype) -fz(fuzzername) -dp(dirpath)")
52            return
53        if "FUZZ" in options.testtype:
54            self.fuzz_dir_generation(options)
55        else:
56            LOG.error("GEN is not support %s." % options.testtype)
57
58    def gen_fuzzer_list_file(self, fuzzer_list):
59        filepath = os.path.join(sys.source_code_root_path, "test",
60            "developer_test", "libs", "fuzzlib", "fuzzer_list.txt")
61        LOG.info("The fuzzer list file path: %s" % filepath)
62        if os.path.exists(filepath):
63            os.remove(filepath)
64        with os.fdopen(os.open(filepath, FLAGS, MODES), 'w') as gn_file:
65            gn_file.truncate(0)
66            if fuzzer_list:
67                for target in fuzzer_list:
68                    if target:
69                        gn_file.write("\"%s\",\n" % target)
70