1# coding: utf-8
2"""The main CFFI wrapping of libzmq"""
3
4# Copyright (C) PyZMQ Developers
5# Distributed under the terms of the Modified BSD License.
6
7
8import json
9import os
10from os.path import dirname, join
11from cffi import FFI
12
13from zmq.utils.constant_names import all_names, no_prefix
14
15
16base_zmq_version = (3,2,2)
17
18def load_compiler_config():
19    """load pyzmq compiler arguments"""
20    import zmq
21    zmq_dir = dirname(zmq.__file__)
22    zmq_parent = dirname(zmq_dir)
23
24    fname = join(zmq_dir, 'utils', 'compiler.json')
25    if os.path.exists(fname):
26        with open(fname) as f:
27            cfg = json.load(f)
28    else:
29        cfg = {}
30
31    cfg.setdefault("include_dirs", [])
32    cfg.setdefault("library_dirs", [])
33    cfg.setdefault("runtime_library_dirs", [])
34    cfg.setdefault("libraries", ["zmq"])
35
36    # cast to str, because cffi can't handle unicode paths (?!)
37    cfg['libraries'] = [str(lib) for lib in cfg['libraries']]
38    for key in ("include_dirs", "library_dirs", "runtime_library_dirs"):
39        # interpret paths relative to parent of zmq (like source tree)
40        abs_paths = []
41        for p in cfg[key]:
42            if p.startswith('zmq'):
43                p = join(zmq_parent, p)
44            abs_paths.append(str(p))
45        cfg[key] = abs_paths
46    return cfg
47
48
49def zmq_version_info():
50    """Get libzmq version as tuple of ints"""
51    major = ffi.new('int*')
52    minor = ffi.new('int*')
53    patch = ffi.new('int*')
54
55    C.zmq_version(major, minor, patch)
56
57    return (int(major[0]), int(minor[0]), int(patch[0]))
58
59
60cfg = load_compiler_config()
61ffi = FFI()
62
63def _make_defines(names):
64    _names = []
65    for name in names:
66        define_line = "#define %s ..." % (name)
67        _names.append(define_line)
68
69    return "\n".join(_names)
70
71c_constant_names = []
72for name in all_names:
73    if no_prefix(name):
74        c_constant_names.append(name)
75    else:
76        c_constant_names.append("ZMQ_" + name)
77
78# load ffi definitions
79here = os.path.dirname(__file__)
80with open(os.path.join(here, '_cdefs.h')) as f:
81    _cdefs = f.read()
82
83with open(os.path.join(here, '_verify.c')) as f:
84    _verify = f.read()
85
86ffi.cdef(_cdefs)
87ffi.cdef(_make_defines(c_constant_names))
88
89try:
90    C = ffi.verify(_verify,
91        modulename='_cffi_ext',
92        libraries=cfg['libraries'],
93        include_dirs=cfg['include_dirs'],
94        library_dirs=cfg['library_dirs'],
95        runtime_library_dirs=cfg['runtime_library_dirs'],
96    )
97    _version_info = zmq_version_info()
98except Exception as e:
99    raise ImportError("PyZMQ CFFI backend couldn't find zeromq: %s\n"
100    "Please check that you have zeromq headers and libraries." % e)
101
102if _version_info < (3,2,2):
103    raise ImportError("PyZMQ CFFI backend requires zeromq >= 3.2.2,"
104        " but found %i.%i.%i" % _version_info
105    )
106
107nsp = new_sizet_pointer = lambda length: ffi.new('size_t*', length)
108
109new_uint64_pointer = lambda: (ffi.new('uint64_t*'),
110                              nsp(ffi.sizeof('uint64_t')))
111new_int64_pointer = lambda: (ffi.new('int64_t*'),
112                             nsp(ffi.sizeof('int64_t')))
113new_int_pointer = lambda: (ffi.new('int*'),
114                           nsp(ffi.sizeof('int')))
115new_binary_data = lambda length: (ffi.new('char[%d]' % (length)),
116                                  nsp(ffi.sizeof('char') * length))
117
118value_uint64_pointer = lambda val : (ffi.new('uint64_t*', val),
119                                     ffi.sizeof('uint64_t'))
120value_int64_pointer = lambda val: (ffi.new('int64_t*', val),
121                                   ffi.sizeof('int64_t'))
122value_int_pointer = lambda val: (ffi.new('int*', val),
123                                 ffi.sizeof('int'))
124value_binary_data = lambda val, length: (ffi.new('char[%d]' % (length + 1), val),
125                                         ffi.sizeof('char') * length)
126
127IPC_PATH_MAX_LEN = C.get_ipc_path_max_len()
128