Skip to contentSkip to conversation

pycocci: index opts, SmPL patch proof support

PATCH Superseded Luis R. Rodriguez 2 participants 14 messages Jul 18, 2015 – Jul 20, 2015

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

v2 cover pycocci: index opts, SmPL patch proof support

From: "Luis R. Rodriguez" <[email protected]>

This v2 changes the way we do git tree inference by using git rev-parse. While at it, I decided to mesh in SmPL <--> patch equivalence proof support. This is a generalized solution, I originally had written for the backports project, we now give this instead a proper home and purpose under pycocci.

If there are no issues I'll merge this soon, in hopes it will make it for the coccinelle 1.0.2 release.

Luis R. Rodriguez (4):
pycocci: add requirements class
pycocci: add git class
pycocci: figure out if to enable --jobs, --use-gitgrep or
--use-glimpse
pycocci: add Coccinelle SmPL patch proof support

 tools/pycocci | 475 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 462 insertions(+), 13 deletions(-)
Signature · 1 line
2.3.2.209.gd67f9d5.dirty
#1 lore raw

PATCH v2 1/4 pycocci: add requirements class

This will be used later to help examine different tools requirements. For instance, this will be used to fine tune spatch operation depending on the version of spatch you have. Later we'll also use this to add support for SmPL patch equivalence proof support.

This introduces has no functional changes.

---
 tools/pycocci | 204 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 203 insertions(+), 1 deletion(-)
tools/pycocci +203 -1
index 4aa1d3638347..5a11e5c770c7 100755
@@ -10,9 +10,211 @@
 # defaults, specifically for kernel developers.
 
 from multiprocessing import Process, cpu_count, Queue
-import argparse, subprocess, os, sys
+import argparse, subprocess, os, sys, re
 import tempfile, shutil
 
+class ReqError(Exception):
+    pass
+class ExecutionError(ReqError):
+    def __init__(self, errcode):
+        self.error_code = errcode
+
+class Req:
+    "To be used for verifying binay package dependencies on Python code"
+    def __init__(self, chatty=True):
+        self.all_reqs_ok = True
+        self.debug = False
+        self.chatty = chatty
+    def logwrite(self, msg):
+        if self.chatty:
+            sys.stdout.write(msg)
+            sys.stdout.flush()
+    def enable_debug(self):
+        self.debug = True
+    def reqs_match(self):
+        if self.all_reqs_ok:
+            return True
+        self.logwrite("You have unfulfilled binary requirements\n")
+        return False
+    def req_missing(self, program):
+        self.all_reqs_ok = False
+        self.logwrite("You need to have installed: %s\n" % program)
+    def req_old_program(self, program, version_req):
+        self.all_reqs_ok = False
+        self.logwrite("You need to have installed: %s >= %s\n" % (program, version_req))
+    def which(self, program):
+        cmd = ['which', program]
+        process = subprocess.Popen(cmd,
+                                   stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                                   close_fds=True, universal_newlines=True)
+        stdout = process.communicate()[0]
+        process.wait()
+        if process.returncode != 0:
+            raise ExecutionError(process.returncode)
+        return stdout
+    def req_exists(self, program):
+        cmd = ['which', program]
+        process = subprocess.Popen(cmd,
+                                   stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                                   close_fds=True, universal_newlines=True)
+        stdout = process.communicate()[0]
+        process.wait()
+        if process.returncode == 0:
+            return True
+        return False
+    def req_get_prog_version(self, program, version_query, version_pos):
+        '''
+        Suppose you have a binary that outputs:
+        $ spatch --version
+        spatch version 1.0.0-rc21 with Python support and with PCRE support
+
+        Every program veries what it wants you to query it for a version string,
+        prog_version() is designed so that you pass what the program expects for
+        its version query, and the position you expect the version string to be
+        on using python list.
+        '''
+        cmd = [program, version_query]
+        process = subprocess.Popen(cmd,
+                                   stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                                   close_fds=True, universal_newlines=True)
+        stdout = process.communicate()[0]
+        process.wait()
+        if process.returncode != 0:
+            raise ExecutionError(process.returncode)
+        if self.debug:
+            sys.stdout.write("Running '%s' got us this break down:\n%s\n" %
+                             (
+                             ' '.join(cmd),
+                             "\n".join(map(str, [[i, x] for i, x in enumerate(stdout.split())])),
+                             ))
+            sys.stdout.write("You are using for version: %s\n" % stdout.split()[version_pos])
+            sys.stdout.write("Specifically your idx, element: %s\n" % ([[i, x] for i, x in enumerate(stdout.split())][version_pos]))
+        return stdout.split()[version_pos]
+
+    MAX_RC = 25
+    def __compute_rel_weight(self, rel_specs):
+        weight = 0
+        extra = 0
+        sublevel = 0
+        relmod = 0
+
+        if self.debug:
+            sys.stdout.write("VERSION       = %s\n" % rel_specs['VERSION'])
+            sys.stdout.write("PATCHLEVEL    = %s\n" % rel_specs['PATCHLEVEL'])
+            sys.stdout.write("SUBLEVEL      = %s\n" % rel_specs['SUBLEVEL'])
+            sys.stdout.write("EXTRAVERSION  = %s\n" % rel_specs['EXTRAVERSION'])
+            sys.stdout.write("RELMOD_UPDATE = %s\n" % rel_specs['RELMOD_UPDATE'])
+
+        if rel_specs['EXTRAVERSION'] != '':
+            if ("." in rel_specs['EXTRAVERSION'] or
+                    "rc" in rel_specs['EXTRAVERSION']):
+                rc = rel_specs['EXTRAVERSION'].lstrip("-rc")
+                if (rc == ""):
+                    rc = 0
+                else:
+                    rc = int(rc) - (Req.MAX_RC + 1)
+                extra = int(rc)
+            else:
+                extra = int(rel_specs['EXTRAVERSION']) + 10
+
+        if rel_specs['SUBLEVEL'] != '':
+            sublevel = int(rel_specs['SUBLEVEL'].lstrip(".")) * 20
+        else:
+            sublevel = 5
+
+        if rel_specs['RELMOD_UPDATE'] != '':
+            mod = rel_specs['RELMOD_UPDATE']
+            if (mod == ""):
+                mod = 0
+            else:
+                mod = int(mod)
+            relmod = int(mod)
+
+        weight = (int(rel_specs['VERSION'])    << 32) + \
+                 (int(rel_specs['PATCHLEVEL']) << 16) + \
+                 (sublevel   		       << 8 ) + \
+                 (extra * 60) + (relmod * 2)
+
+        return weight
+    def req_get_rel_spec(self, rel):
+        if "rc" in rel:
+            m = re.match(r"v*(?P<VERSION>\d+)\.+"
+                         "(?P<PATCHLEVEL>\d+)[.]*"
+                         "(?P<SUBLEVEL>\d*)"
+                         "(?P<EXTRAVERSION>[-rc]+\w*)\-*"
+                         "(?P<RELMOD_UPDATE>\d*)[-]*",
+                         rel)
+        else:
+            m = re.match(r"v*(?P<VERSION>\d+)\.+"
+                         "(?P<PATCHLEVEL>\d+)[.]*"
+                         "(?P<SUBLEVEL>\d*)[.]*"
+                         "(?P<EXTRAVERSION>\w*)\-*"
+                         "(?P<RELMOD_UPDATE>\d*)[-]*",
+                         rel)
+        if not m:
+            return m
+        rel_specs = m.groupdict()
+        return rel_specs
+    def compute_rel_weight(self, rel):
+        rel_specs = self.req_get_rel_spec(rel)
+        if not rel_specs:
+            return 0
+        return self.__compute_rel_weight(rel_specs)
+    def linux_version_cmp(self, version_req, version):
+        '''
+        If the program follows the linux version style scheme you can
+        use this to compare versions.
+        '''
+        weight_has = self.compute_rel_weight(version)
+        weight_req = self.compute_rel_weight(version_req)
+
+        if self.debug:
+            sys.stdout.write("You have program weight: %s\n" % weight_has)
+            sys.stdout.write("Required program weight: %s\n" % weight_req)
+
+        if weight_has < weight_req:
+            return -1
+        return 0
+    def require_version(self, program, version_query, version_req, version_pos, version_cmp):
+        '''
+        If you have a program version requirement you can specify it here,
+        as for the other flags refer to prog_version.
+        '''
+        if not self.require(program):
+            return False
+        version = self.req_get_prog_version(program, version_query, version_pos)
+        if self.debug:
+            sys.stdout.write("Checking release specs and weight: for: %s\n" % program)
+            sys.stdout.write("You have version: %s\n" % version)
+            sys.stdout.write("Required version: %s\n" % version_req)
+        if version_cmp(version_req, version) != 0:
+            self.req_old_program(program, version_req)
+            return False
+        return True
+    def require(self, program):
+        if self.req_exists(program):
+            return True
+        self.req_missing(program)
+        return False
+    def require_hint(self, program, package_hint):
+        if self.require(program):
+            return True
+        sys.stdout.write("Try installing the package: %s\n" % package_hint)
+        return False
+    def coccinelle(self, version):
+        if self.require_version('spatch', '--version', version, 2, self.linux_version_cmp):
+            return True
+        self.logwrite("Try installing the package: coccinelle\n")
+        self.logwrite("If that is too old go grab the code from source:\n\n")
+        self.logwrite("git clone https://github.com/coccinelle/coccinelle.git\n\n")
+        self.logwrite("To build you will need: ocaml ncurses-devel\n\n")
+        self.logwrite("If on SUSE / OpenSUSE you will also need: ocaml-ocamldoc\n\n")
+        return False
+    def make(self, version):
+        return self.require_version('make', '--version', version, 2, self.linux_version_cmp)
+    def gcc(self, version):
+        return self.require_version('gcc', '--version', version, 3, self.linux_version_cmp)
+
 # simple tempdir wrapper object for 'with' statement
 #
 # Usage:
Signature · 1 line
2.3.2.209.gd67f9d5.dirty
#2 lore raw

PATCH v2 2/4 pycocci: add git class

In reply to Luis R. Rodriguez

From: "Luis R. Rodriguez" <[email protected]>

This will let us check and use git for both inference of whether or not --use-gitgrep is needed later, and also for SmPL patch equivalence proof support later.

---
 tools/pycocci | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 80 insertions(+)
tools/pycocci +80 -0
index 5a11e5c770c7..141f9783d09b 100755
@@ -215,6 +215,86 @@ class Req:
     def gcc(self, version):
         return self.require_version('gcc', '--version', version, 3, self.linux_version_cmp)
 
+class GitError(Exception):
+    pass
+class ExecutionGitError(GitError):
+    def __init__(self, errcode):
+        self.error_code = errcode
+
+def _check(process):
+    if process.returncode != 0:
+        raise ExecutionError(process.returncode)
+
+def git_init(tree=None):
+    process = subprocess.Popen(['git', 'init'],
+                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                               close_fds=True, universal_newlines=True, cwd=tree)
+    stdout = process.communicate()[0]
+    process.wait()
+    _check(process)
+
+def git_rev_parse(tree=None, extra_args=None):
+    cmd = ['git', 'rev-parse' ] + extra_args
+    process = subprocess.Popen(cmd,
+                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                               close_fds=True, universal_newlines=True, cwd=tree)
+    stdout = process.communicate()[0]
+    process.wait()
+    if process.returncode != 0:
+        return None
+    return stdout.split('\n', 1)[0]
+
+def gitname(path=None):
+    work_dir = path
+    if not os.path.isdir(path):
+        work_dir = os.path.dirname(path)
+    process = subprocess.Popen(['git', 'rev-parse', '--show-toplevel', path],
+                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                               close_fds=True, universal_newlines=True, cwd=work_dir)
+    stdout = process.communicate()[0]
+    process.wait()
+    if process.returncode != 0:
+        return None
+    return stdout.split('\n', 1)[0]
+
+def git_add(path, tree=None):
+    process = subprocess.Popen(['git', 'add', '--ignore-removal', path],
+                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                               close_fds=True, universal_newlines=True, cwd=tree)
+    stdout = process.communicate()[0]
+    process.wait()
+    _check(process)
+
+def git_checkout(tree=None, extra_args=None):
+    cmd = ['git', 'checkout' ] + extra_args
+    process = subprocess.Popen(cmd,
+                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                               close_fds=True, universal_newlines=True, cwd=tree)
+    stdout = process.communicate()[0]
+    process.wait()
+    _check(process)
+
+def git_commit_all(message, tree=None):
+    git_add('.', tree=tree)
+    process = subprocess.Popen(['git', 'commit', '--allow-empty', '-a', '-m', message],
+                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                               close_fds=True, universal_newlines=True, cwd=tree)
+    stdout = process.communicate()[0]
+    process.wait()
+    _check(process)
+
+def git_diff(tree=None, extra_args=None):
+    cmd = ['git', 'diff', '--color=always'] + extra_args
+
+    process = subprocess.Popen(cmd,
+                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                               close_fds=True, universal_newlines=True, cwd=tree)
+    stdout = process.communicate()[0]
+    process.wait()
+    _check(process)
+
+    return stdout
+
 # simple tempdir wrapper object for 'with' statement
 #
 # Usage:
Signature · 1 line
2.3.2.209.gd67f9d5.dirty
#3 lore raw

PATCH v2 3/4 pycocci: figure out if to enable --jobs, --use-gitgrep or --use-glimpse

In reply to Luis R. Rodriguez

pycocci was originally written to set sensible defaults for doing development with Coccinelle with a git tree and to also add parallelism wrapper support. Coccinelle now has a '--jobs' argument which does the same but it works better. This feature is available as of 1.0.0 but will have some fixes which will go in on 1.0.2.

Likewise the 1.0.1 release has --use-gitgrep support which works better than --use-coccigrep. An old feature that has been in place for a long time is --use-glimpse, and since we have that code released now as open source we should provide support for it as its expected we'd get the best results with it. The glimpse code still needs a bit of work, as the public releases doesn't yet build correctly, but nevertheless we should support it as glimpse is now open sourced under the ISC license.

Instead of removing the old built-in wrapper for parallelism support lets keep it and instead check the version of coccinelle you have and let pycocci figure out what options you need.

Pycocci will also investingate your work area and determine if your path is part of a git tree or not. That is, you can provide a target path say drivers/net/tun.c and pycocci will be smart enough to know that two levels below a .git directory exists. This also works with directories. It does this by recursing each subdirectory and if it finds a .git then checking if the target is part of the git tree. The check in place for this is implemented as gitname(), upon investingating git code setup_git_directory_gently() is the shortest possible path to determine if a path is part of a git tree, and respectively git rev-parse the easiest tool we can use to infer this from a given path. Something similar is not implemented but can be done for glimpse. This is not a priority however as glimpse can't even build yet as-is with the new public release of code.

If all index options fail to check out we resort to --use-coccigrep as the last-resort default.

---
 tools/pycocci | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++--------
 1 file changed, 85 insertions(+), 12 deletions(-)
tools/pycocci +85 -12
index 141f9783d09b..51d89f618add 100755
@@ -346,14 +346,57 @@ class ExecutionErrorThread(CoccinelleError):
             tf.close()
             os.unlink(fn)
 
-def spatch(cocci_file, outdir,
-           max_threads, thread_id, temp_dir, ret_q, extra_args=[]):
+class ExecutionErrorCocci(CoccinelleError):
+    def __init__(self, errcode, output, cocci_file, logwrite, print_name):
+        self.error_code = errcode
+        logwrite("Failed to apply changes from %s\n" % print_name)
+        logwrite(output)
+
+def spatch(cocci_file, outdir, logwrite, num_jobs, print_name, extra_args=[]):
+
+    req = Req(chatty=True)
+    req.coccinelle('1.0.2')
+
+    if not req.reqs_match():
+        sys.exit(1)
+
+    num_cpus = cpu_count()
+    if num_jobs:
+        threads = int(num_jobs)
+    else:
+        threads = num_cpus
+
+    cmd = ['spatch',
+            '--sp-file', cocci_file,
+            '--in-place',
+            '--recursive-includes',
+            '--relax-include-path',
+            '--timeout', '120',
+            '--dir', outdir ]
+
+    if (threads > 1):
+            cmd.extend(['--jobs', str(threads)])
+
+    cmd.extend(extra_args)
+
+    logwrite("%s\n" % " ".join(cmd))
+
+    sprocess = subprocess.Popen(cmd,
+                                stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+                                close_fds=True, universal_newlines=True)
+    output = sprocess.communicate()[0]
+    sprocess.wait()
+    if sprocess.returncode != 0:
+        raise ExecutionErrorCocci(sprocess.returncode, output, cocci_file, logwrite, print_name)
+    return output
+
+def spatch_old(cocci_file, outdir,
+               max_threads, thread_id, temp_dir, ret_q, extra_args=[]):
     cmd = ['spatch',
             '--sp-file', cocci_file,
             '--in-place',
             '--recursive-includes',
             '--relax-include-path',
-            '--use-coccigrep',
             '--timeout', '120',
             '--dir', outdir ]
 
@@ -385,9 +428,9 @@ def threaded_spatch(cocci_file, outdir, logwrite, num_jobs,
     ret_q = Queue()
     with tempdir() as t:
         for num in range(threads):
-            p = Process(target=spatch, args=(cocci_file, outdir,
-                                             threads, num, t, ret_q,
-                                             extra_args))
+            p = Process(target=spatch_old, args=(cocci_file, outdir,
+                                                 threads, num, t, ret_q,
+                                                 extra_args))
             jobs.append(p)
         for p in jobs:
             p.start()
@@ -440,12 +483,42 @@ def _main():
     if args.jobs > 0:
         jobs = args.jobs
 
-    output = threaded_spatch(args.cocci_file,
-                             args.target_dir,
-                             logwrite,
-                             jobs,
-                             os.path.basename(args.cocci_file),
-                             extra_args=extra_spatch_args)
+    has_spatch_1_0_1 = Req(chatty=False)
+    has_spatch_1_0_1.coccinelle('1.0.1')
+
+    has_spatch_1_0_2 = Req(chatty=False)
+    has_spatch_1_0_2.coccinelle('1.0.2')
+
+    git_reqs = Req(chatty=False)
+    git_reqs.require('git')
+
+    glimpse_index = os.path.abspath(os.path.join(args.target_dir, '.glimpse_index'))
+    git_dir = None
+
+    if git_reqs.reqs_match():
+        git_dir = gitname(args.target_dir)
+
+    if os.path.isfile(glimpse_index):
+       extra_spatch_args.append('--use-glimpse')
+    elif git_dir:
+        if has_spatch_1_0_1.reqs_match():
+            extra_spatch_args.append('--use-gitgrep')
+        else:
+            extra_spatch_args.append('--use-coccigrep')
+    else:
+        extra_spatch_args.append('--use-coccigrep')
+
+    if has_spatch_1_0_2.reqs_match():
+        output = spatch(args.cocci_file, args.target_dir, logwrite, jobs,
+                        os.path.basename(args.cocci_file),
+                        extra_args=extra_spatch_args)
+    else:
+        output = threaded_spatch(args.cocci_file,
+                                 args.target_dir,
+                                 logwrite,
+                                 jobs,
+                                 os.path.basename(args.cocci_file),
+                                 extra_args=extra_spatch_args)
     if args.verbose:
         logwrite(output)
     return 0
Signature · 1 line
2.3.2.209.gd67f9d5.dirty
#4 lore raw

PATCH v2 4/4 pycocci: add Coccinelle SmPL patch proof support

In reply to Luis R. Rodriguez

From: "Luis R. Rodriguez" <[email protected]>

At times you may need to replace a patch series with an SmPL patch, but how can you grow certain that a patch series replaces that patch series perfectly ? How do you visualize such differences ?

This provides support for such proof mechanism. It assumes you have a patch series and respective SmPL patch you wish to use to replace the patch series. Say you have a foo.cocci SmPL patch, you would also have a foo/ directory in which you have series of patches. The foo/ patches are the patches you wish to replace.

You can use then for instance:

  pycocci --show-proof foo.cocci /path/some-src-tree/

If you don't have git yet set up on /path/some-src-tree/ we'll create a git repository for you there with the code there in place already as the base of the repository. Otherwise if you already have git set up we'll use that git tree to do work.

pycocci will create two git branches for proving the work. We leave your original branch intact, whatever it was, and we'll return you back to that same git branch.

As an example, you may end up with:

Current branch: master
Patch branch: pycocci-patch-dd6b2fa4
SmPL branch: pycocci-smpl-731f9863

A series of patches in the directory foo/ will be applied onto the pycocci-patch-dd6b2fa4 branch, the foo.cocci SmPL patch will be applied onto the pycocci-smpl-731f9863 branch.

You get a perfect patch equivalence when:

git diff pycocci-patch-dd6b2fa4..pycocci-smpl-731f9863

yields no results. If there is any delta we give you the diffstat through stdout, and tell you where to go and what to do (above command) to inspect the changes in detail.

Below is a screenshot run:

mcgrof at ergon ~ $ /home/mcgrof/devel/coccinelle/tools/pycocci \
	--show-proof \
	/home/mcgrof/backports/patches/collateral-evolutions/media/0002-no_dmabuf.cocci \
	/home/mcgrof/build/backports-20150626-test

Current branch: master
Patch branch: pycocci-patch-3a9fc1a5
SmPL branch: pycocci-smpl-17d08bf3

Applying patch ...0002-no_dmabuf/v4l2.patch

spatch --sp-file ...0002-no_dmabuf.cocci --in-place --recursive-includes --relax-include-path --timeout 120 --dir ...backports-20150626-test -max 4 -index 0 --use-coccigrep spatch --sp-file ...0002-no_dmabuf.cocci --in-place --recursive-includes --relax-include-path --timeout 120 --dir ...backports-20150626-test -max 4 -index 1 --use-coccigrep spatch --sp-file ...0002-no_dmabuf.cocci --in-place --recursive-includes --relax-include-path --timeout 120 --dir ...backports-20150626-test -max 4 -index 2 --use-coccigrep spatch --sp-file ...0002-no_dmabuf.cocci --in-place --recursive-includes --relax-include-path --timeout 120 --dir ...backports-20150626-test -max 4 -index 3 --use-coccigrep

Differences found:

Change directory to /home/mcgrof/build/backports-20150626-test and run:

        git diff pycocci-patch-3a9fc1a5..pycocci-smpl-17d08bf3

diffstat of the changes:

 drivers/media/pci/cobalt/cobalt-v4l2.c         |  2 ++
 drivers/media/platform/blackfin/bfin_capture.c |  2 ++
 drivers/media/platform/exynos-gsc/gsc-m2m.c    |  4 +++
 drivers/media/platform/s5p-mfc/s5p_mfc_dec.c   |  4 +++
 drivers/media/platform/s5p-mfc/s5p_mfc_enc.c   |  4 +++
 drivers/media/platform/s5p-tv/mixer_video.c    |  4 +++
 drivers/media/platform/soc_camera/soc_camera.c |  4 +++
 drivers/media/platform/sti/bdisp/bdisp-v4l2.c  |  2 ++
 drivers/media/usb/uvc/uvc_queue.c              |  2 --
 drivers/media/usb/uvc/uvc_v4l2.c               |  2 +-
 drivers/media/v4l2-core/Kconfig                |  6 ++--
 drivers/media/v4l2-core/v4l2-mem2mem.c         |  4 ---
 drivers/media/v4l2-core/videobuf2-core.c       | 20 ------------
 drivers/media/v4l2-core/videobuf2-dma-contig.c | 34 ++++++++++++++++++--
 drivers/media/v4l2-core/videobuf2-dma-sg.c     | 38 +++++++++++++++++++++--
 drivers/media/v4l2-core/videobuf2-vmalloc.c    | 43 +++++++++++++++++++++++---
 include/media/v4l2-mem2mem.h                   |  4 ---
 include/media/videobuf2-core.h                 |  8 -----
 18 files changed, 134 insertions(+), 53 deletions(-)
---
 tools/pycocci | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 94 insertions(+)
tools/pycocci +94 -0
index 51d89f618add..18d72abc369b 100755
@@ -12,6 +12,7 @@
 from multiprocessing import Process, cpu_count, Queue
 import argparse, subprocess, os, sys, re
 import tempfile, shutil
+import uuid
 
 class ReqError(Exception):
     pass
@@ -321,6 +322,44 @@ class tempdir(object):
         else:
             shutil.rmtree(self._name)
 
+def apply_patches(args, patch_src, target_dir, logwrite=lambda x:None):
+    """
+    Given a path of a directories of patches apply the patches
+    """
+    patches = []
+    for root, dirs, files in os.walk(patch_src):
+        for f in files:
+            if f.endswith('.patch'):
+                    patches.append(os.path.join(root, f))
+    patches.sort()
+    prefix_len = len(patch_src) + 1
+    for pfile in patches:
+        print_name = pfile[prefix_len:]
+
+        logwrite("Applying patch %s\n" % pfile)
+
+        process = subprocess.Popen(['patch', '-p1'], stdout=subprocess.PIPE,
+                                   stderr=subprocess.STDOUT, stdin=subprocess.PIPE,
+                                   close_fds=True, universal_newlines=True,
+                                   cwd=target_dir)
+        output = process.communicate(input=open(pfile, 'r').read())[0]
+        output = output.split('\n')
+        if output[-1] == '':
+            output = output[:-1]
+        if process.returncode != 0:
+            if not args.verbose:
+                logwrite("Failed to apply changes from %s" % print_name)
+                for line in output:
+                    logwrite('> %s' % line)
+            raise Exception('Patch failed')
+
+        # remove orig/rej files that patch sometimes creates
+        for root, dirs, files in os.walk(target_dir):
+            for f in files:
+                if f[-5:] == '.orig' or f[-4:] == '.rej':
+                    os.unlink(os.path.join(root, f))
+        git_commit_all(tree=target_dir, message="apply patch %s" % (print_name))
+
 class CoccinelleError(Exception):
     pass
 
@@ -465,6 +504,8 @@ def _main():
                         help='Target source directory to modify')
     parser.add_argument('-p', '--profile-cocci', const=True, default=False, action="store_const",
                         help='Enable profile, this will pass --profile  to Coccinelle.')
+    parser.add_argument('-s', '--show-proof', const=True, default=False, action="store_const",
+                        help='Show proof that the provided SmPL patch can replace a respective patch series')
     parser.add_argument('-j', '--jobs', metavar='<jobs>', type=str, default=None,
                         help='Only use the cocci file passed for Coccinelle, don\'t do anything else, ' +
                         'also creates a git repo on the target directory for easy inspection ' +
@@ -475,6 +516,13 @@ def _main():
 
     if not os.path.isfile(args.cocci_file):
         return -2
+    if not os.path.isfile(args.target_dir) and not os.path.isdir(args.target_dir):
+        logwrite("Path (%s) is not a file or directory\n" % (args.target_dir))
+        return -2
+
+    current_branch = None
+    smpl_branch_name = "pycocci-smpl-" + str(uuid.uuid4())[:8]
+    patch_branch_name = "pycocci-patch-" + str(uuid.uuid4())[:8]
 
     extra_spatch_args = []
     if args.profile_cocci:
@@ -498,6 +546,40 @@ def _main():
     if git_reqs.reqs_match():
         git_dir = gitname(args.target_dir)
 
+    if args.show_proof:
+        # As an example if you use --show-proof patches/collateral-evolutions/network/09-threaded-irq.cocci
+        # the patches under 09-threaded-irq will be used for the proof.
+        patch_src = args.cocci_file.split('/')[-1].split('.cocci')[0]
+        dirname = os.path.dirname(args.cocci_file)
+        patch_src = os.path.abspath(os.path.join(dirname, patch_src))
+        if not os.path.isdir(patch_src):
+            logwrite("Path given (%s) must be a directory with patches\n" % (patch_src))
+            return -2
+        git_reqs = Req(chatty=True)
+        git_reqs.require('git')
+        if not git_dir:
+            if os.path.isfile(args.target_dir):
+                logwrite("Path given (%s) is a file, try passing the directory "
+                         "(%s) if you are certain you want us to create a git repo to provide a"
+                         "a proof there\n" % (args.target_dir, os.path.dirname(args.target_dir)))
+                return -2
+            logwrite("Path (%s) not part of a git tree, creating one for you...\n" % (args.target_dir))
+            git_init(tree=args.target_dir)
+            git_commit_all(tree=args.target_dir, message="Initial commit")
+        cmd = [ '--abbrev-ref', 'HEAD' ]
+        current_branch = git_rev_parse(tree=args.target_dir, extra_args = cmd)
+        logwrite("\n")
+        logwrite("Current branch: %s\n" % (current_branch))
+        logwrite("Patch   branch: %s\n" % (patch_branch_name))
+        logwrite("SmPL    branch: %s\n" % (smpl_branch_name))
+        logwrite("\n")
+        git_checkout(tree=args.target_dir, extra_args = ['-b', smpl_branch_name])
+        git_checkout(tree=args.target_dir, extra_args = ['-b', patch_branch_name])
+
+        apply_patches(args, patch_src, args.target_dir, logwrite)
+
+        git_checkout(tree=args.target_dir, extra_args = [smpl_branch_name])
+
     if os.path.isfile(glimpse_index):
        extra_spatch_args.append('--use-glimpse')
     elif git_dir:
@@ -521,6 +603,18 @@ def _main():
                                  extra_args=extra_spatch_args)
     if args.verbose:
         logwrite(output)
+    if args.show_proof:
+        git_commit_all(tree=args.target_dir, message="Initial commit")
+        git_checkout(tree=args.target_dir, extra_args = [current_branch])
+        cmd = [ '--stat', patch_branch_name + ".." + smpl_branch_name ]
+        diff_stat = git_diff(tree=args.target_dir, extra_args = cmd)
+        if len(diff_stat) == 0:
+            logwrite('\nSmPL patch fully replaces patch series!')
+        else:
+            logwrite('\nDifferences found:\n\n')
+            logwrite('Change directory to %s and run:\n\n\tgit diff %s..%s\n\n' % (args.target_dir, patch_branch_name, smpl_branch_name))
+            logwrite('diffstat of the changes:\n')
+            logwrite(diff_stat)
     return 0
 
 if __name__ == '__main__':
Signature · 1 line
2.3.2.209.gd67f9d5.dirty
#5 lore raw
In reply to Luis R. Rodriguez
Quoted 8 lines · Luis R. Rodriguez

From: "Luis R. Rodriguez" <[email protected]>

This v2 changes the way we do git tree inference by using git rev-parse. While at it, I decided to mesh in SmPL <--> patch equivalence proof support. This is a generalized solution, I originally had written for the backports project, we now give this instead a proper home and purpose under pycocci.

Quoted 8 lines

If there are no issues I'll merge this soon, in hopes it will make it for the coccinelle 1.0.2 release.

Luis R. Rodriguez (4):
pycocci: add requirements class
pycocci: add git class
pycocci: figure out if to enable --jobs, --use-gitgrep or
--use-glimpse

Do you need patches 2 and 3?

julia

Quoted 13 lines

pycocci: add Coccinelle SmPL patch proof support

 tools/pycocci | 475 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 462 insertions(+), 13 deletions(-)
Signature · 6 lines
2.3.2.209.gd67f9d5.dirty

_______________________________________________
Cocci mailing list
Cocci at systeme.lip6.fr
https://systeme.lip6.fr/mailman/listinfo/cocci
#6 lore raw
Quoted 14 lines · Julia Lawall
Quoted 11 lines · Luis R. Rodriguez

From: "Luis R. Rodriguez" <[email protected]>

This v2 changes the way we do git tree inference by using git rev-parse. While at it, I decided to mesh in SmPL <--> patch equivalence proof support. This is a generalized solution, I originally had written for the backports project, we now give this instead a proper home and purpose under pycocci.

If there are no issues I'll merge this soon, in hopes it will make it for the coccinelle 1.0.2 release.

Quoted 7 lines
Quoted 5 lines

Luis R. Rodriguez (4):
pycocci: add requirements class
pycocci: add git class
pycocci: figure out if to enable --jobs, --use-gitgrep or
--use-glimpse

Do you need patches 2 and 3?

Do you mean I should squash them together, or something else ?

Luis

Quoted 5 lines

julia

Quoted 3 lines

pycocci: add Coccinelle SmPL patch proof support

 tools/pycocci | 475

++++++++++++++++++++++++++++++++++++++++++++++++++++++++--

Quoted 10 lines
Quoted 10 lines
 1 file changed, 462 insertions(+), 13 deletions(-)

--
2.3.2.209.gd67f9d5.dirty

_______________________________________________
Cocci mailing list
[email protected]
https://systeme.lip6.fr/mailman/listinfo/cocci

#7 lore raw
Quoted 23 lines · Luis R. Rodriguez
Quoted 20 lines · Julia Lawall
Quoted 16 lines · Luis R. Rodriguez

From: "Luis R. Rodriguez" <[email protected]>

This v2 changes the way we do git tree inference by using git rev-parse. While at it, I decided to mesh in SmPL? <--> patch equivalence proof support. This is a generalized solution, I originally had written for the backports project, we now give this instead a proper home and purpose under pycocci.

If there are no issues I'll merge this soon, in hopes it will make it for the coccinelle 1.0.2 release.

Luis R. Rodriguez (4):
? ?pycocci: add requirements class
? ?pycocci: add git class
? ?pycocci: figure out if to enable --jobs, --use-gitgrep or ? ? ?--use-glimpse

Quoted 3 lines
Quoted 1 line

Do you need patches 2 and 3?

Do you mean I should squash them together, or something else ?

I meant that since --use-git is able to cope with receiving a subtree of a git repository, because git itself is able to cope with that, perhaps you don't need them at all. It seems like you are redoing all the work that git already does.

julia

Quoted 21 lines

? Luis

Quoted 5 lines

julia

Quoted 3 lines

? ?pycocci: add Coccinelle SmPL patch proof support

? tools/pycocci | 475

++++++++++++++++++++++++++++++++++++++++++++++++++++++++--

Quoted 10 lines
Quoted 10 lines

? 1 file changed, 462 insertions(+), 13 deletions(-)

--
2.3.2.209.gd67f9d5.dirty

_______________________________________________
Cocci mailing list
Cocci at systeme.lip6.fr
https://systeme.lip6.fr/mailman/listinfo/cocci

#8 lore raw
Quoted 8 lines · Julia Lawall
Quoted 3 lines
Quoted 1 line

Do you need patches 2 and 3?

Do you mean I should squash them together, or something else ?

I meant that since --use-git is able to cope with receiving a subtree of a git repository, because git itself is able to cope with that, perhaps you don't need them at all. It seems like you are redoing all the work that git already does.

Ah, well so although --use-gitgrep has its own heuristics for determining if gitgrep can correctly be used or not we still need something to figure out if it toggle --use-gitgrep or not as I do not think Coccinelle automatically tries to make use of --use-gitgrep unless otherwise specified, please correct me if I'm wrong. That is, if no indexing arguments are passed does Coccinelle figure out on its own whether or not to use --use-glimpse, --use-gitgrep and as a last resort --use-coccigrep ? This is what pycocci is doing here. Other than this another reason for the git class in this series is for Coccinelle SmPL patch equivalence proof support, that uses git to create branches for the patch version of changes, then the smpl version of changes, and finally 'git diff --stat between these two'.

Luis

#9 lore raw
Quoted 10 lines · Luis R. Rodriguez
Quoted 8 lines · Julia Lawall
Quoted 3 lines
Quoted 1 line

Do you need patches 2 and 3?

Do you mean I should squash them together, or something else ?

I meant that since --use-git is able to cope with receiving a subtree of a git repository, because git itself is able to cope with that, perhaps you don't need them at all. It seems like you are redoing all the work that git already does.

Quoted 12 lines

Ah, well so although --use-gitgrep has its own heuristics for determining if gitgrep can correctly be used or not we still need something to figure out if it toggle --use-gitgrep or not as I do not think Coccinelle automatically tries to make use of --use-gitgrep unless otherwise specified, please correct me if I'm wrong. That is, if no indexing arguments are passed does Coccinelle figure out on its own whether or not to use --use-glimpse, --use-gitgrep and as a last resort --use-coccigrep ? This is what pycocci is doing here. Other than this another reason for the git class in this series is for Coccinelle SmPL patch equivalence proof support, that uses git to create branches for the patch version of changes, then the smpl version of changes, and finally 'git diff --stat between these two'.

Not sure to understand. If there is glimpse information in the specified directory, then it would be reasonable to use glimpse. If there is glimpse information in a parent directory, I don't think that using glimpse would be a good idea. In any case, there is no code to handle that.

Otherwise, if you give the argument --use-gitgrep, and the git command fails (not just that it doesn't find anything, but that it actually fails), then it will fall back to --use-coccigrep.

On the other hand, maybe the git detection is necessary for the equivalence check.

julia

#10 lore raw
Quoted 27 lines · Julia Lawall
Quoted 10 lines · Luis R. Rodriguez
Quoted 8 lines · Julia Lawall
Quoted 3 lines
Quoted 1 line

Do you need patches 2 and 3?

Do you mean I should squash them together, or something else ?

I meant that since --use-git is able to cope with receiving a subtree of a git repository, because git itself is able to cope with that, perhaps you don't need them at all. It seems like you are redoing all the work that git already does.

Quoted 12 lines

Ah, well so although --use-gitgrep has its own heuristics for determining if gitgrep can correctly be used or not we still need something to figure out if it toggle --use-gitgrep or not as I do not think Coccinelle automatically tries to make use of --use-gitgrep unless otherwise specified, please correct me if I'm wrong. That is, if no indexing arguments are passed does Coccinelle figure out on its own whether or not to use --use-glimpse, --use-gitgrep and as a last resort --use-coccigrep ? This is what pycocci is doing here. Other than this another reason for the git class in this series is for Coccinelle SmPL patch equivalence proof support, that uses git to create branches for the patch version of changes, then the smpl version of changes, and finally 'git diff --stat between these two'.

Quoted 5 lines

Not sure to understand. If there is glimpse information in the specified directory, then it would be reasonable to use glimpse. If there is glimpse information in a parent directory, I don't think that using glimpse would be a good idea. In any case, there is no code to handle that.

Indeed.

Quoted 3 lines

Otherwise, if you give the argument --use-gitgrep, and the git command fails (not just that it doesn't find anything, but that it actually fails), then it will fall back to --use-coccigrep.

Ah, so it should be safe to just check for the glimpse index on the target directory, use it if its there, otherwise default to using --use-gitgrep as a second step should be safe, regardless of whether or not the target (directory or file) is part of a git tree?

Quoted 2 lines

On the other hand, maybe the git detection is necessary for the equivalence check.

That would be, but the other check seems to be doing double work if I understand correctly as you note.

Luis

#11 lore raw
Quoted 4 lines

Ah, so it should be safe to just check for the glimpse index on the target directory, use it if its there, otherwise default to using --use-gitgrep as a second step should be safe, regardless of whether or not the target (directory or file) is part of a git tree?

Yep.

julia

#12 lore raw
Quoted 6 lines · Julia Lawall
Quoted 4 lines

Ah, so it should be safe to just check for the glimpse index on the target directory, use it if its there, otherwise default to using --use-gitgrep as a second step should be safe, regardless of whether or not the target (directory or file) is part of a git tree?

Yep.

Great thanks, can you confirm if that safe for Coccinelle 1.0.1 or will that only be a safe bet for 1.0.2 ? If only safe for 1.0.2 then I can have it default only for 1.0.2 and for 1.0.2 leave the check in place?

Luis

#13 lore raw
Quoted 6 lines · Luis R. Rodriguez
Quoted 5 lines · Julia Lawall
Quoted 4 lines

Ah, so it should be safe to just check for the glimpse index on the target directory, use it if its there, otherwise default to using --use-gitgrep as a second step should be safe, regardless of whether or not the target (directory or file) is part of a git tree?

Quoted 6 lines
Quoted 1 line

Yep.

Great thanks, can you confirm if that safe for Coccinelle 1.0.1 or will that only be a safe bet for 1.0.2 ? If only safe for 1.0.2 then I can have it default only for 1.0.2 and for 1.0.2 leave the check in place?

It's only supported as of 1.0.2.

julia