Example #1
0
    def verify(self):
        """
        Verify integrity of the license file is integral, cnippet's version, and
        expiration date.
        """

        secret = '$*we#j238@#WA!%'
        h = hashlib.sha1()
        h.update(secret[10:12])
        h.update(base64.b64encode(self.product))
        h.update(secret[1:4])
        h.update(self.version[0])
        h.update(secret[6:9])
        h.update(self.email)
        h.update(self.expiration)
        digest = h.hexdigest()

        # If the hash doesn't match, data has been corrupted.
        if self.key != digest:
            sys.exit(DiagnosticReporter.fatal(CORRUPTED_LICENSE_FILE))

        # Verify product version.
        if int(self.version[0]) != Version().major:
            sys.exit(
                DiagnosticReporter.fatal(INCOMPATIBLE_LICENSE_PRODUCT_VERSION))

        # Verify expiration.
        exp_date = datetime.datetime.strptime(self.expiration, '%d/%B/%Y')
        if datetime.datetime.today() > exp_date:
            sys.exit(DiagnosticReporter.fatal(LICENSE_EXPIRED))
Example #2
0
    def __init__(self, path):
        """
        Validate and initialize data.
        """

        if not os.path.isfile(path):
            sys.exit(DiagnosticReporter.fatal(LICENSE_FILE_NOT_FOUND))

        if os.stat(path).st_size == 0:
            sys.exit(DiagnosticReporter.fatal(CORRUPTED_LICENSE_FILE))

        with open(path, 'r') as f:
            content = f.read()
        lines = content.splitlines()

        if len(lines) != 6:
            sys.exit(DiagnosticReporter.fatal(CORRUPTED_LICENSE_FILE))

        self.product = LicenseFile._check_line(lines[1]).strip()
        self.version = LicenseFile._check_line(lines[2]).strip()
        self.key = LicenseFile._check_line(lines[3]).strip()
        self.expiration = LicenseFile._check_line(lines[4]).strip()
        self.email = LicenseFile._check_line(lines[5]).strip()

        version_pat = re.compile('\d+\.\d+\.\d+')
        if not version_pat.match(self.version):
            sys.exit(DiagnosticReporter.fatal(CORRUPTED_LICENSE_FILE))
Example #3
0
    def collect(self):
        expect_out_file = False
        for w in self.cmd:
            # TODO: Deal with -E... Do nothing?

            # Collect file(s) being compiled.
            if w.endswith(".c"):
                self.sources.append(w)
                continue

            # Identify C version, if specified.
            if w.startswith("-std="):
                self.c_version = w[5:]
            if w == "-ansi":
                self.c_version = "c90"

            # Pedantic compilation.
            if w == "-pedantic-errors":
                self.pedantic = True

            # Keep track of output file, if specified.
            if expect_out_file:
                self.out_file_name = w
                expect_out_file = False

            if w == "-o":
                expect_out_file = True

        # Temporary
        if self.c_version != 'c99':
            DiagnosticReporter.warning(C_VERSION_NOT_SUPPORTED)
            self.c_version = 'c99'
Example #4
0
    def execute(self):
        """
        Entry point.
        """

        trace_op(Driver._id, flatten(self.cnip_opt['host_cc_cmd']))

        if not self.cc.is_supported():
            sys.exit(DiagnosticReporter.fatal(HOST_C_COMPILER_NOT_FOUND))

        cc_cmd = self.cc.parse_command()

        if not cc_cmd.out_file_name:
            gen_dir = ''
        else:
            (gen_dir, _) = os.path.split(cc_cmd.out_file_name)
            if gen_dir:
                gen_dir += '/'
            else:
                gen_dir = ''

        # The adjusted command that is forwarded to the host C compiler is the
        # one provided by the user, with input file replaced.
        new_cmd = self.cnip_opt['host_cc_cmd']

        for c_file_path in cc_cmd.sources:
            if not os.path.isfile(c_file_path):
                sys.exit(
                    DiagnosticReporter.fatal(FILE_DOES_NOT_EXIST, c_file_path))

            if self.cc.check_syntax(c_file_path) == 0:
                # If there are missing declarations in the source, this check
                # would've failed. Since it didn't, there's nothing to infer.
                continue

            unit = make_unit(c_file_path, gen_dir)
            self._compile_unit(unit, cc_cmd)

            trace_op(
                Driver._id,
                f'replace {unit.c_file_path} for {unit.cnip_file_path} in command'
            )
            new_cmd = [
                w.replace(unit.c_file_path, unit.cnip_file_path)
                for w in new_cmd
            ]

        cmd = [self.cnip_opt['host_cc'], '-x', 'c'] + new_cmd

        ok = execute(Driver._id, cmd)
        if ok != 0:
            sys.exit(
                DiagnosticReporter.fatal(HOST_C_COMPILER_FORWARDING_FAILED))

        return 0
Example #5
0
    def execute(self):
        """
        Entry point.
        """

        debug(Driver.ID(), flatten(self.cnip_opts['cc_cmd_line']))

        if not self.cc.is_supported():
            sys.exit(DiagnosticReporter.fatal(HOST_C_COMPILER_NOT_FOUND))

        cc_cmd = self.cc.parse_command()

        if not cc_cmd.out_file_name:
            gen_dir = ''
        else:
            (gen_dir, _) = os.path.split(cc_cmd.out_file_name)
            if gen_dir:
                gen_dir += '/'
            else:
                gen_dir = ''

        # The new command that is forwarded to the host C compiler is the
        # original one provided by the user, with the input file replaced.
        new_cmd = self.cnip_opts['cc_cmd_line']

        for c_file in cc_cmd.c_files:
            if not os.path.isfile(c_file):
                sys.exit(DiagnosticReporter.fatal(FILE_DOES_NOT_EXIST, c_file))

            if self.cc.check_syntax(c_file) == 0:
                # If there are missing declarations in the source, this check
                # would've failed. Since it didn't, there's nothing to infer.
                continue

            unit = make_unit(c_file, gen_dir)
            self._compile_unit(unit, cc_cmd)

            debug(Driver.ID(),
                  f'replace {unit.c_file} for {unit.cnip_file} in command')
            new_cmd = [w.replace(unit.c_file, unit.cnip_file) for w in new_cmd]

        cmd = [self.cnip_opts['cc']] + new_cmd
        code = execute(Driver.ID(), cmd)
        if code != 0:
            sys.exit(
                DiagnosticReporter.fatal(HOST_C_COMPILER_FORWARDING_FAILED))

        return 0
Example #6
0
    def generate_constraints(self,
                             unit: Unit,
                             cc_opts):
        """
        Generate constraints for a unit.
        """

        cmd = [self.generator,
               unit.c_file_path,
               '-o', unit.cstr_file_path,
               '--cc', self.host_cc,
               '--cc-std', cc_opts.c_version]
        cmd += CCompilerFacade.predefined_macros('--cc-D')
        cmd += CCompilerFacade.undefined_macros('--cc-U')

        maybe_append('--no-typedef', self.no_typedef, cmd)
        maybe_append('--no-heuristic', self.no_heuristic, cmd)

        if not self.no_stdlib:
            cmd.append('-p')
            cmd.append('libpsychecstd')

        ok = execute(PsycheFacade._id, cmd)
        if ok != 0:
            sys.exit(
                DiagnosticReporter.fatal(CONSTRAINT_GENERATION_FOR_FILE_FAILED,
                                         unit.c_file_path))
Example #7
0
def copy_file(src_path, dst_path):
    try:
        shutil.copyfile(src_path, dst_path)
    except:
        sys.exit(
            DiagnosticReporter.fatal(EXCEPTION_COPYING_FILE_PATH, src_path,
                                     dst_path))
Example #8
0
    def generate_constraints(self, unit: Unit, cc_cmd_summary):
        """
        Generate constraints for a unit.
        """

        cmd = [
            PsycheCFacade._GENERATOR, unit.c_file, '-o', unit.cstr_file,
            '--cc', self.cc, '--cc-std', cc_cmd_summary.c_version
        ]

        cmd += CCompilerFacade.defined_macros('--cc-D')
        cmd += CCompilerFacade.undefined_macros('--cc-U')

        cmd += cc_cmd_summary.defined_macros('-cc-D ')
        cmd += cc_cmd_summary.undefined_macros('--cc-U ')
        cmd += cc_cmd_summary.include_paths('--cc-I ')

        maybe_append('--no-typedef', self.no_typedef, cmd)
        maybe_append('--no-heuristic', self.no_heuristic, cmd)

        if not self.no_stdlib:
            cmd.append('-p')
            dir_path = pathlib.Path(__file__).parent.parent.absolute()
            cmd.append(os.path.join(dir_path, 'libpsychecstd'))

        code = execute(PsycheCFacade.ID(), cmd)
        if code != 0:
            sys.exit(
                DiagnosticReporter.fatal(CONSTRAINT_GENERATION_FOR_FILE_FAILED,
                                         unit.c_file,
                                         error=code))
Example #9
0
 def _check_line(line):
     """
     Check the line format.
     """
     parts = line.split(':')
     if len(parts) != 2:
         sys.exit(DiagnosticReporter.fatal(CORRUPTED_LICENSE_FILE))
     return parts[1]
Example #10
0
def concat_file(src_path, dst_path):
    with open(dst_path, 'ab') as dst:
        with open(src_path, 'rb') as src:
            try:
                shutil.copyfileobj(src, dst)
            except:
                sys.exit(
                    DiagnosticReporter.fatal(EXCEPTION_COPYING_FILE_OBJECT,
                                             src_path, dst_path))
Example #11
0
def execute(parent, cmd, *args, **kwargs):
    """
    Execute an external process with the given command.
    """

    trace_extern_cmd(parent, flatten(cmd))
    try:
        return subprocess.call(cmd, *args, **kwargs)
    except:
        sys.exit(DiagnosticReporter.fatal(EXCEPTION_EXECUTING_PROCESS, cmd[0]))
Example #12
0
    def collect(self):
        expect_out_file = False
        for v in self.cmd:
            # TODO: Deal vith -E... Do nothing?

            if v.startswith("-std="):
                self.c_version = v[5:]
            if v == "-ansi":
                self.c_version = "c90"

            if v.endswith('.c'):
                self.c_files.append(v)
                continue

            if v.startswith('-D'):
                self.D_lst.append(v[2:].strip())
                continue

            if v.startswith('-U'):
                self.U_lst.append(v[2:].strip())
                continue

            if v.startswith('-I'):
                self.I_lst.append(v[2:].strip())
                continue

            if v == "-pedantic-errors":
                self.pedantic = True

            # Keep track of output file, if specified.
            if expect_out_file:
                self.out_file_name = v
                expect_out_file = False
            if v == "-o":
                expect_out_file = True

        # Temporary
        if self.c_version != 'c99':
            DiagnosticReporter.warning(C_VERSION_NOT_SUPPORTED)
            self.c_version = 'c99'

        return self
Example #13
0
    def git_sha():
        """
        Get git HEAD's sha.
        """

        cmd = ['git', 'rev-parse', 'HEAD']
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        out, err = process.communicate()
        if err:
            sys.exit(DiagnosticReporter.fatal(ERROR_FETCHING_GIT_SHA))
        return out[:7]
Example #14
0
def execute(parent, cmd, *args, **kwargs):
    """
    Execute an external process with the given command.
    """

    with xtrace(parent, flatten(cmd)) as h:
        try:
            code = subprocess.call(cmd, *args, **kwargs)
        except:
            sys.exit(
                DiagnosticReporter.fatal(EXCEPTION_EXECUTING_PROCESS, cmd[0]))
        finally:
            h.report(code)
    return code
    def preprocess(self, c_file_name, pp_file_name):
        """
        Preprocess the file.
        """

        cmd = [self.host_cc, '-E', '-x', 'c', c_file_name, '-o', pp_file_name]

        cmd += CCompilerFacade.predefined_macros('-D')
        cmd += CCompilerFacade.undefined_macros('-U')

        ok = execute(CCompilerFacade._id, cmd)
        if ok != 0:
            sys.exit(
                DiagnosticReporter.fatal(PREPROCESSING_FILE_FAILED,
                                         c_file_name))
Example #16
0
    def _ensure_config_dir_exists(self):
        """
        Ensure that the application directory exists.
        """

        if not os.path.isdir(self.config_dir_path):
            debug(EnvironmentController._id,
                     'create config directory in %s' % self.home_dir_path)
            try:
                os.makedirs(self.config_dir_path)
            except OSError:
                # Check again due to concurrent access.
                if not os.path.isdir(self.config_dir_path):
                    sys.exit(
                        DiagnosticReporter.fatal(ERROR_CREATING_CONFIG_DIRECTORY))
Example #17
0
    def solve_constraints(self, unit: Unit):
        """
        Solve the constraint.
        """

        cmd = [
            PsycheCFacade._SOLVER, '--', '-i', unit.cstr_file, '-o',
            unit.cnip_file
        ]

        if not self.no_stdlib:
            cmd.append('--match-stdlib=approx')

        ok = execute(PsycheCFacade.ID(), cmd)
        if ok != 0:
            sys.exit(
                DiagnosticReporter.fatal(CONSTRAINT_SOLVING_FOR_FILE_FAILED,
                                         unit.c_file))
Example #18
0
    def preprocess(self, c_file_name, pp_file_name):
        """
        Preprocess the file.
        """

        cmd = [self.cc,
               '-E',
               '-x',
               'c',
               c_file_name,
               '-o',
               pp_file_name]

        cmd += CCompilerFacade.defined_macros('-D')
        cmd += CCompilerFacade.undefined_macros('-U')

        cmd += self.original_options()

        code = execute(CCompilerFacade.ID(), cmd)
        if code != 0:
            sys.exit(
                DiagnosticReporter.fatal(PREPROCESSING_FILE_FAILED,
                                         c_file_name))