diff --git "a/test.jsonl" "b/test.jsonl" new file mode 100644--- /dev/null +++ "b/test.jsonl" @@ -0,0 +1,72 @@ +{"instance_id": "clb-pyc-002", "repo": "scipy/scipy", "base_commit": "ff177d92b79167eb5de593c9de41d3ceb97ab189", "problem_statement": "interpolation.zoom incorrect output for certain cases\nI found the behaviour of zoom to be incorrect when working with 3D arrays for nearest neighbour interpolation.\n\nfor example, try the following:\n\n```\nx = numpy.zeros(32, 32, 11)\nx[12, 16, 8] = 1\ny = interpolation.zoom(x, 4, order=0)\n```\n\nand when I check to see at `y[12*4, 16*4, 8*4]` I find its 0, not 1.\non closer analysis, if I do `numpy.where(y==1)` I find:\n\n```\n(array([48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49,\n 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 50, 50,\n 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 51, 51, 51,\n 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51]),\n array([64, 64, 64, 64, 65, 65, 65, 65, 66, 66, 66, 66, 67, 67, 67, 67, 64,\n 64, 64, 64, 65, 65, 65, 65, 66, 66, 66, 66, 67, 67, 67, 67, 64, 64,\n 64, 64, 65, 65, 65, 65, 66, 66, 66, 66, 67, 67, 67, 67, 64, 64, 64,\n 64, 65, 65, 65, 65, 66, 66, 66, 66, 67, 67, 67, 67]),\n array([33, 34, 35, 36, 33, 34, 35, 36, 33, 34, 35, 36, 33, 34, 35, 36, 33,\n 34, 35, 36, 33, 34, 35, 36, 33, 34, 35, 36, 33, 34, 35, 36, 33, 34,\n 35, 36, 33, 34, 35, 36, 33, 34, 35, 36, 33, 34, 35, 36, 33, 34, 35,\n 36, 33, 34, 35, 36, 33, 34, 35, 36, 33, 34, 35, 36]))\n```\n\nit looks like the last dimension is off by 1.\n\nin contrast, if I perform the same test with skimage.transform.resize \n\n```\ny2 = transform.resize(x, numpy.asarray(x.shape)*4, order=0)\n```\n- it provides me with the right output for `numpy.where(y2==1)`:\n\n```\n(array([48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49,\n 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 50, 50,\n 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 51, 51, 51,\n 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51]),\n array([64, 64, 64, 64, 65, 65, 65, 65, 66, 66, 66, 66, 67, 67, 67, 67, 64,\n 64, 64, 64, 65, 65, 65, 65, 66, 66, 66, 66, 67, 67, 67, 67, 64, 64,\n 64, 64, 65, 65, 65, 65, 66, 66, 66, 66, 67, 67, 67, 67, 64, 64, 64,\n 64, 65, 65, 65, 65, 66, 66, 66, 66, 67, 67, 67, 67]),\n array([32, 33, 34, 35, 32, 33, 34, 35, 32, 33, 34, 35, 32, 33, 34, 35, 32,\n 33, 34, 35, 32, 33, 34, 35, 32, 33, 34, 35, 32, 33, 34, 35, 32, 33,\n 34, 35, 32, 33, 34, 35, 32, 33, 34, 35, 32, 33, 34, 35, 32, 33, 34,\n 35, 32, 33, 34, 35, 32, 33, 34, 35, 32, 33, 34, 35]))\n```\n\nunexpected zero output values from zoom\nLast lines / columns of zoomed images seem to have unexpected zero values in some cases.\n\nAfter running \n\n``` python\nimport numpy as np\nfrom scipy.ndimage import zoom\na = zoom(np.ones((110, 72), np.float32), (51. / 110, 40. / 72))\n```\n\n`all(a[-1] == 0)` yields `True`\n\nThe issue is that after resizing a white image, you don't expect getting a black line at its bottom.\n\nZoom does not return the same values when resizing a sub-array relative to the entire array\nWhen you resize a sub-array with a factor of 3 (or higher) the result should be the same when resizing the entire array and then taking the same sub-array (3 times larger of course). However, when using zoom it is not, regardless of interpolation order\n\nCode to reproduce:\n\n```\nimport numpy\nfrom scipy.ndimage import zoom\nfrom scipy.misc import imresize\narr = numpy.array(range(36))\narr.shape = (6,6)\nres = zoom(arr, 3., order=0)\nres_sub = zoom(arr[0:4,0:4], 3., order=0)\nnumpy.abs(res[0:12,0:12] - res_sub).sum()\n```\n\nThe last result should return zero, but it does not. When using imresize, the result is as expected:\n\n```\narr = numpy.array(range(36))\narr.shape = (6,6)\nres = imresize(arr, 3., interp='nearest', mode='F').astype(int)\nres_sub = imresize(arr[0:4,0:4], 3., interp='nearest', mode='F').astype(int)\nnumpy.abs(res[0:12,0:12] - res_sub).sum()\n```\n\nsicpy.ndimage.zoom returns artefacts and boundaries in some cases\nI just ran into some strange behaviour of `scipy.ndimage.zoom` which I did not expect from the documentation. I am not sure whether it is a bug or me missunderstanding the expected behaviour. Here is my example:\n\n``` python\n>>> from scipy.ndimage import zoom\n>>> img = np.ones((768, 1024))\n>>> zoom(img, (0.125, 0.125), order=1)\n\narray([[ 1., 1., 1., ..., 1., 1., 1.],\n [ 1., 1., 1., ..., 1., 1., 1.],\n [ 1., 1., 1., ..., 1., 1., 1.],\n ..., \n [ 1., 1., 1., ..., 1., 1., 1.],\n [ 1., 1., 1., ..., 1., 1., 1.],\n [ 0., 0., 0., ..., 0., 0., 0.]])\n```\n\nIs there something I am missing here or is this bug?\n\nscipy.ndimage.zoom bad interpolation when downsampling (zoom < 1)\nImporting `ndimage` and `skimage` for comparsion:\r\n~~~python\r\nimport scipy.ndimage as ndimage\r\nimport skimage\r\n~~~\r\nNow let's produce simple `a` array as an example:\r\n~~~python\r\na = np.fromfunction(lambda x, y: x + y, (8, 8))\r\n# produces:\r\narray([[ 0., 1., 2., 3., 4., 5., 6., 7.],\r\n [ 1., 2., 3., 4., 5., 6., 7., 8.],\r\n [ 2., 3., 4., 5., 6., 7., 8., 9.],\r\n [ 3., 4., 5., 6., 7., 8., 9., 10.],\r\n [ 4., 5., 6., 7., 8., 9., 10., 11.],\r\n [ 5., 6., 7., 8., 9., 10., 11., 12.],\r\n [ 6., 7., 8., 9., 10., 11., 12., 13.],\r\n [ 7., 8., 9., 10., 11., 12., 13., 14.]])\r\n~~~\r\nNow scale it does by 2x:\r\n~~~python\r\nndimage.zoom(a, zoom=0.5, order=0)\r\n# produces:\r\narray([[ 0., 2., 5., 7.],\r\n [ 2., 4., 7., 9.],\r\n [ 5., 7., 10., 12.],\r\n [ 7., 9., 12., 14.]])\r\n~~~\r\nTop left values? Okie, let's try bilinear.\r\n~~~\r\nndimage.zoom(a, zoom=0.5, order=1)\r\n# produces:\r\narray([[ 0. , 2.33333333, 4.66666667, 7. ],\r\n [ 2.33333333, 4.66666667, 7. , 9.33333333],\r\n [ 4.66666667, 7. , 9.33333333, 11.66666667],\r\n [ 7. , 9.33333333, 11.66666667, 14. ]])\r\n~~~\r\nWhat are these values!? How 0. is a bilinear for `[[0, 1], [1, 2]]`?\r\nFor comparsion I do the same with `skimage`:\r\n~~~python\r\nskimage.transform.rescale(a, scale=0.5, order=1)\r\n# produces correct and expected values:\r\narray([[ 1., 3., 5., 7.],\r\n [ 3., 5., 7., 9.],\r\n [ 5., 7., 9., 11.],\r\n [ 7., 9., 11., 13.]])\r\n~~~\r\nSeems like `ndimage.zoom` is doing some awkward resampling, so the `(0, 0)` of new 4x4 grid matches top left corner of `(0, 0)` input 8x8 grid, while `(3, 3)` of 4x4 matches **bottom-right** of 8x8, while the interior pixels are somehow interpolated with this 1/3 steps.\r\n\r\nWhy `ndimage.zoom` is not resampling using pixel centers? But use pixel corners? This looks like a bug in the implementation. While `skimage` produces correct (and expected) values.\nndimage.interpolation.zoom() option to work like skimage.transform.resize()\n**Is your feature request related to a problem? Please describe.**\r\n\r\nGiven an array as below...\r\n\r\n```py\r\n>>> B = np.arange(0, 9).reshape((3, 3))\r\narray([[0, 1, 2],\r\n [3, 4, 5],\r\n [6, 7, 8]])\r\n```\r\n\r\nI'd like to be able to resample it with scipy.ndimage.interpolation.zoom():\r\n\r\n```py\r\n>>> interpolation.zoom(B, zoom = 2, order = 0)\r\narray([[0, 0, 1, 1, 2, 2],\r\n [0, 0, 1, 1, 2, 2],\r\n [3, 3, 4, 4, 5, 5],\r\n [3, 3, 4, 4, 5, 5],\r\n [6, 6, 7, 7, 8, 8],\r\n [6, 6, 7, 7, 8, 8]])\r\n```\r\n\r\nSo far, so good!\r\n\r\n```py\r\n>>> interpolation.zoom(B, zoom = 3, order = 0)\r\narray([[0, 0, 1, 1, 1, 1, 2, 2, 2],\r\n [0, 0, 1, 1, 1, 1, 2, 2, 2],\r\n [3, 3, 4, 4, 4, 4, 5, 5, 5],\r\n [3, 3, 4, 4, 4, 4, 5, 5, 5],\r\n [3, 3, 4, 4, 4, 4, 5, 5, 5],\r\n [3, 3, 4, 4, 4, 4, 5, 5, 5],\r\n [6, 6, 7, 7, 7, 7, 8, 8, 8],\r\n [6, 6, 7, 7, 7, 7, 8, 8, 8],\r\n [6, 6, 7, 7, 7, 7, 8, 8, 8]])\r\n```\r\n\r\nWRONG. Why is this subset:\r\n\r\n```py\r\n>>> interpolation.zoom(B, zoom = 3, order = 0)[0:3,0:3]\r\narray([[0, 0, 1],\r\n [0, 0, 1],\r\n [3, 3, 4]])\r\n```\r\n\r\nNOT equal to:\r\n\r\n```py\r\narray([[0, 0, 0],\r\n [0, 0, 0],\r\n [0, 0, 0]])\r\n```\r\n\r\n**Describe the solution you'd like**\r\n\r\nThis is what I would have expected for a zeroth-order (nearest neighbor) resampling:\r\n\r\n```\r\narray([[ 0., 0., 0., 1., 1., 1., 2., 2., 2.],\r\n [ 0., 0., 0., 1., 1., 1., 2., 2., 2.],\r\n [ 0., 0., 0., 1., 1., 1., 2., 2., 2.],\r\n [ 3., 3., 3., 4., 4., 4., 5., 5., 5.],\r\n [ 3., 3., 3., 4., 4., 4., 5., 5., 5.],\r\n [ 3., 3., 3., 4., 4., 4., 5., 5., 5.],\r\n [ 6., 6., 6., 7., 7., 7., 8., 8., 8.],\r\n [ 6., 6., 6., 7., 7., 7., 8., 8., 8.],\r\n [ 6., 6., 6., 7., 7., 7., 8., 8., 8.]])\r\n```\r\n\r\nThis issue has confounded others before, but no clear solution within `scipy` or `numpy` exists:\r\n\r\n- https://stackoverflow.com/questions/33721988/scipy-ndimage-zoom-result-depends-on-image-size\r\n- https://stackoverflow.com/questions/48211632/scipy-ndimage-zoom-vs-skimage-transform-rescale-with-order-0?noredirect=1&lq=1\r\n\r\nIt'd be nice if `scipy.ndimage.interpolation.zoom()` supported this, because:\r\n\r\n- Many people seem to *believe* this is what `zoom()` will do (and will be confused when it doesn't);\r\n- `scikit-learn` / `skimage` has many, many more dependencies and this feature is *almost* available in `scipy` as-is.\r\n\r\n**Describe alternatives you've considered**\r\n\r\nIn skimage.transform.resize(), I get the desired result:\r\n\r\n```py\r\n>>> skimage.transform.resize(B, (9, 9), order = 0, preserve_range = True)\r\narray([[ 0., 0., 0., 1., 1., 1., 2., 2., 2.],\r\n [ 0., 0., 0., 1., 1., 1., 2., 2., 2.],\r\n [ 0., 0., 0., 1., 1., 1., 2., 2., 2.],\r\n [ 3., 3., 3., 4., 4., 4., 5., 5., 5.],\r\n [ 3., 3., 3., 4., 4., 4., 5., 5., 5.],\r\n [ 3., 3., 3., 4., 4., 4., 5., 5., 5.],\r\n [ 6., 6., 6., 7., 7., 7., 8., 8., 8.],\r\n [ 6., 6., 6., 7., 7., 7., 8., 8., 8.],\r\n [ 6., 6., 6., 7., 7., 7., 8., 8., 8.]])\r\n```\r\n\r\nThanks for your consideration!\r\n\n", "image": {"image_id": "sha256:a06dba0866df6cc6a1b517fb2516808a1afb412e1ced4adb6fec3518c33cc617", "pull_reference": "yutu0814/pyc-case-002-scipy@sha256:a06dba0866df6cc6a1b517fb2516808a1afb412e1ced4adb6fec3518c33cc617"}, "cohort": "python50", "patch": "diff --git a/scipy/ndimage/interpolation.py b/scipy/ndimage/interpolation.py\nindex 8f5f1bc..2e85cdf 100644\n--- a/scipy/ndimage/interpolation.py\n+++ b/scipy/ndimage/interpolation.py\n@@ -597,7 +597,7 @@ def affine_transform(input, matrix, offset=0.0, output_shape=None,\n \"SciPy 0.18.0.\"\n )\n _nd_image.zoom_shift(filtered, matrix, offset/matrix, output, order,\n- mode, cval, npad)\n+ mode, cval, npad, False)\n else:\n _nd_image.geometric_transform(filtered, None, None, matrix, offset,\n output, order, mode, cval, npad, None,\n@@ -673,13 +673,13 @@ def shift(input, shift, output=None, order=3, mode='constant', cval=0.0,\n if not shift.flags.contiguous:\n shift = shift.copy()\n _nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval,\n- npad)\n+ npad, False)\n return output\n \n \n @docfiller\n def zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0,\n- prefilter=True):\n+ prefilter=True, *, grid_mode=False):\n \"\"\"\n Zoom an array.\n \n@@ -698,6 +698,22 @@ def zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0,\n %(mode_interp_constant)s\n %(cval)s\n %(prefilter)s\n+ grid_mode : bool, optional\n+ If False, the distance from the pixel centers is zoomed. Otherwise, the\n+ distance including the full pixel extent is used. For example, a 1d\n+ signal of length 5 is considered to have length 4 when `grid_mode` is\n+ False, but length 5 when `grid_mode` is True. See the following\n+ visual illustration:\n+\n+ .. code-block:: text\n+\n+ | pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 |\n+ |<-------------------------------------->|\n+ vs.\n+ |<----------------------------------------------->|\n+\n+ The starting point of the arrow in the diagram above corresponds to\n+ coordinate location 0 in each mode.\n \n Returns\n -------\n@@ -758,16 +774,35 @@ def zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0,\n else:\n npad = 0\n filtered = input\n+ if grid_mode:\n+ # warn about modes that may have surprising behavior\n+ suggest_mode = None\n+ if mode == 'constant':\n+ suggest_mode = 'grid-constant'\n+ elif mode == 'wrap':\n+ suggest_mode = 'grid-wrap'\n+ if suggest_mode is not None:\n+ warnings.warn(\n+ (\"It is recommended to use mode = {} instead of {} when \"\n+ \"grid_mode is True.\"\n+ ).format(suggest_mode, mode)\n+ )\n mode = _ni_support._extend_mode_to_code(mode)\n \n- zoom_div = numpy.array(output_shape, float) - 1\n+ zoom_div = numpy.array(output_shape)\n+ zoom_nominator = numpy.array(input.shape)\n+ if not grid_mode:\n+ zoom_div -= 1\n+ zoom_nominator -= 1\n+\n # Zooming to infinite values is unpredictable, so just choose\n # zoom factor 1 instead\n- zoom = numpy.divide(numpy.array(input.shape) - 1, zoom_div,\n+ zoom = numpy.divide(zoom_nominator, zoom_div,\n out=numpy.ones_like(input.shape, dtype=numpy.float64),\n where=zoom_div != 0)\n zoom = numpy.ascontiguousarray(zoom)\n- _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval, npad)\n+ _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval, npad,\n+ grid_mode)\n return output\n \n \ndiff --git a/scipy/ndimage/src/nd_image.c b/scipy/ndimage/src/nd_image.c\nindex 0e8a854..f8d51b6 100644\n--- a/scipy/ndimage/src/nd_image.c\n+++ b/scipy/ndimage/src/nd_image.c\n@@ -819,18 +819,19 @@ static PyObject *Py_ZoomShift(PyObject *obj, PyObject *args)\n {\n PyArrayObject *input = NULL, *output = NULL, *shift = NULL;\n PyArrayObject *zoom = NULL;\n- int mode, order, nprepad;\n+ int mode, order, nprepad, grid_mode;\n double cval;\n \n- if (!PyArg_ParseTuple(args, \"O&O&O&O&iidi\",\n+ if (!PyArg_ParseTuple(args, \"O&O&O&O&iidii\",\n NI_ObjectToInputArray, &input,\n NI_ObjectToOptionalInputArray, &zoom,\n NI_ObjectToOptionalInputArray, &shift,\n NI_ObjectToOutputArray, &output,\n- &order, &mode, &cval, &nprepad))\n+ &order, &mode, &cval, &nprepad, &grid_mode))\n goto exit;\n \n- NI_ZoomShift(input, zoom, shift, output, order, (NI_ExtendMode)mode, cval, nprepad);\n+ NI_ZoomShift(input, zoom, shift, output, order, (NI_ExtendMode)mode, cval,\n+ nprepad, grid_mode);\n #ifdef HAVE_WRITEBACKIFCOPY\n PyArray_ResolveWritebackIfCopy(output);\n #endif\ndiff --git a/scipy/ndimage/src/ni_interpolation.c b/scipy/ndimage/src/ni_interpolation.c\nindex 83ad542..f951883 100644\n--- a/scipy/ndimage/src/ni_interpolation.c\n+++ b/scipy/ndimage/src/ni_interpolation.c\n@@ -59,7 +59,8 @@ map_coordinate(double in, npy_intp len, int mode)\n npy_intp sz2 = 2 * len;\n if (in < -sz2)\n in = sz2 * (npy_intp)(-in / sz2) + in;\n- in = in < -len ? in + sz2 : -in - 1;\n+ // -1e-15 check to avoid possibility that: (-in - 1) == -1\n+ in = in < -len ? in + sz2 : (in > -1e-15 ? 1e-15 : -in) - 1;\n }\n break;\n case NI_EXTEND_WRAP:\n@@ -640,7 +641,7 @@ NI_GeometricTransform(PyArrayObject *input, int (*map)(npy_intp*, double*,\n \n int NI_ZoomShift(PyArrayObject *input, PyArrayObject* zoom_ar,\n PyArrayObject* shift_ar, PyArrayObject *output,\n- int order, int mode, double cval, int nprepad)\n+ int order, int mode, double cval, int nprepad, int grid_mode)\n {\n char *po, *pi;\n npy_intp **zeros = NULL, **offsets = NULL, ***edge_offsets = NULL;\n@@ -770,7 +771,16 @@ int NI_ZoomShift(PyArrayObject *input, PyArrayObject* zoom_ar,\n if (shifts)\n cc += shift;\n if (zooms)\n- cc *= zoom;\n+ {\n+ if (grid_mode)\n+ {\n+ cc += 0.5;\n+ cc *= zoom;\n+ cc -= 0.5;\n+ } else {\n+ cc *= zoom;\n+ }\n+ }\n cc += (double)nprepad;\n if ((mode != NI_EXTEND_GRID_CONSTANT) && (mode != NI_EXTEND_NEAREST)) {\n /* if the input coordinate is outside the borders, map it: */\ndiff --git a/scipy/ndimage/src/ni_interpolation.h b/scipy/ndimage/src/ni_interpolation.h\nindex f0beaca..53d3e2d 100644\n--- a/scipy/ndimage/src/ni_interpolation.h\n+++ b/scipy/ndimage/src/ni_interpolation.h\n@@ -38,6 +38,6 @@ int NI_GeometricTransform(PyArrayObject*, int (*)(npy_intp*, double*, int, int,\n PyArrayObject*, PyArrayObject*, int, int,\n double, int);\n int NI_ZoomShift(PyArrayObject*, PyArrayObject*, PyArrayObject*,\n- PyArrayObject*, int, int, double, int);\n+ PyArrayObject*, int, int, double, int, int);\n \n #endif\n", "test_patch": "diff --git a/scipy/ndimage/tests/test_interpolation.py b/scipy/ndimage/tests/test_interpolation.py\nindex 6563210..389c0ad 100644\n--- a/scipy/ndimage/tests/test_interpolation.py\n+++ b/scipy/ndimage/tests/test_interpolation.py\n@@ -1107,19 +1107,45 @@ class TestNdimageInterpolation:\n out = ndimage.zoom(arr, zoom)\n assert_array_equal(out.shape, (4, 15, 29))\n \n- @pytest.mark.parametrize('zoom', [(1, 1), (8, 2), (8, 8)])\n+ @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])\n @pytest.mark.parametrize('mode', ['nearest', 'constant', 'wrap', 'reflect',\n 'mirror', 'grid-wrap', 'grid-mirror',\n 'grid-constant'])\n def test_zoom_by_int_order0(self, zoom, mode):\n # order 0 zoom should be the same as replication via numpy.kron\n+ # Note: This is not True for general x shapes when grid_mode is False,\n+ # but works here for all modes because the size ratio happens to\n+ # always be an integer when x.shape = (2, 2).\n x = numpy.array([[0, 1],\n [2, 3]], dtype=float)\n+ # x = numpy.arange(16, dtype=float).reshape(4, 4)\n assert_array_almost_equal(\n ndimage.zoom(x, zoom, order=0, mode=mode),\n numpy.kron(x, numpy.ones(zoom))\n )\n \n+ @pytest.mark.parametrize('shape', [(2, 3), (4, 4)])\n+ @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])\n+ @pytest.mark.parametrize('mode', ['nearest', 'reflect', 'mirror',\n+ 'grid-wrap', 'grid-constant'])\n+ def test_zoom_grid_by_int_order0(self, shape, zoom, mode):\n+ # When grid_mode is True, order 0 zoom should be the same as\n+ # replication via numpy.kron. The only exceptions to this are the\n+ # non-grid modes 'constant' and 'wrap'.\n+ x = numpy.arange(numpy.prod(shape), dtype=float).reshape(shape)\n+ assert_array_almost_equal(\n+ ndimage.zoom(x, zoom, order=0, mode=mode, grid_mode=True),\n+ numpy.kron(x, numpy.ones(zoom))\n+ )\n+\n+ @pytest.mark.parametrize('mode', ['constant', 'wrap'])\n+ def test_zoom_grid_mode_warnings(self, mode):\n+ # Warn on use of non-grid modes when grid_mode is True\n+ x = numpy.arange(9, dtype=float).reshape((3, 3))\n+ with pytest.warns(UserWarning,\n+ match=\"It is recommended to use mode\"):\n+ ndimage.zoom(x, 2, mode=mode, grid_mode=True),\n+\n @pytest.mark.parametrize('order', range(0, 6))\n def test_rotate01(self, order):\n data = numpy.array([[0, 0, 0, 0],\n", "FAIL_TO_PASS": ["scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[nearest-zoom0-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[nearest-zoom0-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[nearest-zoom1-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[nearest-zoom1-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[nearest-zoom2-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[nearest-zoom2-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[nearest-zoom3-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[nearest-zoom3-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[reflect-zoom0-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[reflect-zoom0-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[reflect-zoom1-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[reflect-zoom1-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[reflect-zoom2-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[reflect-zoom2-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[reflect-zoom3-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[reflect-zoom3-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[mirror-zoom0-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[mirror-zoom0-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[mirror-zoom1-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[mirror-zoom1-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[mirror-zoom2-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[mirror-zoom2-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[mirror-zoom3-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[mirror-zoom3-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-wrap-zoom0-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-wrap-zoom0-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-wrap-zoom1-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-wrap-zoom1-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-wrap-zoom2-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-wrap-zoom2-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-wrap-zoom3-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-wrap-zoom3-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-constant-zoom0-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-constant-zoom0-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-constant-zoom1-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-constant-zoom1-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-constant-zoom2-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-constant-zoom2-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-constant-zoom3-shape0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_by_int_order0[grid-constant-zoom3-shape1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_mode_warnings[constant]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_grid_mode_warnings[wrap]"], "PASS_TO_PASS": ["scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_boundaries[nearest-expected_value0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_boundaries2[grid-wrap-expected_value2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_boundary_spline_accuracy[0-grid-constant]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_boundary_spline_accuracy[2-reflect]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_boundary_spline_accuracy[3-nearest]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_boundary_spline_accuracy[5-grid-mirror]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline01[uint8-3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline01[uint16-5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline01[int64-2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline01[float32-3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline02[int8-4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline02[uint16-2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline02[uint32-3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline02[uint64-4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline03[int8-2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline03[int16-3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline03[int32-4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline03[int64-5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline03[float64-3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline04[uint8-4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline04[uint16-5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline04[int64-3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline04[float32-4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline05[int8-5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline05[uint16-3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline05[uint32-4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_spline05[uint64-5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform01[0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform02[4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform04[1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform05[float64-4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform06[2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform07[5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform10[2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform13[5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform15[3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform17[0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform18[3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform20[1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform21[4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform23[1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform24[5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform_vs_padded[1-nearest]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform_vs_padded[3-grid-wrap]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_geometric_transform_vs_padded[5-grid-constant]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_map_coordinates01[float64-3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_map_coordinates02[0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_map_coordinates_large_data", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform02[3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform04[0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform05[float64-3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform06[0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform07[4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform09[1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform10[4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform12[2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform13[5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform15[2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform16[5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform18[3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform20[0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform21[3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform23[1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform24[4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform26[1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform_shift_via_grid_wrap[0-shift1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform_shift_via_grid_wrap[2-shift0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform_shift_via_grid_wrap[3-shift4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_affine_transform_shift_via_grid_wrap[5-shift3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift01[2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift02[5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift04[2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift05[complex128-0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift06[3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift08[0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift09[3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift_grid_wrap[1-shift2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift_grid_wrap[3-shift1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift_grid_wrap[5-shift0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift_grid_constant1[1-shift0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift_grid_constant1[2-shift4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift_grid_constant1[4-shift3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift_reflect[2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift_nearest_boundary[False-5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift_vs_padded[0-nearest]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift_vs_padded[2-grid-wrap]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_shift_vs_padded[4-grid-wrap]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom1[0]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_affine01[float64-1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_affine01[complex128-5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_by_int_order0[constant-zoom1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_by_int_order0[reflect-zoom2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_zoom_by_int_order0[grid-wrap-zoom3]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_rotate01[1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_rotate02[4]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_rotate03[complex128-1]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_rotate04[5]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_rotate06[2]", "scipy/ndimage/tests/test_interpolation.py::TestNdimageInterpolation::test_rotate07[5]", "scipy/ndimage/tests/test_interpolation.py::test_zoom_output_shape"]} +{"instance_id": "clb-pyc-007", "repo": "numpy/numpy", "base_commit": "fc2518ba6b11fc52b0ff477b9e83576be90562d8", "problem_statement": "NumPy's array-allocation failure path raises _ArrayMemoryError and returns immediately, bypassing the common failure cleanup and leaking dtype references on every failed allocation. Route this path through the shared cleanup while preserving the formatted allocation error.", "image": {"image_id": "sha256:ddbe5866e7eec2a3e12f4ebf75adf5c83c154c8ac15f049f3039395c37a8c617", "pull_reference": "yutu0814/pyc-case-007-numpy@sha256:ddbe5866e7eec2a3e12f4ebf75adf5c83c154c8ac15f049f3039395c37a8c617"}, "cohort": "python50", "patch": "diff --git a/numpy/core/src/multiarray/ctors.c b/numpy/core/src/multiarray/ctors.c\nindex 502ab0e..beee985 100644\n--- a/numpy/core/src/multiarray/ctors.c\n+++ b/numpy/core/src/multiarray/ctors.c\n@@ -869,7 +869,7 @@ discover_dimensions(PyObject *obj, int *maxndim, npy_intp *d, int check_it,\n return 0;\n }\n \n-static PyObject *\n+static void\n raise_memory_error(int nd, npy_intp const *dims, PyArray_Descr *descr)\n {\n static PyObject *exc_type = NULL;\n@@ -894,12 +894,12 @@ raise_memory_error(int nd, npy_intp const *dims, PyArray_Descr *descr)\n }\n PyErr_SetObject(exc_type, exc_value);\n Py_DECREF(exc_value);\n- return NULL;\n+ return;\n \n fail:\n /* we couldn't raise the formatted exception for some reason */\n PyErr_WriteUnraisable(NULL);\n- return PyErr_NoMemory();\n+ PyErr_NoMemory();\n }\n \n /*\n@@ -1079,10 +1079,10 @@ PyArray_NewFromDescr_int(\n data = npy_alloc_cache(nbytes);\n }\n if (data == NULL) {\n- return raise_memory_error(fa->nd, fa->dimensions, descr);\n+ raise_memory_error(fa->nd, fa->dimensions, descr);\n+ goto fail;\n }\n fa->flags |= NPY_ARRAY_OWNDATA;\n-\n }\n else {\n /*\n", "test_patch": "diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py\nindex 2edcc68..86a8cff 100644\n--- a/numpy/core/tests/test_multiarray.py\n+++ b/numpy/core/tests/test_multiarray.py\n@@ -845,6 +845,13 @@ class TestCreation:\n assert_raises(ValueError, np.zeros, shape, dtype=np.int8)\n assert_raises(ValueError, np.ones, shape, dtype=np.int8)\n \n+ @pytest.mark.skipif(np.dtype(np.intp).itemsize != 8,\n+ reason=\"malloc may not fail on 32 bit systems\")\n+ def test_malloc_fails(self):\n+ # This test is guaranteed to fail due to a too large allocation\n+ with assert_raises(np.core._exceptions._ArrayMemoryError):\n+ np.empty(np.iinfo(np.intp).max, dtype=np.uint8)\n+\n def test_zeros(self):\n types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']\n for dt in types:\n", "FAIL_TO_PASS": ["numpy/core/tests/test_multiarray.py::TestCreation::test_malloc_fails"], "PASS_TO_PASS": ["numpy/core/tests/test_multiarray.py::TestCreation::test_zeros"]} +{"instance_id": "clb-pyc-010", "repo": "numpy/numpy", "base_commit": "5e8ad11b75245caf2d158eacf369b011ef262795", "problem_statement": "Several ndarray methods return a newly converted Python/NumPy scalar when a caller supplies a zero-dimensional out array. They must return the exact out object by identity, consistently with higher-dimensional outputs.", "image": {"image_id": "sha256:9c6264f39867c2376935e2c989a26c328eadb1b0f813d66291a224c84971e790", "pull_reference": "yutu0814/pyc-case-010-numpy@sha256:9c6264f39867c2376935e2c989a26c328eadb1b0f813d66291a224c84971e790"}, "cohort": "python50", "patch": "diff --git a/numpy/core/src/multiarray/methods.c b/numpy/core/src/multiarray/methods.c\nindex 8a659fa..262514e 100644\n--- a/numpy/core/src/multiarray/methods.c\n+++ b/numpy/core/src/multiarray/methods.c\n@@ -117,8 +117,15 @@ array_take(PyArrayObject *self, PyObject *args, PyObject *kwds)\n PyArray_ClipmodeConverter, &mode))\n return NULL;\n \n- return PyArray_Return((PyArrayObject *)\n- PyArray_TakeFrom(self, indices, dimension, out, mode));\n+ PyObject *ret = PyArray_TakeFrom(self, indices, dimension, out, mode);\n+\n+ /* this matches the unpacking behavior of ufuncs */\n+ if (out == NULL) {\n+ return PyArray_Return((PyArrayObject *)ret);\n+ }\n+ else {\n+ return ret;\n+ }\n }\n \n static PyObject *\n@@ -274,7 +281,15 @@ array_argmax(PyArrayObject *self, PyObject *args, PyObject *kwds)\n PyArray_OutputConverter, &out))\n return NULL;\n \n- return PyArray_Return((PyArrayObject *)PyArray_ArgMax(self, axis, out));\n+ PyObject *ret = PyArray_ArgMax(self, axis, out);\n+\n+ /* this matches the unpacking behavior of ufuncs */\n+ if (out == NULL) {\n+ return PyArray_Return((PyArrayObject *)ret);\n+ }\n+ else {\n+ return ret;\n+ }\n }\n \n static PyObject *\n@@ -289,7 +304,15 @@ array_argmin(PyArrayObject *self, PyObject *args, PyObject *kwds)\n PyArray_OutputConverter, &out))\n return NULL;\n \n- return PyArray_Return((PyArrayObject *)PyArray_ArgMin(self, axis, out));\n+ PyObject *ret = PyArray_ArgMin(self, axis, out);\n+\n+ /* this matches the unpacking behavior of ufuncs */\n+ if (out == NULL) {\n+ return PyArray_Return((PyArrayObject *)ret);\n+ }\n+ else {\n+ return ret;\n+ }\n }\n \n static PyObject *\n@@ -1189,7 +1212,15 @@ array_choose(PyArrayObject *self, PyObject *args, PyObject *kwds)\n return NULL;\n }\n \n- return PyArray_Return((PyArrayObject *)PyArray_Choose(self, choices, out, clipmode));\n+ PyObject *ret = PyArray_Choose(self, choices, out, clipmode);\n+\n+ /* this matches the unpacking behavior of ufuncs */\n+ if (out == NULL) {\n+ return PyArray_Return((PyArrayObject *)ret);\n+ }\n+ else {\n+ return ret;\n+ }\n }\n \n static PyObject *\n@@ -2290,8 +2321,16 @@ array_compress(PyArrayObject *self, PyObject *args, PyObject *kwds)\n PyArray_OutputConverter, &out)) {\n return NULL;\n }\n- return PyArray_Return(\n- (PyArrayObject *)PyArray_Compress(self, condition, axis, out));\n+\n+ PyObject *ret = PyArray_Compress(self, condition, axis, out);\n+\n+ /* this matches the unpacking behavior of ufuncs */\n+ if (out == NULL) {\n+ return PyArray_Return((PyArrayObject *)ret);\n+ }\n+ else {\n+ return ret;\n+ }\n }\n \n \n@@ -2326,7 +2365,15 @@ array_trace(PyArrayObject *self, PyObject *args, PyObject *kwds)\n \n rtype = _CHKTYPENUM(dtype);\n Py_XDECREF(dtype);\n- return PyArray_Return((PyArrayObject *)PyArray_Trace(self, offset, axis1, axis2, rtype, out));\n+ PyObject *ret = PyArray_Trace(self, offset, axis1, axis2, rtype, out);\n+\n+ /* this matches the unpacking behavior of ufuncs */\n+ if (out == NULL) {\n+ return PyArray_Return((PyArrayObject *)ret);\n+ }\n+ else {\n+ return ret;\n+ }\n }\n \n #undef _CHKTYPENUM\n@@ -2411,7 +2458,16 @@ array_round(PyArrayObject *self, PyObject *args, PyObject *kwds)\n PyArray_OutputConverter, &out)) {\n return NULL;\n }\n- return PyArray_Return((PyArrayObject *)PyArray_Round(self, decimals, out));\n+\n+ PyObject *ret = PyArray_Round(self, decimals, out);\n+\n+ /* this matches the unpacking behavior of ufuncs */\n+ if (out == NULL) {\n+ return PyArray_Return((PyArrayObject *)ret);\n+ }\n+ else {\n+ return ret;\n+ }\n }\n \n \n", "test_patch": "diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py\nindex f36c27c..a698370 100644\n--- a/numpy/core/tests/test_multiarray.py\n+++ b/numpy/core/tests/test_multiarray.py\n@@ -1582,6 +1582,11 @@ class TestMethods:\n # gh-12031, caused SEGFAULT\n assert_raises(TypeError, oned.choose,np.void(0), [oned])\n \n+ out = np.array(0)\n+ ret = np.choose(np.array(1), [10, 20, 30], out=out)\n+ assert out is ret\n+ assert_equal(out[()], 20)\n+\n # gh-6272 check overlap on out\n x = np.arange(5)\n y = np.choose([0,0,0], [x[:3], x[:3], x[:3]], out=x[1:4], mode='wrap')\n@@ -1658,7 +1663,7 @@ class TestMethods:\n out = np.zeros_like(arr)\n res = arr.round(*round_args, out=out)\n assert_equal(out, expected)\n- assert_equal(out, res)\n+ assert out is res\n \n check_round(np.array([1.2, 1.5]), [1, 2])\n check_round(np.array(1.5), 2)\n@@ -3023,6 +3028,10 @@ class TestMethods:\n assert_equal(b.trace(0, 1, 2), [3, 11])\n assert_equal(b.trace(offset=1, axis1=0, axis2=2), [1, 3])\n \n+ out = np.array(1)\n+ ret = a.trace(out=out)\n+ assert ret is out\n+\n def test_trace_subclass(self):\n # The class would need to overwrite trace to ensure single-element\n # output also has the right subclass.\n@@ -4126,6 +4135,13 @@ class TestArgmax:\n a.argmax(-1, out=out)\n assert_equal(out, a.argmax(-1))\n \n+ @pytest.mark.parametrize('ndim', [0, 1])\n+ def test_ret_is_out(self, ndim):\n+ a = np.ones((4,) + (3,)*ndim)\n+ out = np.empty((3,)*ndim, dtype=np.intp)\n+ ret = a.argmax(axis=0, out=out)\n+ assert ret is out\n+\n def test_argmax_unicode(self):\n d = np.zeros(6031, dtype='>> a = np.zeros(2, dtype={'names':[], 'formats':[], 'offsets':[], 'itemsize':8})\r\n>>> b = a.view(np.dtype([]))\r\n>>> b\r\narray([], shape=(2, 0),\r\n dtype={'names':[], 'formats':[], 'offsets':[], 'itemsize':8})\r\n>>> b.dtype == np.dtype([])\r\nFalse\r\n```\r\n\r\n\n", "image": {"image_id": "sha256:8ec3a832740cfffca716ebf9a7a1b9b324d57ca877843e324a74f53f49942c4d", "pull_reference": "yutu0814/pyc-case-014-numpy@sha256:8ec3a832740cfffca716ebf9a7a1b9b324d57ca877843e324a74f53f49942c4d"}, "cohort": "python50", "patch": "diff --git a/doc/release/upcoming_changes/14393.c_api.rst b/doc/release/upcoming_changes/14393.c_api.rst\nnew file mode 100644\nindex 0000000..0afd275\n--- /dev/null\n+++ b/doc/release/upcoming_changes/14393.c_api.rst\n@@ -0,0 +1,5 @@\n+PyDataType_ISUNSIZED(descr) now returns False for structured datatypes\n+----------------------------------------------------------------------\n+Previously this returned True for any datatype of itemsize 0, but now this\n+returns false for the non-flexible datatype with itemsize 0, ``np.dtype([])``.\n+\ndiff --git a/doc/source/reference/c-api/array.rst b/doc/source/reference/c-api/array.rst\nindex a2b56ce..8936a47 100644\n--- a/doc/source/reference/c-api/array.rst\n+++ b/doc/source/reference/c-api/array.rst\n@@ -997,6 +997,10 @@ argument must be a :c:type:`PyObject *` that can be directly interpret\n called on flexible dtypes. Types that are attached to an array will always\n be sized, hence the array form of this macro not existing.\n \n+ .. versionchanged:: 1.18\n+\n+ For structured datatypes with no fields this function now returns False.\n+\n .. c:function:: PyTypeNum_ISUSERDEF(num)\n \n .. c:function:: PyDataType_ISUSERDEF(descr)\ndiff --git a/numpy/core/include/numpy/ndarraytypes.h b/numpy/core/include/numpy/ndarraytypes.h\nindex 1221aee..bda000d 100644\n--- a/numpy/core/include/numpy/ndarraytypes.h\n+++ b/numpy/core/include/numpy/ndarraytypes.h\n@@ -1695,7 +1695,8 @@ PyArray_CLEARFLAGS(PyArrayObject *arr, int flags)\n #define PyDataType_ISOBJECT(obj) PyTypeNum_ISOBJECT(((PyArray_Descr*)(obj))->type_num)\n #define PyDataType_HASFIELDS(obj) (((PyArray_Descr *)(obj))->names != NULL)\n #define PyDataType_HASSUBARRAY(dtype) ((dtype)->subarray != NULL)\n-#define PyDataType_ISUNSIZED(dtype) ((dtype)->elsize == 0)\n+#define PyDataType_ISUNSIZED(dtype) ((dtype)->elsize == 0 && \\\n+ !PyDataType_HASFIELDS(dtype))\n #define PyDataType_MAKEUNSIZED(dtype) ((dtype)->elsize = 0)\n \n #define PyArray_ISBOOL(obj) PyTypeNum_ISBOOL(PyArray_TYPE(obj))\ndiff --git a/numpy/core/src/multiarray/arrayobject.c b/numpy/core/src/multiarray/arrayobject.c\nindex eb939f4..074496d 100644\n--- a/numpy/core/src/multiarray/arrayobject.c\n+++ b/numpy/core/src/multiarray/arrayobject.c\n@@ -1200,15 +1200,28 @@ _void_compare(PyArrayObject *self, PyArrayObject *other, int cmp_op)\n }\n }\n if (res == NULL && !PyErr_Occurred()) {\n- PyErr_SetString(PyExc_ValueError, \"No fields found.\");\n+ /* these dtypes had no fields. Use a MultiIter to broadcast them\n+ * to an output array, and fill with True (for EQ)*/\n+ PyArrayMultiIterObject *mit = (PyArrayMultiIterObject *)\n+ PyArray_MultiIterNew(2, self, other);\n+ if (mit == NULL) {\n+ return NULL;\n+ }\n+\n+ res = PyArray_NewFromDescr(&PyArray_Type,\n+ PyArray_DescrFromType(NPY_BOOL),\n+ mit->nd, mit->dimensions,\n+ NULL, NULL, 0, NULL);\n+ Py_DECREF(mit);\n+ if (res) {\n+ PyArray_FILLWBYTE((PyArrayObject *)res,\n+ cmp_op == Py_EQ ? 1 : 0);\n+ }\n }\n return res;\n }\n else {\n- /*\n- * compare as a string. Assumes self and\n- * other have same descr->type\n- */\n+ /* compare as a string. Assumes self and other have same descr->type */\n return _strings_richcompare(self, other, cmp_op, 0);\n }\n }\ndiff --git a/numpy/core/src/multiarray/ctors.c b/numpy/core/src/multiarray/ctors.c\nindex f0a1550..6b4b9aa 100644\n--- a/numpy/core/src/multiarray/ctors.c\n+++ b/numpy/core/src/multiarray/ctors.c\n@@ -3843,7 +3843,13 @@ PyArray_FromBuffer(PyObject *buf, PyArray_Descr *type,\n s = (npy_intp)ts - offset;\n n = (npy_intp)count;\n itemsize = type->elsize;\n- if (n < 0 ) {\n+ if (n < 0) {\n+ if (itemsize == 0) {\n+ PyErr_SetString(PyExc_ValueError,\n+ \"cannot determine count if itemsize is 0\");\n+ Py_DECREF(type);\n+ return NULL;\n+ }\n if (s % itemsize != 0) {\n PyErr_SetString(PyExc_ValueError,\n \"buffer size must be a multiple\"\\\n@@ -4036,7 +4042,7 @@ PyArray_FromIter(PyObject *obj, PyArray_Descr *dtype, npy_intp count)\n }\n for (i = 0; (i < count || count == -1) &&\n (value = PyIter_Next(iter)); i++) {\n- if (i >= elcount) {\n+ if (i >= elcount && elsize != 0) {\n npy_intp nbytes;\n /*\n Grow PyArray_DATA(ret):\ndiff --git a/numpy/core/src/multiarray/methods.c b/numpy/core/src/multiarray/methods.c\nindex 79c60aa..8073071 100644\n--- a/numpy/core/src/multiarray/methods.c\n+++ b/numpy/core/src/multiarray/methods.c\n@@ -1861,7 +1861,7 @@ array_reduce_ex(PyArrayObject *self, PyObject *args)\n PyDataType_FLAGCHK(descr, NPY_ITEM_HASOBJECT) ||\n (PyType_IsSubtype(((PyObject*)self)->ob_type, &PyArray_Type) &&\n ((PyObject*)self)->ob_type != &PyArray_Type) ||\n- PyDataType_ISUNSIZED(descr)) {\n+ descr->elsize == 0) {\n /* The PickleBuffer class from version 5 of the pickle protocol\n * can only be used for arrays backed by a contiguous data buffer.\n * For all other cases we fallback to the generic array_reduce\n", "test_patch": "diff --git a/numpy/core/tests/test_dtype.py b/numpy/core/tests/test_dtype.py\nindex f60eab6..f5ca775 100644\n--- a/numpy/core/tests/test_dtype.py\n+++ b/numpy/core/tests/test_dtype.py\n@@ -419,6 +419,31 @@ class TestRecord(object):\n assert_raises(ValueError, np.dtype,\n {'formats': ['i4', 'i4'], 'f0': ('i4', 0), 'f1':('i4', 4)})\n \n+ def test_fieldless_views(self):\n+ a = np.zeros(2, dtype={'names':[], 'formats':[], 'offsets':[], \n+ 'itemsize':8})\n+ assert_raises(ValueError, a.view, np.dtype([]))\n+\n+ d = np.dtype((np.dtype([]), 10))\n+ assert_equal(d.shape, (10,))\n+ assert_equal(d.itemsize, 0)\n+ assert_equal(d.base, np.dtype([]))\n+\n+ arr = np.fromiter((() for i in range(10)), [])\n+ assert_equal(arr.dtype, np.dtype([]))\n+ assert_raises(ValueError, np.frombuffer, b'', dtype=[])\n+ assert_equal(np.frombuffer(b'', dtype=[], count=2),\n+ np.empty(2, dtype=[]))\n+\n+ assert_raises(ValueError, np.dtype, ([], 'f8'))\n+ assert_raises(ValueError, np.zeros(1, dtype='i4').view, [])\n+\n+ assert_equal(np.zeros(2, dtype=[]) == np.zeros(2, dtype=[]),\n+ np.ones(2, dtype=bool))\n+\n+ assert_equal(np.zeros((1, 2), dtype=[]) == a,\n+ np.ones((1, 2), dtype=bool))\n+\n \n class TestSubarray(object):\n def test_single_subarray(self):\n", "FAIL_TO_PASS": ["numpy/core/tests/test_dtype.py::TestRecord::test_fieldless_views"], "PASS_TO_PASS": ["numpy/core/tests/test_dtype.py::TestRecord::test_partial_dict", "numpy/core/tests/test_dtype.py::TestSubarray::test_single_subarray"]} +{"instance_id": "clb-pyc-015", "repo": "numpy/numpy", "base_commit": "965ea2ff417bcb285beca5c36cd02a8790a3d8f6", "problem_statement": "BUG: np.lexsort MemoryError on empty array with non-standard strides\nNumpy 1.17.0 raises MemoryError when using `lexsort` on an empty array with non-standard `strides`. If `strides` is the natural one, or if there is >= 1 element in the input, then it works as expected.\r\n\r\n### Reproducing code example:\r\n\r\n```python\r\nimport numpy as np\r\n\r\nxs = np.array([], dtype='i8')\r\nassert xs.strides == (8,)\r\nassert np.lexsort((xs,)).shape[0] == 0 # Works\r\n\r\nys = np.array([0], dtype='i8')\r\nys.strides = (16,)\r\nassert np.lexsort((ys,)).shape[0] == 1 # Works\r\n\r\nxs.strides = (16,)\r\nassert np.lexsort((xs,)).shape[0] == 0 # MemoryError\r\n```\r\n\r\n### Numpy/Python version information:\r\n\r\n1.17.0 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)]\n", "image": {"image_id": "sha256:f2da0afcaca3b41ce053ae0355187005b364e3490eda7dbeecac6561e03d5967", "pull_reference": "yutu0814/pyc-case-015-numpy@sha256:f2da0afcaca3b41ce053ae0355187005b364e3490eda7dbeecac6561e03d5967"}, "cohort": "python50", "patch": "diff --git a/numpy/core/src/multiarray/item_selection.c b/numpy/core/src/multiarray/item_selection.c\nindex 762563e..19de04a 100644\n--- a/numpy/core/src/multiarray/item_selection.c\n+++ b/numpy/core/src/multiarray/item_selection.c\n@@ -1456,8 +1456,8 @@ PyArray_LexSort(PyObject *sort_keys, int axis)\n \n /* Now we can check the axis */\n nd = PyArray_NDIM(mps[0]);\n- if ((nd == 0) || (PyArray_SIZE(mps[0]) == 1)) {\n- /* single element case */\n+ if ((nd == 0) || (PyArray_SIZE(mps[0]) <= 1)) {\n+ /* empty/single element case */\n ret = (PyArrayObject *)PyArray_NewFromDescr(\n &PyArray_Type, PyArray_DescrFromType(NPY_INTP),\n PyArray_NDIM(mps[0]), PyArray_DIMS(mps[0]), NULL, NULL,\n@@ -1466,7 +1466,9 @@ PyArray_LexSort(PyObject *sort_keys, int axis)\n if (ret == NULL) {\n goto fail;\n }\n- *((npy_intp *)(PyArray_DATA(ret))) = 0;\n+ if (PyArray_SIZE(mps[0]) > 0) {\n+ *((npy_intp *)(PyArray_DATA(ret))) = 0;\n+ }\n goto finish;\n }\n if (check_and_adjust_axis(&axis, nd) < 0) {\n@@ -1516,19 +1518,28 @@ PyArray_LexSort(PyObject *sort_keys, int axis)\n char *valbuffer, *indbuffer;\n int *swaps;\n \n- if (N == 0 || maxelsize == 0 || sizeof(npy_intp) == 0) {\n- goto fail;\n+ assert(N > 0); /* Guaranteed and assumed by indbuffer */\n+ int valbufsize = N * maxelsize;\n+ if (NPY_UNLIKELY(valbufsize) == 0) {\n+ valbufsize = 1; /* Ensure allocation is not empty */\n }\n- valbuffer = PyDataMem_NEW(N * maxelsize);\n+\n+ valbuffer = PyDataMem_NEW(valbufsize);\n if (valbuffer == NULL) {\n goto fail;\n }\n indbuffer = PyDataMem_NEW(N * sizeof(npy_intp));\n if (indbuffer == NULL) {\n+ PyDataMem_FREE(valbuffer);\n+ goto fail;\n+ }\n+ swaps = malloc(NPY_LIKELY(n > 0) ? n * sizeof(int) : 1);\n+ if (swaps == NULL) {\n+ PyDataMem_FREE(valbuffer);\n PyDataMem_FREE(indbuffer);\n goto fail;\n }\n- swaps = malloc(n*sizeof(int));\n+\n for (j = 0; j < n; j++) {\n swaps[j] = PyArray_ISBYTESWAPPED(mps[j]);\n }\n@@ -1557,8 +1568,8 @@ PyArray_LexSort(PyObject *sort_keys, int axis)\n #else\n if (rcode < 0) {\n #endif\n- npy_free_cache(valbuffer, N * maxelsize);\n- npy_free_cache(indbuffer, N * sizeof(npy_intp));\n+ PyDataMem_FREE(valbuffer);\n+ PyDataMem_FREE(indbuffer);\n free(swaps);\n goto fail;\n }\n", "test_patch": "diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py\nindex 944d053..c5289f6 100644\n--- a/numpy/core/tests/test_regression.py\n+++ b/numpy/core/tests/test_regression.py\n@@ -436,6 +436,32 @@ class TestRegression(object):\n \n assert_raises(KeyError, np.lexsort, BuggySequence())\n \n+ def test_lexsort_zerolen_custom_strides(self):\n+ # Ticket #14228\n+ xs = np.array([], dtype='i8')\n+ assert xs.strides == (8,)\n+ assert np.lexsort((xs,)).shape[0] == 0 # Works\n+\n+ xs.strides = (16,)\n+ assert np.lexsort((xs,)).shape[0] == 0 # Was: MemoryError\n+\n+ def test_lexsort_zerolen_custom_strides_2d(self):\n+ xs = np.array([], dtype='i8')\n+\n+ xs.shape = (0, 2)\n+ xs.strides = (16, 16)\n+ assert np.lexsort((xs,), axis=0).shape[0] == 0\n+\n+ xs.shape = (2, 0)\n+ xs.strides = (16, 16)\n+ assert np.lexsort((xs,), axis=0).shape[0] == 2\n+\n+ def test_lexsort_zerolen_element(self):\n+ dt = np.dtype([]) # a void dtype with no fields\n+ xs = np.empty(4, dt)\n+\n+ assert np.lexsort((xs,)).shape[0] == xs.shape[0]\n+\n def test_pickle_py2_bytes_encoding(self):\n # Check that arrays and scalars pickled on Py2 are\n # unpickleable on Py3 using encoding='bytes'\n", "FAIL_TO_PASS": ["numpy/core/tests/test_regression.py::TestRegression::test_lexsort_zerolen_custom_strides", "numpy/core/tests/test_regression.py::TestRegression::test_lexsort_zerolen_custom_strides_2d"], "PASS_TO_PASS": ["numpy/core/tests/test_regression.py::TestRegression::test_lexsort", "numpy/core/tests/test_regression.py::TestRegression::test_lexsort_invalid_sequence"]} +{"instance_id": "clb-pyc-022", "repo": "numpy/numpy", "base_commit": "99953e494aa3be5ae8385d8461b9e4dfbeec43ec", "problem_statement": "Creating an array from an object with an invalid __array_interface__ can corrupt the reference count of the cached dtype object on failure paths. Invalid shape or strides metadata should raise the expected exception without decreasing the global dtype reference count or triggering CPython reference-count errors.", "image": {"image_id": "sha256:7e54bbcd8594c941e1ee9e41ea15905787d0bca6fb8085b4523d5069737d6de8", "pull_reference": "yutu0814/pyc-case-022-numpy@sha256:7e54bbcd8594c941e1ee9e41ea15905787d0bca6fb8085b4523d5069737d6de8"}, "cohort": "python50", "patch": "diff --git a/numpy/core/src/multiarray/ctors.c b/numpy/core/src/multiarray/ctors.c\r\nindex 63bf537..b2e329d 100644\r\n--- a/numpy/core/src/multiarray/ctors.c\r\n+++ b/numpy/core/src/multiarray/ctors.c\r\n@@ -2500,6 +2500,11 @@ PyArray_FromInterface(PyObject *origin)\r\n &PyArray_Type, dtype,\r\n n, dims, NULL, data,\r\n dataflags, NULL, base);\r\n+ /*\r\n+ * Ref to dtype was stolen by PyArray_NewFromDescrAndBase\r\n+ * Prevent DECREFing dtype in fail codepath by setting to NULL\r\n+ */\r\n+ dtype = NULL;\r\n if (ret == NULL) {\r\n goto fail;\r\n }\r\n", "test_patch": "diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py\r\nindex a67a291..77534c1 100644\r\n--- a/numpy/core/tests/test_multiarray.py\r\n+++ b/numpy/core/tests/test_multiarray.py\r\n@@ -7009,12 +7009,11 @@ class TestArrayAttributeDeletion(object):\r\n assert_raises(AttributeError, delattr, a, s)\r\n \r\n \r\n-def test_array_interface():\r\n- # Test scalar coercion within the array interface\r\n+class TestArrayInterface():\r\n class Foo(object):\r\n def __init__(self, value):\r\n self.value = value\r\n- self.iface = {'typestr': '=f8'}\r\n+ self.iface = {'typestr': 'f8'}\r\n \r\n def __float__(self):\r\n return float(self.value)\r\n@@ -7023,22 +7022,39 @@ def test_array_interface():\r\n def __array_interface__(self):\r\n return self.iface\r\n \r\n+\r\n f = Foo(0.5)\r\n- assert_equal(np.array(f), 0.5)\r\n- assert_equal(np.array([f]), [0.5])\r\n- assert_equal(np.array([f, f]), [0.5, 0.5])\r\n- assert_equal(np.array(f).dtype, np.dtype('=f8'))\r\n- # Test various shape definitions\r\n- f.iface['shape'] = ()\r\n- assert_equal(np.array(f), 0.5)\r\n- f.iface['shape'] = None\r\n- assert_raises(TypeError, np.array, f)\r\n- f.iface['shape'] = (1, 1)\r\n- assert_equal(np.array(f), [[0.5]])\r\n- f.iface['shape'] = (2,)\r\n- assert_raises(ValueError, np.array, f)\r\n-\r\n- # test scalar with no shape\r\n+\r\n+ @pytest.mark.parametrize('val, iface, expected', [\r\n+ (f, {}, 0.5),\r\n+ ([f], {}, [0.5]),\r\n+ ([f, f], {}, [0.5, 0.5]),\r\n+ (f, {'shape': ()}, 0.5),\r\n+ (f, {'shape': None}, TypeError),\r\n+ (f, {'shape': (1, 1)}, [[0.5]]),\r\n+ (f, {'shape': (2,)}, ValueError),\r\n+ (f, {'strides': ()}, 0.5),\r\n+ (f, {'strides': (2,)}, ValueError),\r\n+ (f, {'strides': 16}, TypeError),\r\n+ ])\r\n+ def test_scalar_interface(self, val, iface, expected):\r\n+ # Test scalar coercion within the array interface\r\n+ self.f.iface = {'typestr': 'f8'}\r\n+ self.f.iface.update(iface)\r\n+ if HAS_REFCOUNT:\r\n+ pre_cnt = sys.getrefcount(np.dtype('f8'))\r\n+ if isinstance(expected, type):\r\n+ assert_raises(expected, np.array, val)\r\n+ else:\r\n+ result = np.array(val)\r\n+ assert_equal(np.array(val), expected)\r\n+ assert result.dtype == 'f8'\r\n+ del result\r\n+ if HAS_REFCOUNT:\r\n+ post_cnt = sys.getrefcount(np.dtype('f8'))\r\n+ assert_equal(pre_cnt, post_cnt)\r\n+\r\n+def test_interface_no_shape():\r\n class ArrayLike(object):\r\n array = np.array(1)\r\n __array_interface__ = array.__array_interface__\r\n", "FAIL_TO_PASS": ["numpy/core/tests/test_multiarray.py::TestArrayInterface::test_scalar_interface[val6-iface6-ValueError]", "numpy/core/tests/test_multiarray.py::TestArrayInterface::test_scalar_interface[val8-iface8-ValueError]", "numpy/core/tests/test_multiarray.py::TestArrayInterface::test_scalar_interface[val9-iface9-TypeError]"], "PASS_TO_PASS": ["numpy/core/tests/test_multiarray.py::test_interface_no_shape", "numpy/core/tests/test_multiarray.py::test_array_interface_itemsize"]} +{"instance_id": "clb-pyc-023", "repo": "numpy/numpy", "base_commit": "70b773e4015b4fbb61bc1f7bdffc9cc789d58e94", "problem_statement": "np.place warning: WRITEBACKIFCOPY detected in array_dealloc\nHello there,\r\n\r\nI'm having a problem with getting a runtime warning:\r\n\r\n/.../.virtualenv/python_3_env/lib/python3.6/site-packages/numpy/lib/function_base.py:1725: RuntimeWarning: WRITEBACKIFCOPY detected in array_dealloc. Required call to PyArray_ResolveWritebackIfCopy or PyArray_DiscardWritebackIfCopy is missing.\r\n\r\nActually, I'm curious about what this warning actually means?\r\nThe origin of the warning is from a numpy.place, wich is placed in a generator:\r\n\r\n```\r\ndef mygen():\r\n ...\r\n yield np.place(arr, bool_mask, vals)\r\n```\r\n\r\nIf I remove the np.place operation, there is no warning.\r\nThe weird thing is, that I only get this warning, after I call the generator for the second time, e.g.\r\n\r\n```\r\na = mygen() # no warning\r\na = mygen() # warning\r\na = mygen() # no warnings more from here on\r\n...\r\n\r\n```\r\n\r\nI'm using Python 3.6.2 and numpy 1.16.0.\r\n\r\n\r\n\r\n\r\n\n", "image": {"image_id": "sha256:8b841335373b60b3e3aa4c1cb856876881e173ce982971adaf302df454690fdf", "pull_reference": "yutu0814/pyc-case-023-numpy@sha256:8b841335373b60b3e3aa4c1cb856876881e173ce982971adaf302df454690fdf"}, "cohort": "python50", "patch": "diff --git a/numpy/core/src/multiarray/compiled_base.c b/numpy/core/src/multiarray/compiled_base.c\r\nindex 88924a8..625028b 100644\r\n--- a/numpy/core/src/multiarray/compiled_base.c\r\n+++ b/numpy/core/src/multiarray/compiled_base.c\r\n@@ -328,6 +328,7 @@ arr_insert(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)\r\n } else {\r\n Py_XDECREF(values);\r\n Py_XDECREF(mask);\r\n+ PyArray_ResolveWritebackIfCopy(array);\r\n Py_XDECREF(array);\r\n Py_RETURN_NONE;\r\n }\r\n@@ -358,6 +359,7 @@ arr_insert(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)\r\n \r\n fail:\r\n Py_XDECREF(mask);\r\n+ PyArray_ResolveWritebackIfCopy(array);\r\n Py_XDECREF(array);\r\n Py_XDECREF(values);\r\n return NULL;\r\n", "test_patch": "diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py\r\nindex 77534c1..241f8e4 100644\r\n--- a/numpy/core/tests/test_multiarray.py\r\n+++ b/numpy/core/tests/test_multiarray.py\r\n@@ -7729,6 +7729,8 @@ class TestWritebackIfCopy(object):\r\n # uses arr_insert\r\n np.place(a, a>2, [44, 55])\r\n assert_equal(a, np.array([[0, 44], [1, 55], [2, 44]]))\r\n+ # hit one of the failing paths\r\n+ assert_raises(ValueError, np.place, a, a>20, [])\r\n \r\n def test_put_noncontiguous(self):\r\n a = np.arange(6).reshape(2,3).T # force non-c-contiguous\r\n", "FAIL_TO_PASS": ["numpy/core/tests/test_multiarray.py::TestWritebackIfCopy::test_insert_noncontiguous"], "PASS_TO_PASS": ["numpy/core/tests/test_multiarray.py::TestWritebackIfCopy::test_put_noncontiguous", "numpy/core/tests/test_multiarray.py::TestWritebackIfCopy::test_putmask_noncontiguous"]} +{"instance_id": "clb-pyc-027", "repo": "numpy/numpy", "base_commit": "0fd5f2506bf2f41b023392c945312e5a1a3eb819", "problem_statement": "np.unravel_index() does not accept empty inputs\nI would expect a tuple of empty outputs back. I get the following:\n\n```\n>>> np.unravel_index([], (10, 12))\nTraceback (most recent call last):\n File \"\", line 1, in \nTypeError: Iterator operand 0 dtype could not be cast from dtype('float64') to dtype('int64') according to the rule 'same_kind'\n```\n\nThis does not seem to be a regression, as I can see this with numpy v1.9.2, but it does seem silly.\n\n", "image": {"image_id": "sha256:71d2efe092c6ee64b8a0a6ef40ee58ca656c90a6a43fbd8fd3aa2f35833dfc02", "pull_reference": "yutu0814/pyc-case-027-numpy@sha256:71d2efe092c6ee64b8a0a6ef40ee58ca656c90a6a43fbd8fd3aa2f35833dfc02"}, "cohort": "python50", "patch": "diff --git a/numpy/core/src/multiarray/compiled_base.c b/numpy/core/src/multiarray/compiled_base.c\r\nindex 1e0c1eb..d80d165 100644\r\n--- a/numpy/core/src/multiarray/compiled_base.c\r\n+++ b/numpy/core/src/multiarray/compiled_base.c\r\n@@ -832,17 +832,63 @@ fail:\r\n return NULL;\r\n }\r\n \r\n+static const char *EMPTY_SEQUENCE_ERR_MSG = \"indices must be integral: the provided \" \\\r\n+ \"empty sequence was inferred as float. Wrap it with \" \\\r\n+ \"'np.array(indices, dtype=np.intp)'\";\r\n+\r\n+static const char *NON_INTEGRAL_ERROR_MSG = \"only int indices permitted\";\r\n+\r\n+/* Convert obj to an ndarray with integer dtype or fail */\r\n+static PyArrayObject *\r\n+astype_anyint(PyObject *obj) {\r\n+ PyArrayObject *ret;\r\n+\r\n+ if (!PyArray_Check(obj)) {\r\n+ /* prefer int dtype */\r\n+ PyArray_Descr *dtype_guess = NULL;\r\n+ if (PyArray_DTypeFromObject(obj, NPY_MAXDIMS, &dtype_guess) < 0) {\r\n+ return NULL;\r\n+ }\r\n+ if (dtype_guess == NULL) {\r\n+ if (PySequence_Check(obj) && PySequence_Size(obj) == 0) {\r\n+ PyErr_SetString(PyExc_TypeError, EMPTY_SEQUENCE_ERR_MSG);\r\n+ }\r\n+ return NULL;\r\n+ }\r\n+ ret = (PyArrayObject*)PyArray_FromAny(obj, dtype_guess, 0, 0, 0, NULL);\r\n+ if (ret == NULL) {\r\n+ return NULL;\r\n+ }\r\n+ }\r\n+ else {\r\n+ ret = (PyArrayObject *)obj;\r\n+ Py_INCREF(ret);\r\n+ }\r\n+\r\n+ if (!(PyArray_ISINTEGER(ret) || PyArray_ISBOOL(ret))) {\r\n+ /* ensure dtype is int-based */\r\n+ PyErr_SetString(PyExc_TypeError, NON_INTEGRAL_ERROR_MSG);\r\n+ Py_DECREF(ret);\r\n+ return NULL;\r\n+ }\r\n+\r\n+ return ret;\r\n+}\r\n+\r\n /*\r\n * Converts a Python sequence into 'count' PyArrayObjects\r\n *\r\n- * seq - Input Python object, usually a tuple but any sequence works.\r\n- * op - Where the arrays are placed.\r\n- * count - How many arrays there should be (errors if it doesn't match).\r\n- * paramname - The name of the parameter that produced 'seq'.\r\n+ * seq - Input Python object, usually a tuple but any sequence works.\r\n+ * Must have integral content.\r\n+ * paramname - The name of the parameter that produced 'seq'.\r\n+ * count - How many arrays there should be (errors if it doesn't match).\r\n+ * op - Where the arrays are placed.\r\n */\r\n-static int sequence_to_arrays(PyObject *seq,\r\n- PyArrayObject **op, int count,\r\n- char *paramname)\r\n+static int int_sequence_to_arrays(PyObject *seq,\r\n+ char *paramname,\r\n+ int count,\r\n+ PyArrayObject **op\r\n+ )\r\n {\r\n int i;\r\n \r\n@@ -856,27 +902,23 @@ static int sequence_to_arrays(PyObject *seq,\r\n for (i = 0; i < count; ++i) {\r\n PyObject *item = PySequence_GetItem(seq, i);\r\n if (item == NULL) {\r\n- while (--i >= 0) {\r\n- Py_DECREF(op[i]);\r\n- op[i] = NULL;\r\n- }\r\n- return -1;\r\n+ goto fail;\r\n }\r\n-\r\n- op[i] = (PyArrayObject *)PyArray_FROM_O(item);\r\n+ op[i] = astype_anyint(item);\r\n+ Py_DECREF(item);\r\n if (op[i] == NULL) {\r\n- while (--i >= 0) {\r\n- Py_DECREF(op[i]);\r\n- op[i] = NULL;\r\n- }\r\n- Py_DECREF(item);\r\n- return -1;\r\n+ goto fail;\r\n }\r\n-\r\n- Py_DECREF(item);\r\n }\r\n \r\n return 0;\r\n+\r\n+fail:\r\n+ while (--i >= 0) {\r\n+ Py_XDECREF(op[i]);\r\n+ op[i] = NULL;\r\n+ }\r\n+ return -1;\r\n }\r\n \r\n /* Inner loop for unravel_index */\r\n@@ -1023,11 +1065,10 @@ arr_ravel_multi_index(PyObject *self, PyObject *args, PyObject *kwds)\r\n }\r\n \r\n /* Get the multi_index into op */\r\n- if (sequence_to_arrays(coords0, op, dimensions.len, \"multi_index\") < 0) {\r\n+ if (int_sequence_to_arrays(coords0, \"multi_index\", dimensions.len, op) < 0) {\r\n goto fail;\r\n }\r\n \r\n-\r\n for (i = 0; i < dimensions.len; ++i) {\r\n op_flags[i] = NPY_ITER_READONLY|\r\n NPY_ITER_ALIGNED;\r\n@@ -1222,15 +1263,9 @@ arr_unravel_index(PyObject *self, PyObject *args, PyObject *kwds)\r\n \r\n unravel_size = PyArray_MultiplyList(dimensions.ptr, dimensions.len);\r\n \r\n- if (!PyArray_Check(indices0)) {\r\n- indices = (PyArrayObject*)PyArray_FROM_O(indices0);\r\n- if (indices == NULL) {\r\n- goto fail;\r\n- }\r\n- }\r\n- else {\r\n- indices = (PyArrayObject *)indices0;\r\n- Py_INCREF(indices);\r\n+ indices = astype_anyint(indices0);\r\n+ if (indices == NULL) {\r\n+ goto fail;\r\n }\r\n \r\n dtype = PyArray_DescrFromType(NPY_INTP);\r\n", "test_patch": "diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py\r\nindex 3246f68..028bba3 100644\r\n--- a/numpy/lib/tests/test_index_tricks.py\r\n+++ b/numpy/lib/tests/test_index_tricks.py\r\n@@ -77,6 +77,26 @@ class TestRavelUnravelIndex(object):\r\n [[3, 6, 6], [4, 5, 1]])\r\n assert_equal(np.unravel_index(1621, (6, 7, 8, 9)), [3, 1, 4, 1])\r\n \r\n+ def test_empty_indices(self):\r\n+ msg1 = 'indices must be integral: the provided empty sequence was'\r\n+ msg2 = 'only int indices permitted'\r\n+ assert_raises_regex(TypeError, msg1, np.unravel_index, [], (10, 3, 5))\r\n+ assert_raises_regex(TypeError, msg1, np.unravel_index, (), (10, 3, 5))\r\n+ assert_raises_regex(TypeError, msg2, np.unravel_index, np.array([]),\r\n+ (10, 3, 5))\r\n+ assert_equal(np.unravel_index(np.array([],dtype=int), (10, 3, 5)),\r\n+ [[], [], []])\r\n+ assert_raises_regex(TypeError, msg1, np.ravel_multi_index, ([], []),\r\n+ (10, 3))\r\n+ assert_raises_regex(TypeError, msg1, np.ravel_multi_index, ([], ['abc']),\r\n+ (10, 3))\r\n+ assert_raises_regex(TypeError, msg2, np.ravel_multi_index,\r\n+ (np.array([]), np.array([])), (5, 3))\r\n+ assert_equal(np.ravel_multi_index(\r\n+ (np.array([], dtype=int), np.array([], dtype=int)), (5, 3)), [])\r\n+ assert_equal(np.ravel_multi_index(np.array([[], []], dtype=int),\r\n+ (5, 3)), [])\r\n+\r\n def test_big_indices(self):\r\n # ravel_multi_index for big indices (issue #7546)\r\n if np.intp == np.int64:\r\n", "FAIL_TO_PASS": ["numpy/lib/tests/test_index_tricks.py::TestRavelUnravelIndex::test_empty_indices"], "PASS_TO_PASS": ["numpy/lib/tests/test_index_tricks.py::TestRavelUnravelIndex::test_big_indices", "numpy/lib/tests/test_index_tricks.py::TestRavelUnravelIndex::test_dtypes"]} +{"instance_id": "clb-pyc-031", "repo": "numpy/numpy", "base_commit": "b65b21c397381351965bf3f590054d2bccdd03d2", "problem_statement": "choose does not broadcast index array appropriately (Trac #925)\n_Original ticket http://projects.scipy.org/numpy/ticket/925 on 2008-10-03 by @teoliphant, assigned to unknown._\n\nThe advertised behavior of choose(choices, sequence_of_arrays) is that the choices array and all the arrays in the sequence must be broadcastable to the same shape which is the shape of the output. \n\nHowever, NumPy does not look at the shape of the choices array, only the sequence_of_arrays. \n\nThis requires an adaptation of the code in PyArray_Choose function in C. Probably the easiest thing is to construct a MultiIterator object to handle the broadcasting internal to that function, construct the output, and then fill appropriately.\n\n", "image": {"image_id": "sha256:d485b6f5f151ad2c42c3c32e32f97d01a66e10ed307a21112efd85cb523ef363", "pull_reference": "yutu0814/pyc-case-031-numpy@sha256:d485b6f5f151ad2c42c3c32e32f97d01a66e10ed307a21112efd85cb523ef363"}, "cohort": "python50", "patch": "diff --git a/numpy/core/code_generators/numpy_api_order.txt b/numpy/core/code_generators/numpy_api_order.txt\nindex bebc531..ff629d6 100644\n--- a/numpy/core/code_generators/numpy_api_order.txt\n+++ b/numpy/core/code_generators/numpy_api_order.txt\n@@ -170,3 +170,4 @@ PyArray_SearchsideConverter\n PyArray_CheckAxis\n PyArray_OverflowMultiplyList\n PyArray_CompareString\n+PyArray_MultiIterFromObjects\ndiff --git a/numpy/core/src/arrayobject.c b/numpy/core/src/arrayobject.c\nindex ad3cbc4..f944a49 100644\n--- a/numpy/core/src/arrayobject.c\n+++ b/numpy/core/src/arrayobject.c\n@@ -10790,6 +10790,75 @@ static PyTypeObject PyArrayMapIter_Type = {\n /** END of Subscript Iterator **/\n \n \n+/*\n+ NUMPY_API\n+ Get MultiIterator from array of Python objects and any additional\n+\n+ PyObject **mps -- array of PyObjects \n+ int n - number of PyObjects in the array\n+ int nadd - number of additional arrays to include in the\n+ iterator. \n+\n+ Returns a multi-iterator object.\n+ */\n+static PyObject *\n+PyArray_MultiIterFromObjects(PyObject **mps, int n, int nadd, ...)\n+{\n+ va_list va;\n+ PyArrayMultiIterObject *multi;\n+ PyObject *current;\n+ PyObject *arr;\n+\n+ int i, ntot, err=0;\n+\n+ ntot = n + nadd;\n+ if (ntot < 2 || ntot > NPY_MAXARGS) {\n+ PyErr_Format(PyExc_ValueError,\n+ \"Need between 2 and (%d) \" \\\n+ \"array objects (inclusive).\", NPY_MAXARGS);\n+ return NULL;\n+ }\n+\n+ multi = _pya_malloc(sizeof(PyArrayMultiIterObject));\n+ if (multi == NULL) return PyErr_NoMemory();\n+ PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type);\n+\n+ for(i=0; iiters[i] = NULL;\n+ multi->numiter = ntot;\n+ multi->index = 0;\n+\n+ va_start(va, nadd);\n+ for(i=0; iiters[i] = (PyArrayIterObject *)PyArray_IterNew(arr);\n+ Py_DECREF(arr);\n+ }\n+ }\n+\n+ va_end(va);\n+\n+ if (!err && PyArray_Broadcast(multi) < 0) err=1;\n+\n+ if (err) {\n+ Py_DECREF(multi);\n+ return NULL;\n+ }\n+\n+ PyArray_MultiIter_RESET(multi);\n+\n+ return (PyObject *)multi; \n+}\n+\n /*NUMPY_API\n Get MultiIterator,\n */\ndiff --git a/numpy/core/src/multiarraymodule.c b/numpy/core/src/multiarraymodule.c\nindex 022d6f1..e3e84fd 100644\n--- a/numpy/core/src/multiarraymodule.c\n+++ b/numpy/core/src/multiarraymodule.c\n@@ -2326,50 +2326,40 @@ static PyObject *\n PyArray_Choose(PyArrayObject *ip, PyObject *op, PyArrayObject *ret,\n NPY_CLIPMODE clipmode)\n {\n- intp *sizes, offset;\n int n, elsize;\n intp i, m;\n char *ret_data;\n PyArrayObject **mps, *ap;\n- intp *self_data, mi;\n+ PyArrayMultiIterObject *multi=NULL;\n+ intp mi;\n int copyret=0;\n ap = NULL;\n \n /* Convert all inputs to arrays of a common type */\n+ /* Also makes them C-contiguous */\n mps = PyArray_ConvertToCommonType(op, &n);\n if (mps == NULL) return NULL;\n \n- sizes = (intp *)_pya_malloc(n*sizeof(intp));\n- if (sizes == NULL) goto fail;\n-\n- ap = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)ip,\n- PyArray_INTP,\n- 0, 0);\n- if (ap == NULL) goto fail;\n-\n- /* Check the dimensions of the arrays */\n for(i=0; ind < mps[i]->nd) {\n- PyErr_SetString(PyExc_ValueError,\n- \"too many dimensions\");\n- goto fail;\n- }\n- if (!PyArray_CompareLists(ap->dimensions+(ap->nd-mps[i]->nd),\n- mps[i]->dimensions, mps[i]->nd)) {\n- PyErr_SetString(PyExc_ValueError,\n- \"array dimensions must agree\");\n- goto fail;\n- }\n- sizes[i] = PyArray_NBYTES(mps[i]);\n }\n \n+ ap = (PyArrayObject *)PyArray_FROM_OT((PyObject *)ip, NPY_INTP);\n+\n+ if (ap == NULL) goto fail;\n+\n+ /* Broadcast all arrays to each other, index array at the end. */ \n+ multi = (PyArrayMultiIterObject *)\\\n+\tPyArray_MultiIterFromObjects((PyObject **)mps, n, 1, ap);\n+ if (multi == NULL) goto fail;\n+\n+ /* Set-up return array */\n if (!ret) {\n Py_INCREF(mps[0]->descr);\n ret = (PyArrayObject *)PyArray_NewFromDescr(ap->ob_type,\n mps[0]->descr,\n- ap->nd,\n- ap->dimensions,\n+ multi->nd,\n+ multi->dimensions,\n NULL, NULL, 0,\n (PyObject *)ap);\n }\n@@ -2377,8 +2367,10 @@ PyArray_Choose(PyArrayObject *ip, PyObject *op, PyArrayObject *ret,\n PyArrayObject *obj;\n int flags = NPY_CARRAY | NPY_UPDATEIFCOPY | NPY_FORCECAST;\n \n- if (PyArray_SIZE(ret) != PyArray_SIZE(ap)) {\n- PyErr_SetString(PyExc_TypeError,\n+ if ((PyArray_NDIM(ret) != multi->nd) || \n+\t !PyArray_CompareLists(PyArray_DIMS(ret), multi->dimensions, \n+\t\t\t\t multi->nd)) {\n+\t PyErr_SetString(PyExc_TypeError,\n \"invalid shape for output array.\");\n ret = NULL;\n goto fail;\n@@ -2399,12 +2391,10 @@ PyArray_Choose(PyArrayObject *ip, PyObject *op, PyArrayObject *ret,\n \n if (ret == NULL) goto fail;\n elsize = ret->descr->elsize;\n- m = PyArray_SIZE(ret);\n- self_data = (intp *)ap->data;\n ret_data = ret->data;\n \n- for (i=0; i= n) {\n switch(clipmode) {\n case NPY_RAISE:\n@@ -2426,17 +2416,16 @@ PyArray_Choose(PyArrayObject *ip, PyObject *op, PyArrayObject *ret,\n break;\n }\n }\n- offset = i*elsize;\n- if (offset >= sizes[mi]) {offset = offset % sizes[mi]; }\n- memmove(ret_data, mps[mi]->data+offset, elsize);\n- ret_data += elsize; self_data++;\n+ memmove(ret_data, PyArray_MultiIter_DATA(multi, mi), elsize);\n+ ret_data += elsize; \n+\tPyArray_MultiIter_NEXT(multi);\n }\n \n PyArray_INCREF(ret);\n+ Py_DECREF(multi);\n for(i=0; ibase;\n@@ -2447,10 +2436,10 @@ PyArray_Choose(PyArrayObject *ip, PyObject *op, PyArrayObject *ret,\n return (PyObject *)ret;\n \n fail:\n+ Py_XDECREF(multi);\n for(i=0; i 0) {\n+ /* Copy tout[0] to t, and count how many times it occurs. */\n+ t = tout[0];\n+ t0count = 1;\n+ while ((t0count < ntimes) && (tout[t0count] == t)) {\n+ ++t0count;\n+ }\n+ }\n \n /* Setup array to hold the output evaluations*/\n ap_yout= (PyArrayObject *) PyArray_SimpleNew(2,dims,NPY_DOUBLE);\n@@ -599,9 +609,13 @@ odepack_odeint(PyObject *dummy, PyObject *args, PyObject *kwdict)\n goto fail;\n }\n yout = (double *) PyArray_DATA(ap_yout);\n- /* Copy initial vector into first row of output */\n- memcpy(yout, y, neq*sizeof(double)); /* copy initial value to output */\n- yout_ptr = yout + neq; /* set output pointer to next position */\n+\n+ /* Copy initial vector into first row(s) of output */\n+ yout_ptr = yout;\n+ for (k = 0; k < t0count; ++k) {\n+ memcpy(yout_ptr, y, neq*sizeof(double));\n+ yout_ptr += neq;\n+ }\n \n itol = setup_extra_inputs(&ap_rtol, o_rtol, &ap_atol, o_atol, &ap_tcrit,\n o_tcrit, &numcrit, neq);\n@@ -643,7 +657,7 @@ odepack_odeint(PyObject *dummy, PyObject *args, PyObject *kwdict)\n iopt = 1;\n }\n istate = 1;\n- k = 1;\n+ k = t0count;\n \n /* If full output make some useful output arrays */\n if (full_output) {\ndiff --git a/scipy/integrate/odepack.py b/scipy/integrate/odepack.py\nindex 2f0d25b..ccfde88 100644\n--- a/scipy/integrate/odepack.py\n+++ b/scipy/integrate/odepack.py\n@@ -3,10 +3,12 @@ from __future__ import division, print_function, absolute_import\n \n __all__ = ['odeint']\n \n+import numpy as np\n from . import _odepack\n from copy import copy\n import warnings\n \n+\n class ODEintWarning(Warning):\n pass\n \n@@ -61,6 +63,8 @@ def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0,\n t : array\n A sequence of time points for which to solve for y. The initial\n value point should be the first element of this sequence.\n+ This sequence must be monotonically increasing or monotonically\n+ decreasing; repeated values are allowed.\n args : tuple, optional\n Extra arguments to pass to function.\n Dfun : callable(y, t, ...) or callable(t, y, ...)\n@@ -225,6 +229,13 @@ def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0,\n ml = -1 # changed to zero inside function call\n if mu is None:\n mu = -1 # changed to zero inside function call\n+\n+ dt = np.diff(t)\n+ if not((dt >= 0).all() or (dt <= 0).all()):\n+ raise ValueError(\"The values in t must be monotonically increasing \"\n+ \"or monotonically decreasing; repeated values are \"\n+ \"allowed.\")\n+\n t = copy(t)\n y0 = copy(y0)\n output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,\n", "test_patch": "diff --git a/scipy/integrate/tests/test_integrate.py b/scipy/integrate/tests/test_integrate.py\nindex aa8620e..22d5bba 100644\n--- a/scipy/integrate/tests/test_integrate.py\n+++ b/scipy/integrate/tests/test_integrate.py\n@@ -805,3 +805,31 @@ def test_odeint_bad_shapes():\n # shape of array returned by badjac(x, t) is not correct.\n assert_raises(RuntimeError, odeint, sys1, [10, 10], [0, 1], Dfun=badjac)\n \n+\n+def test_repeated_t_values():\n+ \"\"\"Regression test for gh-8217.\"\"\"\n+\n+ def func(x, t):\n+ return -0.25*x\n+\n+ t = np.zeros(10)\n+ sol = odeint(func, [1.], t)\n+ assert_array_equal(sol, np.ones((len(t), 1)))\n+\n+ tau = 4*np.log(2)\n+ t = [0]*9 + [tau, 2*tau, 2*tau, 3*tau]\n+ sol = odeint(func, [1, 2], t, rtol=1e-12, atol=1e-12)\n+ expected_sol = np.array([[1.0, 2.0]]*9 +\n+ [[0.5, 1.0],\n+ [0.25, 0.5],\n+ [0.25, 0.5],\n+ [0.125, 0.25]])\n+ assert_allclose(sol, expected_sol)\n+\n+ # Edge case: empty t sequence.\n+ sol = odeint(func, [1.], [])\n+ assert_array_equal(sol, np.array([], dtype=np.float64).reshape((0, 1)))\n+\n+ # t values are not monotonic.\n+ assert_raises(ValueError, odeint, func, [1.], [0, 1, 0.5, 0])\n+ assert_raises(ValueError, odeint, func, [1, 2, 3], [0, -1, -2, 3])\n", "FAIL_TO_PASS": ["scipy/integrate/tests/test_integrate.py::test_repeated_t_values"], "PASS_TO_PASS": ["scipy/integrate/tests/test_integrate.py::test_odeint_trivial_time", "scipy/integrate/tests/test_integrate.py::test_odeint_bad_shapes"]} +{"instance_id": "clb-pyc-037", "repo": "scipy/scipy", "base_commit": "bf05e8d3412e2d96ab6735b6935e2a65f2620c30", "problem_statement": "scipy.ndimage.label crash on 64-bit linux (Trac #742)\n_Original ticket http://projects.scipy.org/scipy/ticket/742 on 2008-09-23 by trac user usovalx, assigned to unknown._\n\nIt appears that ndimage.label is bugged for 64-bit linux builds. So far I was able to trigger the bug by using reasonably large 3-d datasets. Sample code:\n# \n\nfrom numpy import *\nimport scipy.ndimage as nd\n\nshape=(3, 1000, 1000)\na = random.rand(product(shape)).reshape(shape)\nm = a > .7\n# nd.label(m, nd.generate_binary_structure(3,3))\n\nThis code works fine on 32-bit machines, but crashes with \"segmentation fault python\" on 64-bit fedora & debian. Both 0.6.0 and (current) trunk versions crash.\n\n", "image": {"image_id": "sha256:04dff5e59cea830266f4137be5ca38e2333c9668c2880e6f6f542c7188cd8328", "pull_reference": "yutu0814/pyc-case-037-scipy@sha256:04dff5e59cea830266f4137be5ca38e2333c9668c2880e6f6f542c7188cd8328"}, "cohort": "python50", "patch": "diff --git a/scipy/ndimage/src/ni_measure.c b/scipy/ndimage/src/ni_measure.c\nindex cfd4d4d..1aa27d9 100644\n--- a/scipy/ndimage/src/ni_measure.c\n+++ b/scipy/ndimage/src/ni_measure.c\n@@ -132,7 +132,7 @@ int NI_Label(PyArrayObject* input, PyArrayObject* strct,\n Int32 neighbor = 0;\n /* iterate over structuring element: */\n for(ll = 0; ll < filter_size; ll++) {\n- int offset = oo[ll];\n+ npy_intp offset = oo[ll];\n if (offset != mask_value) {\n Int32 tt = *(Int32*)(po + offset);\n if (tt > 0) {\n", "test_patch": "diff --git a/scipy/ndimage/tests/test_regression.py b/scipy/ndimage/tests/test_regression.py\nindex a824679..28d7553 100644\n--- a/scipy/ndimage/tests/test_regression.py\n+++ b/scipy/ndimage/tests/test_regression.py\n@@ -16,5 +16,19 @@ def test_zoom_output_shape():\n x = np.arange(12).reshape((3,4))\n ndimage.zoom(x, 2, output=np.zeros((6,8)))\n \n+def test_ticket_742():\n+ def SE(img, thresh=.7, size=4):\n+ mask = img > thresh\n+ rank = len(mask.shape)\n+ la, co = ndimage.label(mask,\n+ ndimage.generate_binary_structure(rank, rank))\n+ slices = ndimage.find_objects(la)\n+\n+ if np.dtype(np.intp) != np.dtype('i'):\n+ shape=(3,1240,1240)\n+ a = np.random.rand(np.product(shape)).reshape(shape)\n+ # shouldn't crash\n+ SE(a)\n+\n if __name__ == \"__main__\":\n run_module_suite()\n", "FAIL_TO_PASS": ["scipy/ndimage/tests/test_regression.py::test_ticket_742"], "PASS_TO_PASS": ["scipy/ndimage/tests/test_regression.py::test_byte_order_median", "scipy/ndimage/tests/test_regression.py::test_zoom_output_shape"]} +{"instance_id": "clb-pyc-041", "repo": "scipy/scipy", "base_commit": "e13278e712ac33c6110b5d48a8da0acfa7768b71", "problem_statement": "Crash of interpolate.splprep(task=-1)\nRunning the circle example but with task = -1 parameter for splprep\nhttp://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html#spline-interpolation-in-1-d-procedural-interpolate-splxxx\n\nI got a crash in firpack.py at \n t,c,o = _fitpack._parcur(ravel(transpose(x)),w,u,ub,ue,k,task,ipar,s,t, nest,wrk,iwrk,per)\n\nHere is my code:\n\n``` python\nfrom scipy import interpolate\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\"\"\" tutorial example \"\"\"\nt = np.arange(0, 1.1, .1)\nx = np.sin(2*np.pi*t)\ny = np.cos(2*np.pi*t)\ntck,u = interpolate.splprep([x,y], s=0)\nunew = np.arange(0, 1.01, 0.01)\nout = interpolate.splev(unew, tck)\nplt.figure()\nplt.plot(x, y, 'x', out[0], out[1], np.sin(2*np.pi*unew), np.cos(2*np.pi*unew), x, y, 'b')\nplt.legend(['Linear', 'Cubic Spline', 'True'])\nplt.axis([-1.05, 1.05, -1.05, 1.05])\nplt.title('Spline of parametrically-defined curve')\nplt.show()\n\n\"\"\"test with splprep(task=-1) \"\"\"\nuknots = tck[0] # using the knots from the previous fitting\ntck,u = interpolate.splprep([x,y], task=-1, t=uknots) # here is the crash\nplt.figure()\nplt.plot(x, y, 'x', out[0], out[1], np.sin(2*np.pi*unew), np.cos(2*np.pi*unew), x, y, 'b')\nplt.legend(['Linear', 'Cubic Spline', 'True'])\nplt.axis([-1.05, 1.05, -1.05, 1.05])\nplt.title('Spline of parametrically-defined curve')\nplt.show()\n```\n\nHere are the parameters for _fitpack._parcur:\n1) in the first case\n\n```\n[ 0.00000000e+00 1.00000000e+00 5.87785252e-01 8.09016994e-01\n 9.51056516e-01 3.09016994e-01 9.51056516e-01 -3.09016994e-01\n 5.87785252e-01 -8.09016994e-01 1.22464680e-16 -1.00000000e+00\n -5.87785252e-01 -8.09016994e-01 -9.51056516e-01 -3.09016994e-01\n -9.51056516e-01 3.09016994e-01 -5.87785252e-01 8.09016994e-01\n -2.44929360e-16 1.00000000e+00] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] 0 1 3 0 False 0 [] 15 [] [] 0\n```\n\n2) in the second case (task =-1)\n\n```\n[ 0.00000000e+00 1.00000000e+00 5.87785252e-01 8.09016994e-01\n 9.51056516e-01 3.09016994e-01 9.51056516e-01 -3.09016994e-01\n 5.87785252e-01 -8.09016994e-01 1.22464680e-16 -1.00000000e+00\n -5.87785252e-01 -8.09016994e-01 -9.51056516e-01 -3.09016994e-01\n -9.51056516e-01 3.09016994e-01 -5.87785252e-01 8.09016994e-01\n -2.44929360e-16 1.00000000e+00] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] 0 1 3 -1 False 6.30958424018 [ 0. 0. 0. 0. 0.2 0.3 0.4 0.5 0.6 0.7 0.8 1. 1. 1. 1. ] 17 [] [] 0\n```\n\nI'm, using scipy '0.14.0'.\n\nsplprep segfaults if fixed knots are specified\ninterpolate.splprep causes random python segfault if task=-1 and fixed knots are specified, apparently near _fitpack._parcur call.\r\n\r\n### Reproducing code example:\r\n```\r\nimport numpy as np\r\nfrom scipy.interpolate import splprep\r\nN = 1000\r\nx = np.arange(N)\r\n# Sinusoid 0-100\r\ny = 100*np.sin(x/30.)\r\n# Add 0-10 random noise\r\ny += np.random.randint(0,10,N)\r\nu = np.arange(N)\r\n# Free knots\r\nresp = splprep([x, y], full_output=True, task=0, k=3, s=15000., u=u)\r\n(tck, u1), err, ier, msg = resp\r\n# Use the obtained knots as fixed:\r\nresp = splprep([x, y], full_output=True, task=-1, k=3, u=u, t=tck[0])\r\n(tck, u1), err, ier, msg = resp\r\n```\r\nIf it does not fail immediately, it will if you repeat the calculation in a for loop (eg: 10 times). The behaviour seems quite random.\r\nMore detailed explanation here:\r\nhttps://gist.github.com/mythsmith/9951a8d04092bd11aadbd8a4ef680e22\r\n\r\n### Error message:\r\n```\r\n*** Error in `python': free(): invalid pointer: .... ****\r\n```\r\n\r\n### Scipy/Numpy/Python version information:\r\nBoth:\r\n```\r\n0.18.1 1.11.3 sys.version_info(major=3, minor=6, micro=0, releaselevel='final', serial=0)\r\n'0.17.1', '1.11.1', sys.version_info(major=2, minor=7, micro=13, releaselevel='final', serial=0)\r\n```\r\nThe first one was on my local Anaconda3 installation. The second on SageMathCloud.\r\n\r\n\n", "image": {"image_id": "sha256:162ec26dfa62fdd3ffa1a0dc4976961257e6796f803eb39e11be871f1dc4faf9", "pull_reference": "yutu0814/pyc-case-041-scipy@sha256:162ec26dfa62fdd3ffa1a0dc4976961257e6796f803eb39e11be871f1dc4faf9"}, "cohort": "python50", "patch": "diff --git a/scipy/interpolate/src/_fitpackmodule.c b/scipy/interpolate/src/_fitpackmodule.c\nindex 52cd383..ba44a49 100644\n--- a/scipy/interpolate/src/_fitpackmodule.c\n+++ b/scipy/interpolate/src/_fitpackmodule.c\n@@ -499,7 +499,7 @@ fitpack_parcur(PyObject *dummy, PyObject *args)\n if (ap_t == NULL || ap_c == NULL) {\n goto fail;\n }\n- if (iopt == 0|| n > no) {\n+ if (iopt != 1|| n > no) {\n Py_XDECREF(ap_wrk);\n ap_wrk = NULL;\n Py_XDECREF(ap_iwrk);\n", "test_patch": "diff --git a/scipy/interpolate/tests/test_fitpack.py b/scipy/interpolate/tests/test_fitpack.py\nindex 7b90c36..c2179a4 100644\n--- a/scipy/interpolate/tests/test_fitpack.py\n+++ b/scipy/interpolate/tests/test_fitpack.py\n@@ -459,6 +459,19 @@ def test_splev_der_k():\n assert_allclose(splev(x, (t, c, k), k), splev(x, tck2))\n \n \n+def test_splprep_segfault():\n+ # regression test for gh-3847: splprep segfaults if knots are specified\n+ # for task=-1\n+ t = np.arange(0, 1.1, 0.1)\n+ x = np.sin(2*np.pi*t)\n+ y = np.cos(2*np.pi*t)\n+ tck, u = interpolate.splprep([x, y], s=0)\n+ unew = np.arange(0, 1.01, 0.01)\n+\n+ uknots = tck[0] # using the knots from the previous fitting\n+ tck, u = interpolate.splprep([x, y], task=-1, t=uknots) # here is the crash\n+\n+\n def test_bisplev_integer_overflow():\n np.random.seed(1)\n \n", "FAIL_TO_PASS": ["scipy/interpolate/tests/test_fitpack.py::test_splprep_segfault"], "PASS_TO_PASS": ["scipy/interpolate/tests/test_fitpack.py::test_dblint", "scipy/interpolate/tests/test_fitpack.py::test_splev_der_k"]} +{"instance_id": "clb-pyc-042", "repo": "scipy/scipy", "base_commit": "8c7973148c5dea4a28e0e082f8c1f182313b72c1", "problem_statement": "scipy.signal.sepfir2d reads random memory when given even sized hrow or hcol\n`scipy.signal.sepfir2d` reads random memory when given even sized `hrow` or `hcol`. Deep down in the source code for `sepfir2` there is a comment than only odd-lengths are acceptable:\r\nhttps://github.com/scipy/scipy/blob/d06791710acae119e099829087f8e1aedc4e1bd7/scipy/signal/S_bspline_util.c#L173\r\nhttps://github.com/scipy/scipy/blob/d06791710acae119e099829087f8e1aedc4e1bd7/scipy/signal/D_bspline_util.c#L177\r\nhttps://github.com/scipy/scipy/blob/d06791710acae119e099829087f8e1aedc4e1bd7/scipy/signal/C_bspline_util.c#L176\r\nhttps://github.com/scipy/scipy/blob/d06791710acae119e099829087f8e1aedc4e1bd7/scipy/signal/Z_bspline_util.c#L173\r\nHowever, this is not documented or enforced in `sepfir2d`.\n", "image": {"image_id": "sha256:73a308a6d0431d6f5d682647daf0828549209bc26bf7e79d2bff7e205d7d2bcb", "pull_reference": "yutu0814/pyc-case-042-scipy@sha256:73a308a6d0431d6f5d682647daf0828549209bc26bf7e79d2bff7e205d7d2bcb"}, "cohort": "python50", "patch": "diff --git a/scipy/signal/splinemodule.c b/scipy/signal/splinemodule.c\nindex 58f1aa7..1c10218 100644\n--- a/scipy/signal/splinemodule.c\n+++ b/scipy/signal/splinemodule.c\n@@ -214,11 +214,13 @@ static char doc_FIRsepsym2d[] = \"out = sepfir2d(input, hrow, hcol)\\n\"\n \" Parameters\\n\"\n \" ----------\\n\"\n \" input : ndarray\\n\"\n-\" The input signal.\\n\"\n+\" The input signal. Must be a rank-2 array.\\n\"\n \" hrow : ndarray\\n\"\n-\" A row direction filter defined by the rank-1 arrays.\\n\"\n+\" A rank-1 array defining the row direction of the filter.\\n\"\n+\" Must be odd-length\\n\"\n \" hcol : ndarray\\n\"\n-\" A column direction filter defined by the rank-1 arrays.\\n\"\n+\" A rank-1 array defining the column direction of the filter.\\n\"\n+\" Must be odd-length\\n\"\n \"\\n\"\n \" Returns\\n\"\n \" -------\\n\"\n@@ -242,13 +244,17 @@ static PyObject *FIRsepsym2d(PyObject *NPY_UNUSED(dummy), PyObject *args)\n thetype = PyArray_ObjectType(image, NPY_FLOAT);\n thetype = PyArray_MIN(thetype, NPY_CDOUBLE);\n a_image = (PyArrayObject *)PyArray_FromObject(image, thetype, 2, 2);\n+ if (a_image == NULL) goto fail;\n+\n a_hrow = (PyArrayObject *)PyArray_ContiguousFromObject(hrow, thetype, 1, 1);\n+ if (a_hrow == NULL) goto fail;\n+\n a_hcol = (PyArrayObject *)PyArray_ContiguousFromObject(hcol, thetype, 1, 1);\n- \n- if ((a_image == NULL) || (a_hrow == NULL) || (a_hcol==NULL)) goto fail;\n+ if (a_hcol == NULL) goto fail;\n \n out = (PyArrayObject *)PyArray_SimpleNew(2, PyArray_DIMS(a_image), thetype);\n if (out == NULL) goto fail;\n+\n M = PyArray_DIMS(a_image)[0];\n N = PyArray_DIMS(a_image)[1];\n \n@@ -256,6 +262,11 @@ static PyObject *FIRsepsym2d(PyObject *NPY_UNUSED(dummy), PyObject *args)\n outstrides[0] = N;\n outstrides[1] = 1;\n \n+ if (PyArray_DIMS(a_hrow)[0] % 2 != 1 ||\n+ PyArray_DIMS(a_hcol)[0] % 2 != 1) {\n+ PYERR(\"hrow and hcol must be odd length\");\n+ }\n+\n switch (thetype) {\n case NPY_FLOAT:\n ret = S_separable_2Dconvolve_mirror((float *)PyArray_DATA(a_image), \n", "test_patch": "diff --git a/scipy/signal/tests/test_bsplines.py b/scipy/signal/tests/test_bsplines.py\nindex 57524eb..4d77918 100644\n--- a/scipy/signal/tests/test_bsplines.py\n+++ b/scipy/signal/tests/test_bsplines.py\n@@ -4,9 +4,11 @@ from numpy import array\n from numpy.testing import (assert_equal,\n assert_allclose, assert_array_equal,\n assert_almost_equal)\n+import pytest\n from pytest import raises\n \n import scipy.signal.bsplines as bsp\n+from scipy import signal\n \n \n class TestBSplines(object):\n@@ -226,3 +228,33 @@ class TestBSplines(object):\n 7.32718426, 7.874, 7.81016848, 7.433, 7.03980488, 6.759,\n 6.71900226, 6.203, 4.49418159])\n assert_allclose(bsp.qspline1d_eval(cj, newx, dx=dx, x0=x[0]), newy)\n+\n+\n+def test_sepfir2d_invalid_filter():\n+ filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0])\n+ image = np.random.rand(7, 9)\n+ # No error for odd lengths\n+ signal.sepfir2d(image, filt, filt[2:])\n+\n+ # Row or column filter must be odd\n+ with pytest.raises(ValueError, match=\"odd length\"):\n+ signal.sepfir2d(image, filt, filt[1:])\n+ with pytest.raises(ValueError, match=\"odd length\"):\n+ signal.sepfir2d(image, filt[1:], filt)\n+\n+ # Filters must be 1-dimensional\n+ with pytest.raises(ValueError, match=\"object too deep\"):\n+ signal.sepfir2d(image, filt.reshape(1, -1), filt)\n+ with pytest.raises(ValueError, match=\"object too deep\"):\n+ signal.sepfir2d(image, filt, filt.reshape(1, -1))\n+\n+def test_sepfir2d_invalid_image():\n+ filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0])\n+ image = np.random.rand(8, 8)\n+\n+ # Image must be 2 dimensional\n+ with pytest.raises(ValueError, match=\"object too deep\"):\n+ signal.sepfir2d(image.reshape(4, 4, 4), filt, filt)\n+\n+ with pytest.raises(ValueError, match=\"object of too small depth\"):\n+ signal.sepfir2d(image[0], filt, filt)\n", "FAIL_TO_PASS": ["scipy/signal/tests/test_bsplines.py::test_sepfir2d_invalid_filter"], "PASS_TO_PASS": ["scipy/signal/tests/test_bsplines.py::TestBSplines::test_spline_filter", "scipy/signal/tests/test_bsplines.py::TestBSplines::test_bspline"]} +{"instance_id": "clb-pyc-044", "repo": "scipy/scipy", "base_commit": "fc6b387bc0c51b5b252712584580b4f0975498fb", "problem_statement": "segfault from map_coordinates\nI received segmentation faults when running `map_coordinates` with `order=1` on a large array when attempting to access data that was past the 4GB level if the input data array type was `float32`. I have verified that changing from `float32` -> `float64` or using `order=3` both avoid the problem. \n\nI suspect these lines in `map_coordinates` should include a coercion to `float64` in the `order <= 1` case:\n\n```\n if prefilter and order > 1:\n filtered = spline_filter(input, order, output=numpy.float64)\n else:\n filtered = input\n```\n\n", "image": {"image_id": "sha256:46e9a7fa9636a89717b530dbde3a6da3e2c67050a18b70847b78b4316e051831", "pull_reference": "yutu0814/pyc-case-044-scipy@sha256:46e9a7fa9636a89717b530dbde3a6da3e2c67050a18b70847b78b4316e051831"}, "cohort": "python50", "patch": "diff --git a/scipy/ndimage/src/ni_filters.c b/scipy/ndimage/src/ni_filters.c\nindex 96c2e799..c5e70562 100644\n--- a/scipy/ndimage/src/ni_filters.c\n+++ b/scipy/ndimage/src/ni_filters.c\n@@ -639,9 +639,10 @@ exit:\n return PyErr_Occurred() ? 0 : 1;\n }\n \n-static double NI_Select(double *buffer, int min, int max, int rank)\n+static double NI_Select(double *buffer, npy_intp min,\n+ npy_intp max, npy_intp rank)\n {\n- int ii, jj;\n+ npy_intp ii, jj;\n double x, t;\n \n if (min == max)\ndiff --git a/scipy/ndimage/src/ni_interpolation.c b/scipy/ndimage/src/ni_interpolation.c\nindex bb67b33c..94f2a7ab 100644\n--- a/scipy/ndimage/src/ni_interpolation.c\n+++ b/scipy/ndimage/src/ni_interpolation.c\n@@ -466,7 +466,8 @@ NI_GeometricTransform(PyArrayObject *input, int (*map)(npy_intp*, double*,\n size *= output->dimensions[qq];\n for(kk = 0; kk < size; kk++) {\n double t = 0.0;\n- int constant = 0, edge = 0, offset = 0;\n+ int constant = 0, edge = 0;\n+ npy_intp offset = 0;\n if (map) {\n /* call mappint functions: */\n if (!map(io.coordinates, icoor, orank, irank, map_data)) {\n@@ -513,11 +514,11 @@ NI_GeometricTransform(PyArrayObject *input, int (*map)(npy_intp*, double*,\n double cc = map_coordinate(icoor[hh], idimensions[hh], mode);\n if (cc > -1.0) {\n /* find the filter location along this axis: */\n- int start;\n+ npy_intp start;\n if (order & 1) {\n- start = (int)floor(cc) - order / 2;\n+ start = (npy_intp)floor(cc) - order / 2;\n } else {\n- start = (int)floor(cc + 0.5) - order / 2;\n+ start = (npy_intp)floor(cc + 0.5) - order / 2;\n }\n /* get the offset to the start of the filter: */\n offset += istrides[hh] * start;\n@@ -526,12 +527,12 @@ NI_GeometricTransform(PyArrayObject *input, int (*map)(npy_intp*, double*,\n edge = 1;\n edge_offsets[hh] = data_offsets[hh];\n for(ll = 0; ll <= order; ll++) {\n- int idx = start + ll;\n- int len = idimensions[hh];\n+ npy_intp idx = start + ll;\n+ npy_intp len = idimensions[hh];\n if (len <= 1) {\n idx = 0;\n } else {\n- int s2 = 2 * len - 2;\n+ npy_intp s2 = 2 * len - 2;\n if (idx < 0) {\n idx = s2 * (int)(-idx / s2) + idx;\n idx = idx <= 1 - len ? idx + s2 : -idx;\n@@ -562,7 +563,7 @@ NI_GeometricTransform(PyArrayObject *input, int (*map)(npy_intp*, double*,\n t = 0.0;\n for(hh = 0; hh < filter_size; hh++) {\n double coeff = 0.0;\n- int idx = 0;\n+ npy_intp idx = 0;\n \n if (NI_UNLIKELY(edge)) {\n for(ll = 0; ll < irank; ll++) {\n@@ -739,13 +740,13 @@ int NI_ZoomShift(PyArrayObject *input, PyArrayObject* zoom_ar,\n cc *= zoom;\n cc = map_coordinate(cc, idimensions[jj], mode);\n if (cc > -1.0) {\n- int start;\n+ npy_intp start;\n if (zeros && zeros[jj])\n zeros[jj][kk] = 0;\n if (order & 1) {\n- start = (int)floor(cc) - order / 2;\n+ start = (npy_intp)floor(cc) - order / 2;\n } else {\n- start = (int)floor(cc + 0.5) - order / 2;\n+ start = (npy_intp)floor(cc + 0.5) - order / 2;\n }\n offsets[jj][kk] = istrides[jj] * start;\n if (start < 0 || start + order >= idimensions[jj]) {\n@@ -755,12 +756,12 @@ int NI_ZoomShift(PyArrayObject *input, PyArrayObject* zoom_ar,\n goto exit;\n }\n for(hh = 0; hh <= order; hh++) {\n- int idx = start + hh;\n- int len = idimensions[jj];\n+ npy_intp idx = start + hh;\n+ npy_intp len = idimensions[jj];\n if (len <= 1) {\n idx = 0;\n } else {\n- int s2 = 2 * len - 2;\n+ npy_intp s2 = 2 * len - 2;\n if (idx < 0) {\n idx = s2 * (int)(-idx / s2) + idx;\n idx = idx <= 1 - len ? idx + s2 : -idx;\n@@ -846,7 +847,7 @@ int NI_ZoomShift(PyArrayObject *input, PyArrayObject* zoom_ar,\n const int type_num = NI_NormalizeType(input->descr->type_num);\n t = 0.0;\n for(hh = 0; hh < filter_size; hh++) {\n- int idx = 0;\n+ npy_intp idx = 0;\n double coeff = 0.0;\n \n if (NI_UNLIKELY(edge)) {\ndiff --git a/scipy/ndimage/src/ni_measure.c b/scipy/ndimage/src/ni_measure.c\nindex dcb34f86..f8ad50d4 100644\n--- a/scipy/ndimage/src/ni_measure.c\n+++ b/scipy/ndimage/src/ni_measure.c\n@@ -564,11 +564,11 @@ int NI_Histogram(PyArrayObject *input, PyArrayObject *labels,\n doit = label != 0;\n }\n if (doit) {\n- int bin;\n+ npy_intp bin;\n double val;\n NI_GET_VALUE(pi, val, NI_NormalizeType(input->descr->type_num));\n if (val >= min && val < max) {\n- bin = (int)((val - min) / bsize);\n+ bin = (npy_intp)((val - min) / bsize);\n ++(ph[idx][bin]);\n }\n }\n@@ -691,7 +691,7 @@ int NI_WatershedIFT(PyArrayObject* input, PyArrayObject* markers,\n /* Initialization and find the maximum of the input. */\n maxval = 0;\n for(jj = 0; jj < size; jj++) {\n- int ival = 0;\n+ npy_intp ival = 0;\n switch(NI_NormalizeType(input->descr->type_num)) {\n CASE_GET_INPUT(ival, pi, UInt8);\n CASE_GET_INPUT(ival, pi, UInt16);\ndiff --git a/scipy/ndimage/src/ni_morphology.c b/scipy/ndimage/src/ni_morphology.c\nindex 787120f2..588fa1a2 100644\n--- a/scipy/ndimage/src/ni_morphology.c\n+++ b/scipy/ndimage/src/ni_morphology.c\n@@ -765,7 +765,7 @@ static void _VoronoiFT(char *pf, npy_intp len, npy_intp *coor, int rank,\n npy_intp **f, npy_intp *g, Float64 *sampling)\n {\n npy_intp l = -1, ii, maxl, idx1, idx2;\n- int jj;\n+ npy_intp jj;\n \n for(ii = 0; ii < len; ii++)\n for(jj = 0; jj < rank; jj++)\n@@ -853,7 +853,7 @@ static void _ComputeFT(char *pi, char *pf, npy_intp *ishape,\n int d, npy_intp *coor, npy_intp **f, npy_intp *g,\n PyArrayObject *features, Float64 *sampling)\n {\n- int kk;\n+ npy_intp kk;\n npy_intp jj;\n \n if (d == 0) {\n", "test_patch": "diff --git a/scipy/ndimage/tests/test_ndimage.py b/scipy/ndimage/tests/test_ndimage.py\nindex bfe9161d..9c505ae7 100644\n--- a/scipy/ndimage/tests/test_ndimage.py\n+++ b/scipy/ndimage/tests/test_ndimage.py\n@@ -32,11 +32,12 @@ from __future__ import division, print_function, absolute_import\n \n import warnings\n import math\n+import sys\n \n import numpy\n from numpy import fft\n from numpy.testing import (assert_, assert_equal, assert_array_equal,\n- run_module_suite, assert_array_almost_equal, assert_almost_equal)\n+ run_module_suite, assert_array_almost_equal, assert_almost_equal, dec)\n import scipy.ndimage as ndimage\n \n \n@@ -1705,6 +1706,16 @@ class TestNdimage:\n assert_array_almost_equal(out, [[0, 0], [0, 4], [0, 7]])\n assert_array_almost_equal(out, ndimage.shift(data[:,::2], (1, 1)))\n \n+ # do not run on 32 bit or windows (no sparse memory)\n+ @dec.skipif('win32' in sys.platform or numpy.intp(0).itemsize < 8)\n+ def test_map_coordinates_large_data(self):\n+ # check crash on large data\n+ n = 30000\n+ a = numpy.empty(n**2, dtype=numpy.float32).reshape(n, n)\n+ # fill the part we might read\n+ a[n - 3:,n - 3:] = 0\n+ ndimage.map_coordinates(a, [[n - 1.5], [n - 1.5]], order=1)\n+\n def test_affine_transform01(self):\n data = numpy.array([1])\n for order in range(0, 6):\n", "FAIL_TO_PASS": ["scipy/ndimage/tests/test_ndimage.py::TestNdimage::test_map_coordinates_large_data"], "PASS_TO_PASS": ["scipy/ndimage/tests/test_ndimage.py::TestNdimage::test_map_coordinates01", "scipy/ndimage/tests/test_ndimage.py::TestNdimage::test_map_coordinates02"]} +{"instance_id": "clb-pyc-046", "repo": "tskit-dev/tskit", "base_commit": "eb8b4aebe42f39f7e536a603e8cd25d9cf104e22", "problem_statement": ".newick() raises: LibraryError: Supplied buffer if too small\nHi all, \r\n\r\nI'm getting a buffer size error when calling `.newick()` on a tree with large Ne. The problem seems to be derived from C code in `._ll_sparse_tree.get_newick()`. I see in the trees.py code that if you provide a `node_labels` argument to `.newick()` it skips the compiled `get_newick()` function and instead uses the Python function `__build_newick()` in trees.py. The latter function works fine, but the C code raises the error. \r\n\r\nYou should be able to recreate the error with the following code which will print the first newick string successfully but raise the `LibraryError` on the second one:\r\n\r\n```python\r\nimport msprime\r\n\r\n# get a tree sequence\r\nts = msprime.simulate(10, Ne=100e6, length=10, random_seed=123)\r\n\r\n# iterate over trees\r\nfor i in ts.trees():\r\n \r\n # this works. It calls Py code under the hood.\r\n nwk1 = i.newick(node_labels={})\r\n print(nwk1)\r\n \r\n # this doesn't work. It call C code under the hood.\r\n nwk2 = i.newick()\r\n```\r\n\r\noutput:\r\n```python\r\n(:288429157.63675111532211,(:172974721.34986978769302,((:73244998.80208450555801,((:8406986.89599480479956,:8406986.89599480479956):12158249.56021711230278,(:14131513.13161224499345,:14131513.13161224499345):6433723.32459967210889):52679762.34587258845568):33927916.07371711730957,(:90580458.18467475473881,(:5298987.32885717041790,:5298987.32885717041790):85281470.85581758618355):16592456.69112686812878):65801806.47406816482544):115454436.28688132762909);\r\n\r\n---------------------------------------------------------------------------\r\nLibraryError Traceback (most recent call last)\r\n in \r\n 10 \r\n 11 # c code\r\n---> 12 nwk2 = i.newick()\r\n\r\n~/miniconda3/envs/py36/lib/python3.6/site-packages/msprime/trees.py in newick(self, precision, root, node_labels)\r\n 1153 root = self.root\r\n 1154 if node_labels is None:\r\n-> 1155 s = self._ll_sparse_tree.get_newick(precision=precision, root=root)\r\n 1156 if not IS_PY2:\r\n 1157 s = s.decode()\r\n\r\nLibraryError: Supplied buffer if too small\r\n```\r\n\r\nI'll use the `node_labels` arg for now as a workaround, but I figured this looks like it is probably a bug. If it helps, I'm using msprime v.0.6.1 in Python 3.6 on Ubuntu. \n", "image": {"image_id": "sha256:94b0040be34ac50a0b340ee284e51a414a4d1efa8696791ae661d0cbeea80743", "pull_reference": "yutu0814/pyc-case-046-tskit@sha256:94b0040be34ac50a0b340ee284e51a414a4d1efa8696791ae661d0cbeea80743"}, "cohort": "python50", "patch": "diff --git a/python/CHANGELOG.rst b/python/CHANGELOG.rst\nindex 60500c9..55d36c7 100644\n--- a/python/CHANGELOG.rst\n+++ b/python/CHANGELOG.rst\n@@ -83,6 +83,9 @@ In development\n \n **Bugfixes**\n \n+- :issue:`453` - Fix LibraryError when ``tree.newick()`` is called with large node time\n+ values (:user:`jeromekelleher`, :pr:`637`).\n+\n **Deprecated**\n \n - The ``sample_counts`` feature has been deprecated and is now\ndiff --git a/python/_tskitmodule.c b/python/_tskitmodule.c\nindex 69afab9..581dd81 100644\n--- a/python/_tskitmodule.c\n+++ b/python/_tskitmodule.c\n@@ -3659,7 +3659,7 @@ MigrationTable_add_row(MigrationTable *self, PyObject *args, PyObject *kwds)\n PyObject *py_metadata = Py_None;\n char *metadata = \"\";\n Py_ssize_t metadata_length = 0;\n- static char *kwlist[] = {\"left\", \"right\", \"node\", \"source\", \"dest\", \n+ static char *kwlist[] = {\"left\", \"right\", \"node\", \"source\", \"dest\",\n \"time\", \"metadata\", NULL};\n \n if (!PyArg_ParseTupleAndKeywords(args, kwds, \"ddiiid|O\", kwlist,\n@@ -9017,34 +9017,35 @@ static PyObject *\n Tree_get_newick(Tree *self, PyObject *args, PyObject *kwds)\n {\n PyObject *ret = NULL;\n- static char *kwlist[] = {\"root\", \"precision\", NULL};\n+ static char *kwlist[] = {\"root\", \"precision\", \"buffer_size\", NULL};\n int precision = 14;\n+ /* We have a default bufsize for convenience, but the high-level code\n+ * should set this by computing an upper bound. */\n+ Py_ssize_t buffer_size = 1024;\n int root, err;\n- size_t buffer_size;\n char *buffer = NULL;\n \n if (Tree_check_tree(self) != 0) {\n goto out;\n }\n- if (!PyArg_ParseTupleAndKeywords(args, kwds, \"i|i\", kwlist, &root, &precision)) {\n+ if (!PyArg_ParseTupleAndKeywords(args, kwds, \"i|in\", kwlist, &root, &precision,\n+ &buffer_size)) {\n goto out;\n }\n if (precision < 0 || precision > 16) {\n PyErr_SetString(PyExc_ValueError, \"Precision must be between 0 and 16, inclusive\");\n goto out;\n }\n- buffer_size = tsk_treeseq_get_num_nodes(self->tree->tree_sequence);\n- /* For every node, we have roughly precision bytes, plus bracketing and leading values.\n- * This is a rough guess, so add 10 just to be on the safe side. We might need\n- * to be more precise with this though if we have large time values.\n- */\n- buffer_size *= precision + 10;\n+ if (buffer_size <= 0) {\n+ PyErr_SetString(PyExc_ValueError, \"Buffer size must be > 0\");\n+ goto out;\n+ }\n buffer = PyMem_Malloc(buffer_size);\n if (buffer == NULL) {\n PyErr_NoMemory();\n }\n err = tsk_convert_newick(self->tree, (tsk_id_t) root, precision, 0,\n- buffer_size, buffer);\n+ (size_t) buffer_size, buffer);\n if (err != 0) {\n handle_library_error(err);\n goto out;\ndiff --git a/python/tskit/trees.py b/python/tskit/trees.py\nindex 028250b..ab1ac08 100644\n--- a/python/tskit/trees.py\n+++ b/python/tskit/trees.py\n@@ -30,6 +30,7 @@ import concurrent.futures\n import functools\n import itertools\n import json\n+import math\n import textwrap\n import warnings\n from typing import Any\n@@ -2045,7 +2046,16 @@ class Tree:\n )\n root = self.root\n if node_labels is None:\n- s = self._ll_tree.get_newick(precision=precision, root=root)\n+ # This should be a safe over-estimate.\n+ root_time = max(1, self.time(root))\n+ max_label_size = math.ceil(math.log10(self.tree_sequence.num_nodes))\n+ single_node_size = (\n+ 3 + max_label_size + math.ceil(math.log10(root_time)) + precision\n+ )\n+ buffer_size = single_node_size * self.num_nodes\n+ s = self._ll_tree.get_newick(\n+ precision=precision, root=root, buffer_size=buffer_size\n+ )\n s = s.decode()\n else:\n return self.__build_newick(root, precision, node_labels) + \";\"\n", "test_patch": "diff --git a/python/tests/test_highlevel.py b/python/tests/test_highlevel.py\nindex e76bb98..1014aa9 100644\n--- a/python/tests/test_highlevel.py\n+++ b/python/tests/test_highlevel.py\n@@ -1887,6 +1887,18 @@ class TestTree(HighLevelTestCase):\n for tree in ts.trees():\n self.verify_newick(tree)\n \n+ def test_newick_large_times(self):\n+ for n in [2, 10, 20, 100]:\n+ ts = msprime.simulate(n, Ne=100e6, random_seed=1)\n+ tree = ts.first()\n+ for precision in [0, 1, 16]:\n+ newick_py = tree.newick(\n+ node_labels={u: str(u + 1) for u in ts.samples()},\n+ precision=precision,\n+ )\n+ newick_c = tree.newick(precision=precision)\n+ self.assertEqual(newick_c, newick_py)\n+\n def test_as_dict_of_dicts(self):\n for ts in get_example_tree_sequences():\n tree = next(ts.trees())\ndiff --git a/python/tests/test_lowlevel.py b/python/tests/test_lowlevel.py\nindex 6bbad57..1679212 100644\n--- a/python/tests/test_lowlevel.py\n+++ b/python/tests/test_lowlevel.py\n@@ -1841,10 +1841,15 @@ class TestTree(LowLevelTestCase):\n self.assertEqual(st.get_newick(0), b\"1;\")\n for bad_type in [None, \"\", [], {}]:\n self.assertRaises(TypeError, st.get_newick, precision=bad_type)\n- self.assertRaises(TypeError, st.get_newick, ts, time_scale=bad_type)\n+ self.assertRaises(TypeError, st.get_newick, ts, buffer_size=bad_type)\n while st.next():\n- newick = st.get_newick(st.get_left_root())\n+ u = st.get_left_root()\n+ newick = st.get_newick(u)\n self.assertTrue(newick.endswith(b\";\"))\n+ with self.assertRaises(ValueError):\n+ st.get_newick(u, buffer_size=-1)\n+ with self.assertRaises(_tskit.LibraryError):\n+ st.get_newick(u, buffer_size=1)\n \n def test_index(self):\n for ts in self.get_example_tree_sequences():\n", "FAIL_TO_PASS": ["python/tests/test_highlevel.py::TestTree::test_newick_large_times", "python/tests/test_lowlevel.py::TestTree::test_newick_interface"], "PASS_TO_PASS": ["python/tests/test_highlevel.py::TestTree::test_newick", "python/tests/test_lowlevel.py::TestTree::test_newick_precision"]} +{"instance_id": "clb-pyc-048", "repo": "scipy/scipy", "base_commit": "018986cb0260881827c6ef33cd2d804f54e39c85", "problem_statement": "`scipy.signal.{medfilt,medfilt2d}` hit \"Windows fatal exception: access violation\" with SciPy 1.7.0 on Windows\nSince yesterday with the new SciPy 1.7.0 release, CuPy's Windows CI is experiencing the following fatal error (cupy/cupy#5364) and the CI was interrupted.\r\n\r\n#### Reproducing code example:\r\nThe failing tests can be found here:\r\nhttps://github.com/cupy/cupy/blob/4469fae998df33c72ff40ef954cb08b8f0004b18/tests/cupyx_tests/scipy_tests/signal_tests/test_signaltools.py#L250-L281\r\n\r\nThe failure is reproducible only on Windows and **not seen on Linux**.\r\n\r\n#### Error message:\r\n```\r\n01:07:54.763807 STDERR 1188] | Windows fatal exception: access violation |  \r\n01:07:54.763807 STDERR 1188] |   |  \r\n01:07:54.763807 STDERR 1188] | Current thread 0x0000121c (most recent call first): |  \r\n01:07:54.763807 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\scipy\\signal\\signaltools.py\", line 1538 in medfilt |  \r\n01:07:54.763807 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\scipy\\signal\\signaltools.py\", line 1851 in medfilt2d |  \r\n01:07:54.763807 STDERR 1188] | File \"C:\\Windows\\TEMP\\flexci\\run-00151477\\work\\src\\tests\\cupyx_tests\\scipy_tests\\signal_tests\\test_signaltools.py\", line 281 in test_medfilt2d |  \r\n01:07:54.763807 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\cupy\\testing\\_helper.py\", line 47 in _call_func |  \r\n01:07:54.763807 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\cupy\\testing\\_helper.py\", line 90 in _call_func_numpy |  \r\n01:07:54.763807 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\cupy\\testing\\_helper.py\", line 101 in _call_func_numpy_cupy |  \r\n01:07:54.763807 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\cupy\\testing\\_helper.py\", line 265 in test_func |  \r\n01:07:54.763807 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\cupy\\testing\\_helper.py\", line 825 in test_func |  \r\n01:07:54.764804 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\unittest\\case.py\", line 615 in run |  \r\n01:07:54.764804 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\unittest\\case.py\", line 663 in __call__ |  \r\n01:07:54.764804 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\unittest.py\", line 321 in runtest |  \r\n01:07:54.764804 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\runner.py\", line 162 in pytest_runtest_call |  \r\n01:07:54.765777 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\callers.py\", line 187 in _multicall |  \r\n01:07:54.765777 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\manager.py\", line 87 in <lambda> |  \r\n01:07:54.765777 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\manager.py\", line 93 in _hookexec |  \r\n01:07:54.765777 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\hooks.py\", line 286 in __call__ |  \r\n01:07:54.765777 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\runner.py\", line 255 in <lambda> |  \r\n01:07:54.769663 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\runner.py\", line 311 in from_call |  \r\n01:07:54.769663 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\runner.py\", line 255 in call_runtest_hook |  \r\n01:07:54.769663 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\runner.py\", line 215 in call_and_report |  \r\n01:07:54.769663 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\runner.py\", line 126 in runtestprotocol |  \r\n01:07:54.769663 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\runner.py\", line 109 in pytest_runtest_protocol |  \r\n01:07:54.769663 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\callers.py\", line 187 in _multicall |  \r\n01:07:54.769663 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\manager.py\", line 87 in <lambda> |  \r\n01:07:54.769663 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\manager.py\", line 93 in _hookexec |  \r\n01:07:54.769663 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\hooks.py\", line 286 in __call__ |  \r\n01:07:54.769663 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\main.py\", line 348 in pytest_runtestloop |  \r\n01:07:54.769663 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\callers.py\", line 187 in _multicall |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\manager.py\", line 87 in <lambda> |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\manager.py\", line 93 in _hookexec |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\hooks.py\", line 286 in __call__ |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\main.py\", line 323 in _main |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\main.py\", line 269 in wrap_session |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\main.py\", line 316 in pytest_cmdline_main |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\callers.py\", line 187 in _multicall |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\manager.py\", line 87 in <lambda> |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\manager.py\", line 93 in _hookexec |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pluggy\\hooks.py\", line 286 in __call__ |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\config\\__init__.py\", line 163 in main |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\_pytest\\config\\__init__.py\", line 185 in console_main |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\site-packages\\pytest\\__main__.py\", line 5 in <module> |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\runpy.py\", line 85 in _run_code |  \r\n01:07:54.781377 STDERR 1188] | File \"C:\\Development\\Python\\Python37\\lib\\runpy.py\", line 193 in _run_module_as_main | 12s\r\n01:08:06.784203 STDOUT 1188] | Last 10 lines from the test output: |  \r\n01:08:06.812846 STDOUT 1188] | ........................................................................ [ 75%] |  \r\n01:08:06.814324 STDOUT 1188] | ........................................................................ [ 75%] |  \r\n01:08:06.814324 STDOUT 1188] | ........................................................................ [ 75%] |  \r\n01:08:06.814604 STDOUT 1188] | ........................................................................ [ 75%] |  \r\n01:08:06.814604 STDOUT 1188] | ........................................................................ [ 75%] |  \r\n01:08:06.814604 STDOUT 1188] | ........................................................................ [ 76%] |  \r\n01:08:06.814604 STDOUT 1188] | ........................................................................ [ 76%] |  \r\n01:08:06.814604 STDOUT 1188] | ........................................................................ [ 76%] |  \r\n01:08:06.814604 STDOUT 1188] | ........................................................................ [ 76%] |  \r\n01:08:06.814604 STDOUT 1188] | ............FFFF....FFFF\r\n```\r\n\r\n#### Scipy/Numpy/Python version information:\r\nPython: 3.7.2\r\nNumPy: 1.20.3\r\nSciPy: 1.7.0\r\n\r\ncc: @kmaehashi @emcastillo\n", "image": {"image_id": "sha256:064bfb4045a30796b74a723138efe20e24f2be4e0aa19f4ef6a3a644cce2ce85", "pull_reference": "yutu0814/pyc-case-048-scipy@sha256:064bfb4045a30796b74a723138efe20e24f2be4e0aa19f4ef6a3a644cce2ce85"}, "cohort": "python50", "patch": "diff --git a/scipy/signal/sigtoolsmodule.c b/scipy/signal/sigtoolsmodule.c\nindex e39e0c15..2fd6fcf4 100644\n--- a/scipy/signal/sigtoolsmodule.c\n+++ b/scipy/signal/sigtoolsmodule.c\n@@ -856,14 +856,14 @@ PyObject *PyArray_OrderFilterND(PyObject *op1, PyObject *op2, int order) {\n \tint is1, os;\n \tchar *op, *ap1_ptr, *ap2_ptr, *sort_buffer=NULL;\n \tnpy_intp *ret_ind=NULL;\n-\tCompareFunction compare_func;\n+\tCompareFunction compare_func=NULL;\n \tchar *zptr=NULL;\n \tPyArray_CopySwapFunc *copyswap;\n \n \t/* Get Array objects from input */\n-\ttypenum = PyArray_ObjectType(op1, 0); \n+\ttypenum = PyArray_ObjectType(op1, 0);\n \ttypenum = PyArray_ObjectType(op2, typenum);\n-\t\n+\n \tap1 = (PyArrayObject *)PyArray_ContiguousFromObject(op1, typenum, 0, 0);\n \tif (ap1 == NULL) return NULL;\n \tap2 = (PyArrayObject *)PyArray_ContiguousFromObject(op2, typenum, 0, 0);\n@@ -894,21 +894,23 @@ PyObject *PyArray_OrderFilterND(PyObject *op1, PyObject *op2, int order) {\n \"Order must be non-negative and less than number of nonzero elements in domain.\");\n \t goto fail;\n \t}\n-\t\n+\n \tret = (PyArrayObject *)PyArray_SimpleNew(PyArray_NDIM(ap1),\n PyArray_DIMS(ap1),\n typenum);\n \tif (ret == NULL) goto fail;\n-\t\n-\tcompare_func = compare_functions[PyArray_TYPE(ap1)];\n+\n+\tif (PyArray_TYPE(ap1) < sizeof(compare_functions) / sizeof(compare_functions[0])) {\n+\t compare_func = compare_functions[PyArray_TYPE(ap1)];\n+\t}\n \tif (compare_func == NULL) {\n-\t PyErr_SetString(PyExc_ValueError, \n- \"order_filterND not available for this type\");\n+\t PyErr_SetString(PyExc_ValueError,\n+ \"order_filterND not available for this type\");\n \t\tgoto fail;\n \t}\n \n \tis1 = PyArray_ITEMSIZE(ap1);\n-\t\n+\n \tif (!(sort_buffer = malloc(n2_nonzero*is1))) goto fail;\n \n \tos = PyArray_ITEMSIZE(ret);\n", "test_patch": "diff --git a/scipy/signal/tests/test_signaltools.py b/scipy/signal/tests/test_signaltools.py\nindex 2b5cc6a0..bd64fcff 100644\n--- a/scipy/signal/tests/test_signaltools.py\n+++ b/scipy/signal/tests/test_signaltools.py\n@@ -1062,6 +1062,17 @@ class TestMedFilt:\n assert_equal(signal.medfilt(in_typed).dtype, dtype)\n assert_equal(signal.medfilt2d(in_typed).dtype, dtype)\n \n+ @pytest.mark.parametrize('dtype', [np.bool_, np.cfloat, np.cdouble,\n+ np.clongdouble, np.float16,])\n+ def test_invalid_dtypes(self, dtype):\n+ in_typed = np.array(self.IN, dtype=dtype)\n+ with pytest.raises(ValueError, match=\"order_filterND\"):\n+ signal.medfilt(in_typed)\n+\n+ with pytest.raises(ValueError, match=\"order_filterND\"):\n+ signal.medfilt2d(in_typed)\n+\n+\n def test_none(self):\n # gh-1651, trac #1124. Ensure this does not segfault.\n with pytest.warns(UserWarning):\n", "FAIL_TO_PASS": ["scipy/signal/tests/test_signaltools.py::TestMedFilt::test_invalid_dtypes[float16]"], "PASS_TO_PASS": ["scipy/signal/tests/test_signaltools.py::TestMedFilt::test_basic", "scipy/signal/tests/test_signaltools.py::TestMedFilt::test_none"]} +{"instance_id": "clb-pyc-049", "repo": "CheetahTemplate3/cheetah3", "base_commit": "c86628cad04edc5167f9a9c8999abc62c6558e7b", "problem_statement": "Calling Template.getVar() with a string beginning with \"$\" crashes\nThe compiled C version of NameMapper does not handle names beginning with \"$\" correctly. Specifically on CentOS 6.10, this command results in a Segmentation fault:\r\n`python -c \"from Cheetah.Template import Template; print(Template(source='blah').getVar('$'))\"`\r\n\r\nI get the same result from both Cheetah 3.1.0 and 3.2.5 on Python 2.7.\r\n\r\nAfter deleting _namemapper.so, the same command produces a traceback:\r\n\r\n```/home/sscadmin/.local/share/virtualenvs/python2.7/lib64/python2.7/site-packages/Cheetah/Compiler.py:1627: UserWarning: \r\nYou don't have the C version of NameMapper installed! I'm disabling Cheetah's useStackFrames option as it is painfully slow with the Python version of NameMapper. You should get a copy of Cheetah with compiled C version of NameMapper.\r\n \"\\nYou don't have the C version of NameMapper installed! \"\r\nTraceback (most recent call last):\r\n File \"\", line 1, in \r\n File \"/home/sscadmin/.local/share/virtualenvs/python2.7/lib64/python2.7/site-packages/Cheetah/Template.py\", line 1446, in getVar\r\n self.searchList(), varName.replace('$', ''), autoCall)\r\n File \"/home/sscadmin/.local/share/virtualenvs/python2.7/lib64/python2.7/site-packages/Cheetah/NameMapper.py\", line 289, in valueFromSearchList\r\n _raiseNotFoundException(key, searchList)\r\n File \"/home/sscadmin/.local/share/virtualenvs/python2.7/lib64/python2.7/site-packages/Cheetah/NameMapper.py\", line 174, in _raiseNotFoundException\r\n raise NotFound(excString)\r\nCheetah.NameMapper.NotFound: cannot find ''\r\n```\n", "image": {"image_id": "sha256:9b8ca8cf610a15b88d144cab71608125a57d9fa61fd9d41664684b023d991629", "pull_reference": "yutu0814/pyc-case-049-cheetah@sha256:9b8ca8cf610a15b88d144cab71608125a57d9fa61fd9d41664684b023d991629"}, "cohort": "python50", "patch": "diff --git a/Cheetah/c/_namemapper.c b/Cheetah/c/_namemapper.c\nindex 6c472b9..15ab99a 100644\n--- a/Cheetah/c/_namemapper.c\n+++ b/Cheetah/c/_namemapper.c\n@@ -268,11 +268,16 @@ static PyObject *namemapper_valueForName(PYARGS)\n \n createNameCopyAndChunks();\n \n- theValue = PyNamemapper_valueForName(obj, nameChunks, numChunks, executeCallables);\n- free(nameCopy);\n- if (wrapInternalNotFoundException(name, obj)) {\n+ if (numChunks <= 0) {\n+ PyErr_SetString(PyExc_ValueError, \"Invalid lookup of empty name\");\n theValue = NULL;\n+ } else {\n+ theValue = PyNamemapper_valueForName(obj, nameChunks, numChunks, executeCallables);\n+ if (wrapInternalNotFoundException(name, obj)) {\n+ theValue = NULL;\n+ }\n }\n+ free(nameCopy);\n return theValue;\n }\n \n@@ -300,6 +305,11 @@ static PyObject *namemapper_valueFromSearchList(PYARGS)\n \n createNameCopyAndChunks();\n \n+ if (numChunks <= 0) {\n+ PyErr_SetString(PyExc_ValueError, \"Invalid lookup of empty name\");\n+ goto done;\n+ }\n+\n iterator = PyObject_GetIter(searchList);\n if (iterator == NULL) {\n PyErr_SetString(PyExc_TypeError,\"This searchList is not iterable!\");\n@@ -355,6 +365,11 @@ static PyObject *namemapper_valueFromFrameOrSearchList(PyObject *self, PyObject\n \n createNameCopyAndChunks();\n \n+ if (numChunks <= 0) {\n+ PyErr_SetString(PyExc_ValueError, \"Invalid lookup of empty name\");\n+ goto done;\n+ }\n+\n nameSpace = PyEval_GetLocals();\n checkForNameInNameSpaceAndReturnIfFound(FALSE);\n \n@@ -418,6 +433,11 @@ static PyObject *namemapper_valueFromFrame(PyObject *self, PyObject *args, PyObj\n \n createNameCopyAndChunks();\n \n+ if (numChunks <= 0) {\n+ PyErr_SetString(PyExc_ValueError, \"Invalid lookup of empty name\");\n+ goto done;\n+ }\n+\n nameSpace = PyEval_GetLocals();\n checkForNameInNameSpaceAndReturnIfFound(FALSE);\n \n", "test_patch": "diff --git a/Cheetah/Tests/SyntaxAndOutput.py b/Cheetah/Tests/SyntaxAndOutput.py\nindex c6fa39d..a2ee63c 100755\n--- a/Cheetah/Tests/SyntaxAndOutput.py\n+++ b/Cheetah/Tests/SyntaxAndOutput.py\n@@ -3049,6 +3049,12 @@ class GetVar(OutputTest): # Template.getVar()\n self.verify(\"$getVar('$bogus', 1234)\",\n \"1234\")\n \n+ def test6(self):\n+ \"\"\"$getVar('$') raises ValueError\n+ \"\"\"\n+ with self.assertRaises(ValueError):\n+ self.verify(\"$getVar('$')\", \"never get here\")\n+\n \n class MiscComplexSyntax(OutputTest):\n def test1(self):\n", "FAIL_TO_PASS": ["Cheetah/Tests/SyntaxAndOutput.py::GetVar::test6"], "PASS_TO_PASS": ["Cheetah/Tests/SyntaxAndOutput.py::GetVar::test1", "Cheetah/Tests/SyntaxAndOutput.py::GetVar::test2"]} +{"instance_id": "clb-pyc-053", "repo": "python-pillow/Pillow", "base_commit": "09605ff48e582fda6870a2c4c519650321f3f8de", "problem_statement": "ImageDraw only uses lower 8-bits of colors in I;16 images\n### What did you do?\r\n\r\n`ImageDraw` on an image with mode `I;16` fails to work correctly. When given a fill color (in the range 0...0xFFFF), it draws the shapes correctly, but uses a color with the lower 8-bits repeated twice.\r\n\r\n### What did you expect to happen?\r\nThe full 16-bit fill color provided should be used to draw on the image.\r\n\r\n### What actually happened?\r\nOnly the lower 8-bits (duplicated into the higher and lower byte) were used.\r\n\r\n### What are your OS, Python and Pillow versions?\r\n\r\n* OS: macOS 12 (also confirmed on Ubuntu 20.04)\r\n* Python: 3.10\r\n* Pillow: 9.5.0\r\n\r\n```python\r\nfrom PIL import Image, ImageDraw\r\nimage = Image.new(\"I;16\", (10, 10))\r\ndraw = ImageDraw.Draw(image)\r\n\r\nc = 0x1234\r\ndraw.point([(0, 0)], fill=c)\r\nprint(hex(image.load()[0, 0]))\r\n# --> 0x3434\r\n# (but we expect it to be 0x1234)\r\n\r\nc = 0x4567\r\ndraw.line([(0, 0), (5, 0)], fill=c)\r\nprint(hex(image.load()[0, 0]))\r\n# --> 0x6767\r\n# (but we expect it to be 0x4567)\r\n\r\nc = 0x89AB\r\ndraw.rectangle([(0, 0), (5, 5)], fill=c)\r\nprint(hex(image.load()[0, 0]))\r\n# --> 0xABAB\r\n# (but we expect it to be 0x89AB)\r\n```\r\n\r\nAs you can see, for each color, the *actual* color applied to the image is based on the lower 8-bits, duplicated twice.\r\n\r\nI suspect this has something to do with this: https://github.com/python-pillow/Pillow/blob/7c945f5131cf8596084b32af582f90a43b090540/src/libImaging/Draw.c#L71-L72\r\n(Which was originally added in #3899)\r\n\r\nNote that that issue is also referenced by #5598, so I suspect there might be a similar issue with drawing text.\r\n\n", "image": {"image_id": "sha256:fa3a641ce23062b01e43021ba76fa77574047cb21422ef0daa18c642dd7c7ccc", "pull_reference": "yutu0814/pyc-case-053-pillow@sha256:fa3a641ce23062b01e43021ba76fa77574047cb21422ef0daa18c642dd7c7ccc"}, "cohort": "python50", "patch": "diff --git a/src/libImaging/Draw.c b/src/libImaging/Draw.c\nindex 82f290b..0ccf22d 100644\n--- a/src/libImaging/Draw.c\n+++ b/src/libImaging/Draw.c\n@@ -41,6 +41,7 @@\n #define FLOOR(v) ((v) >= 0.0 ? (int)(v) : (int)floor(v))\n \n #define INK8(ink) (*(UINT8 *)ink)\n+#define INK16(ink) (*(UINT16 *)ink)\n \n /*\n * Rounds around zero (up=away from zero, down=towards zero)\n@@ -68,8 +69,13 @@ static inline void\n point8(Imaging im, int x, int y, int ink) {\n if (x >= 0 && x < im->xsize && y >= 0 && y < im->ysize) {\n if (strncmp(im->mode, \"I;16\", 4) == 0) {\n- im->image8[y][x * 2] = (UINT8)ink;\n+#ifdef WORDS_BIGENDIAN\n+ im->image8[y][x * 2] = (UINT8)(ink >> 8);\n im->image8[y][x * 2 + 1] = (UINT8)ink;\n+#else\n+ im->image8[y][x * 2] = (UINT8)ink;\n+ im->image8[y][x * 2 + 1] = (UINT8)(ink >> 8);\n+#endif\n } else {\n im->image8[y][x] = (UINT8)ink;\n }\n@@ -631,13 +637,17 @@ DRAW draw32rgba = {point32rgba, hline32rgba, line32rgba, polygon32rgba};\n /* Interface */\n /* -------------------------------------------------------------------- */\n \n-#define DRAWINIT() \\\n- if (im->image8) { \\\n- draw = &draw8; \\\n- ink = INK8(ink_); \\\n- } else { \\\n- draw = (op) ? &draw32rgba : &draw32; \\\n- memcpy(&ink, ink_, sizeof(ink)); \\\n+#define DRAWINIT() \\\n+ if (im->image8) { \\\n+ draw = &draw8; \\\n+ if (strncmp(im->mode, \"I;16\", 4) == 0) { \\\n+ ink = INK16(ink_); \\\n+ } else { \\\n+ ink = INK8(ink_); \\\n+ } \\\n+ } else { \\\n+ draw = (op) ? &draw32rgba : &draw32; \\\n+ memcpy(&ink, ink_, sizeof(ink)); \\\n }\n \n int\ndiff --git a/src/libImaging/Paste.c b/src/libImaging/Paste.c\nindex acf5202..6684b11 100644\n--- a/src/libImaging/Paste.c\n+++ b/src/libImaging/Paste.c\n@@ -425,7 +425,7 @@ fill_mask_L(\n *out = BLEND(*mask, *out, ink[0], tmp1);\n if (strncmp(imOut->mode, \"I;16\", 4) == 0) {\n out++;\n- *out = BLEND(*mask, *out, ink[0], tmp1);\n+ *out = BLEND(*mask, *out, ink[1], tmp1);\n }\n out++, mask++;\n }\n", "test_patch": "diff --git a/Tests/images/imagedraw_rectangle_I.png b/Tests/images/imagedraw_rectangle_I.png\nindex 4e94f6943dd8eaac1d3be2b930b835358f1caaf9..a75f12c2e98f417e662f2661eab980b45b61cde1 100644\nGIT binary patch\ndelta 102\nzcmdnWxP@_oidD6zi(^Q|oVT}j@-`TVusS+?xo;%mkkXypn)XS5|Jl7d3_x%o{o2RL\nzk9X7`yK1#D=Yq82qQh_PhD7E_X4Eu!GAut`79dQRy$UJxSp\r\n\r\n\r\nRestarting kernel...\r\n```\r\n\r\nAnd using python in the standard linux terminal it says:\r\n\r\n```\r\nSegmentation fault (core dumped)\r\n```\r\n\r\nThe code below produces the problem.\r\n\r\n```python\r\nimport numpy as np\r\nfrom PIL import Image, ImageFilter\r\n\r\nimg = Image.fromarray(np.ones([100, 100, 3], dtype='uint8'))\r\nimg = img.filter(ImageFilter.BoxBlur(-2))\r\n```\r\n\n", "image": {"image_id": "sha256:418f1ca7c0fe0f3525592d3635a6e06f4e7b45060ad3b0a492f177230eba26fe", "pull_reference": "yutu0814/pyc-case-054-pillow@sha256:418f1ca7c0fe0f3525592d3635a6e06f4e7b45060ad3b0a492f177230eba26fe"}, "cohort": "python50", "patch": "diff --git a/src/PIL/ImageFilter.py b/src/PIL/ImageFilter.py\nindex 59e2c18..63d6dcf 100644\n--- a/src/PIL/ImageFilter.py\n+++ b/src/PIL/ImageFilter.py\n@@ -183,6 +183,9 @@ class BoxBlur(MultibandFilter):\n name = \"BoxBlur\"\n \n def __init__(self, radius):\n+ if radius < 0:\n+ msg = \"radius must be >= 0\"\n+ raise ValueError(msg)\n self.radius = radius\n \n def filter(self, image):\ndiff --git a/src/libImaging/BoxBlur.c b/src/libImaging/BoxBlur.c\nindex 2e45a33..5afe7cf 100644\n--- a/src/libImaging/BoxBlur.c\n+++ b/src/libImaging/BoxBlur.c\n@@ -237,6 +237,9 @@ ImagingBoxBlur(Imaging imOut, Imaging imIn, float radius, int n) {\n if (n < 1) {\n return ImagingError_ValueError(\"number of passes must be greater than zero\");\n }\n+ if (radius < 0) {\n+ return ImagingError_ValueError(\"radius must be >= 0\");\n+ }\n \n if (strcmp(imIn->mode, imOut->mode) || imIn->type != imOut->type ||\n imIn->bands != imOut->bands || imIn->xsize != imOut->xsize ||\n", "test_patch": "diff --git a/Tests/test_image_filter.py b/Tests/test_image_filter.py\nindex cfe46b6..a2ef228 100644\n--- a/Tests/test_image_filter.py\n+++ b/Tests/test_image_filter.py\n@@ -24,6 +24,7 @@ from .helper import assert_image_equal, hopper\n ImageFilter.ModeFilter,\n ImageFilter.GaussianBlur,\n ImageFilter.GaussianBlur(5),\n+ ImageFilter.BoxBlur(0),\n ImageFilter.BoxBlur(5),\n ImageFilter.UnsharpMask,\n ImageFilter.UnsharpMask(10),\n@@ -173,3 +174,14 @@ def test_consistency_5x5(mode):\n Image.merge(mode, source[: len(mode)]).filter(kernel),\n Image.merge(mode, reference[: len(mode)]),\n )\n+\n+\n+def test_invalid_box_blur_filter():\n+ with pytest.raises(ValueError):\n+ ImageFilter.BoxBlur(-2)\n+\n+ im = hopper()\n+ box_blur_filter = ImageFilter.BoxBlur(2)\n+ box_blur_filter.radius = -2\n+ with pytest.raises(ValueError):\n+ im.filter(box_blur_filter)\n", "FAIL_TO_PASS": ["Tests/test_image_filter.py::test_invalid_box_blur_filter"], "PASS_TO_PASS": ["Tests/test_box_blur.py::test_radius_0", "Tests/test_box_blur.py::test_radius_1"]} +{"instance_id": "clb-pyc-056", "repo": "python-pillow/Pillow", "base_commit": "6798c87caf25cedf0cef19245e7db1656aed8602", "problem_statement": "Saving an image with JPEG2000 format doesn't accept Path object\n### What did you do?\r\n\r\nSave a JPEG 2000 image using a `Path` argument:\r\n```python\r\nfrom pathlib import Path\r\nfrom PIL import Image\r\n\r\nimg = Image.new('RGBA', (5, 5), '#00000000')\r\nimg.save(Path('image.jp2'), format='JPEG2000')\r\n```\r\n\r\n### What did you expect to happen?\r\n\r\nIt should save the file correctly, since [the documentation says that passing in a `Path` object is allowed](https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.save).\r\n\r\n### What actually happened?\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"/home/jtai/Desktop/pillow-fail/fail.py\", line 5, in \r\n img.save(Path('image.jp2'), format='JPEG2000')\r\n File \"/home/jtai/Desktop/pillow-fail/venv/lib/python3.9/site-packages/PIL/Image.py\", line 2235, in save\r\n save_handler(self, fp, filename)\r\n File \"/home/jtai/Desktop/pillow-fail/venv/lib/python3.9/site-packages/PIL/Jpeg2KImagePlugin.py\", line 247, in _save\r\n if filename.endswith(\".j2k\"):\r\nAttributeError: 'PosixPath' object has no attribute 'endswith'\r\n```\r\n\r\n### What are your OS, Python and Pillow versions?\r\n\r\n* OS: Pop!_OS 21.04\r\n* Python: 3.9.5\r\n* Pillow: 8.3.1\n", "image": {"image_id": "sha256:abeb4e9ddc951a5c0e9d63f1d5d0c23a8c0bcb668606cfab3e67adde60b76970", "pull_reference": "yutu0814/pyc-case-056-pillow@sha256:abeb4e9ddc951a5c0e9d63f1d5d0c23a8c0bcb668606cfab3e67adde60b76970"}, "cohort": "python50", "patch": "diff --git a/src/PIL/Image.py b/src/PIL/Image.py\nindex 34959cd..5d565f6 100644\n--- a/src/PIL/Image.py\n+++ b/src/PIL/Image.py\n@@ -2180,12 +2180,12 @@ class Image:\n \n filename = \"\"\n open_fp = False\n- if isPath(fp):\n- filename = fp\n- open_fp = True\n- elif isinstance(fp, Path):\n+ if isinstance(fp, Path):\n filename = str(fp)\n open_fp = True\n+ elif isPath(fp):\n+ filename = fp\n+ open_fp = True\n elif fp == sys.stdout:\n try:\n fp = sys.stdout.buffer\n", "test_patch": "diff --git a/Tests/test_image.py b/Tests/test_image.py\nindex c4e6f8a..2d661a9 100644\n--- a/Tests/test_image.py\n+++ b/Tests/test_image.py\n@@ -149,10 +149,11 @@ class TestImage:\n assert im.mode == \"RGB\"\n assert im.size == (128, 128)\n \n- temp_file = str(tmp_path / \"temp.jpg\")\n- if os.path.exists(temp_file):\n- os.remove(temp_file)\n- im.save(Path(temp_file))\n+ for ext in (\".jpg\", \".jp2\"):\n+ temp_file = str(tmp_path / (\"temp.\" + ext))\n+ if os.path.exists(temp_file):\n+ os.remove(temp_file)\n+ im.save(Path(temp_file))\n \n def test_fp_name(self, tmp_path):\n temp_file = str(tmp_path / \"temp.jpg\")\n", "FAIL_TO_PASS": ["Tests/test_image.py::TestImage::test_pathlib"], "PASS_TO_PASS": ["Tests/test_image.py::TestImage::test_fp_name", "Tests/test_image.py::TestImage::test_tempfile"]} +{"instance_id": "clb-pyc-057", "repo": "python-pillow/Pillow", "base_commit": "f0679aff4d43dbd595b98501dc7a8420550bf4e8", "problem_statement": "Pillow fails/hangs on PSD hidden background layer\nDepending on file content, Pillow:\r\n\r\n- fails with \"cannot identify image file\";\r\n- fails with \"Truncated File Read\";\r\n- just hangs inside the `PsdImagePlugin._layerinfo` function because it thinks there are 65534 layers.\r\n\r\nSee attachment: [pillow-psd-fail.zip](https://github.com/python-pillow/Pillow/files/6815914/pillow-psd-fail.zip)\r\n\r\nGIMP works fine with these files.\n", "image": {"image_id": "sha256:9ab77c7426fba99462ea9c55a3a1139fbc455ab39d47d17023fe49a897d7b96a", "pull_reference": "yutu0814/pyc-case-057-pillow@sha256:9ab77c7426fba99462ea9c55a3a1139fbc455ab39d47d17023fe49a897d7b96a"}, "cohort": "python50", "patch": "diff --git a/src/PIL/PsdImagePlugin.py b/src/PIL/PsdImagePlugin.py\nindex e7b8846..04b21e3 100644\n--- a/src/PIL/PsdImagePlugin.py\n+++ b/src/PIL/PsdImagePlugin.py\n@@ -22,6 +22,7 @@ from . import Image, ImageFile, ImagePalette\n from ._binary import i8\n from ._binary import i16be as i16\n from ._binary import i32be as i32\n+from ._binary import si16be as si16\n \n MODES = {\n # (photoshop mode, bits) -> (pil mode, required channels)\n@@ -179,7 +180,7 @@ def _layerinfo(fp, ct_bytes):\n def read(size):\n return ImageFile._safe_read(fp, size)\n \n- ct = i16(read(2))\n+ ct = si16(read(2))\n \n # sanity check\n if ct_bytes < (abs(ct) * 20):\ndiff --git a/src/PIL/_binary.py b/src/PIL/_binary.py\nindex 5564f45..a74ee9e 100644\n--- a/src/PIL/_binary.py\n+++ b/src/PIL/_binary.py\n@@ -47,6 +47,16 @@ def si16le(c, o=0):\n return unpack_from(\"h\", c, o)[0]\n+\n+\n def i32le(c, o=0):\n \"\"\"\n Converts a 4-bytes (32 bits) string to an unsigned integer.\n", "test_patch": "diff --git a/Tests/images/negative_layer_count.psd b/Tests/images/negative_layer_count.psd\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..b111c2d5675ab2eec3bf2df52d2af603e006d2a3\nGIT binary patch\nliteral 5492\nzcmeHKO=uHA7=4?hq{hTl%%O;f98ym$h*rt5u0koK5Yh;(dT_Iwq@meO*iDdtN5N~U\nz2Y(<~_29*`UOjjf1i>E=Z{E~{q6ej}Z)R;1O4EZ72D6Z>y!BC_&{8_Filxe9~\nzwrA<-nTDXqRZ=WNo1)is(}|n_Osi!V=GFA_%Eff_Bce#+0H%=8bfyVxia1^E!=*l~ui7SUW@(c#OpEbD%N{laz9z6)Z!u@<3B)dWb)!z`@$d~$WUX>9fID}A<5kAKJmB2p\nzbl9oezBYgB2ORv({?p~S)5s3rjoe+?5I2t_X;(JH&9)l0>53&&+V+U4n!Z-G8*P#-\nzZ0c>RM%^TP3@U4`V+~c6yx?wu7L#}{80{`h$3e8C4o{@|m_Cm1j?T3iN$p3Q%x^D0V6&OMVeDZJo54vN9CIA2c\n\nliteral 0\nHcmV?d00001\n\ndiff --git a/Tests/test_file_psd.py b/Tests/test_file_psd.py\nindex bf2a5fe..f50fe13 100644\n--- a/Tests/test_file_psd.py\n+++ b/Tests/test_file_psd.py\n@@ -57,9 +57,10 @@ def test_n_frames():\n assert im.n_frames == 1\n assert not im.is_animated\n \n- with Image.open(test_file) as im:\n- assert im.n_frames == 2\n- assert im.is_animated\n+ for path in [test_file, \"Tests/images/negative_layer_count.psd\"]:\n+ with Image.open(path) as im:\n+ assert im.n_frames == 2\n+ assert im.is_animated\n \n \n def test_eoferror():\n", "FAIL_TO_PASS": ["Tests/test_file_psd.py::test_n_frames"], "PASS_TO_PASS": ["Tests/test_file_psd.py::test_sanity", "Tests/test_file_psd.py::test_eoferror"]} +{"instance_id": "clb-pyc-058", "repo": "python-pillow/Pillow", "base_commit": "b21508798ab548ed90eb4d6bf01db14b880c9c91", "problem_statement": "JPEG Adobe APP14 color-transform metadata should use the twelfth payload byte. RGB and CMYK samples should report transforms 1 and 2; a shortened APP14 payload should retain Adobe metadata without inventing an absent transform value. Normal JPEG decoding and CMYK roundtripping should remain correct.", "image": {"image_id": "sha256:3fbe631ca2fb660e8850b0f3dedfdab10187317ad1520063edca003dbce331d5", "pull_reference": "yutu0814/pyc-case-058-pillow@sha256:3fbe631ca2fb660e8850b0f3dedfdab10187317ad1520063edca003dbce331d5"}, "cohort": "python50", "patch": "diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py\nindex 48e0de5..f449a2d 100644\n--- a/src/PIL/JpegImagePlugin.py\n+++ b/src/PIL/JpegImagePlugin.py\n@@ -140,8 +140,8 @@ def APP(self, marker):\n self.info[\"adobe\"] = i16(s, 5)\n # extract Adobe custom properties\n try:\n- adobe_transform = s[1]\n- except Exception:\n+ adobe_transform = s[11]\n+ except IndexError:\n pass\n else:\n self.info[\"adobe_transform\"] = adobe_transform\n", "test_patch": "diff --git a/Tests/images/truncated_app14.jpg b/Tests/images/truncated_app14.jpg\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..232a4c35f8c5ac8cba5c873e698f7415165ccfb3\nGIT binary patch\nliteral 29342\nzcmeIb2Urx#(l9)`OU_v(Nshu2BubE+b4G%|F0h1M!V&}p#ekxcgMb*245A`Q5K#mH\nzQIwojvLHz$2_oO@B8umpbM86s|Gf9T_x=vg&Qw=dbyro_boWfxG+Vt}?*JNIO&v`D\nz0)+tD;2*FxO!`D4808881_po-001NaF@z3)fe-}z10c)*Asz+*X9&x8*aIT)jRp$R\nzhy&mmU;}@C5D7fY0KzemD1hJ_Zx(oc4gSCyaiwlwRS+0wB!{s(28;1`$M|rlnQ<66\nzxuDRvBp@LsCMPc@DK93?At50zE+sD^2lBygKz_(}1Nyyu#0}UF7^K4;L=f0FTB6;0\nzK-hoi0pZ)N2WXRT@8PrsLz0)KqFY$twuhES4|Q&LgVP*Kq^\nzP*G7a;7(Kw+bpzyrGTx+04)iC01z+;7XYP&z-S>`L!jEkTlElSP)b4w{`jUc40IF%\nzLLy=kQZjPT9e&P)08rRYCJg`~fWV*xP(orN5<(b-B$!DHBjBVHCsZ+UqUZ8GB|*dx\nzck`YqHxHxf6KBbTei3bI#Jurl3&S5>{H2&OOHT8tCzvBN>TY4B_q1D#AQ$hSdD;;$\nz`bm>NG3#t;Qhn#xQg&HG*Z8ufYv8%$obqSg6Du-WR&GI&DY+GmJ(H`n02B&JOMsV&\nzn21mcF9N4H9RVnTFBd(b#Hlz2oCHry+ZH5woQM4);?>L;UHlJzw1n+qHxJzKz5Dtw+xX#D^bDDQ5=|Sxu+urM6Bm)f%l2T#aN^4)z>*\nzxY*b5=D_Jln-Jcqub)hKW>Nm9)pf*pPD*_>t0{PCFDW|dohQ+#KI>gp*|_4R-bC5N\nz?&)-qXXy;D^4w{7b3uIV26@32aAWkd*A~!R&@(*dGT4uCM@9oD?Rq1egIene-eKv8\nzn~JZCT!Tdg=RyMf&Sb);&+>W{r>6RsckXk^3@q;-blH&R32``D(I#@VVsl@4%^PK{\nz&cPH=#1jP@1g)LXsK?)(Ia-F58h17=k(O9harNV8t=J5qjKz2>%rbt49;\nzbZs?!pvlqN_dwGUYmfM4*M&*z*-XQiw|u`AlpPVyV(l3^NE8vcCyw)W@rmRR%M<&T\nzglb}3Vc}P-mMd#SD=Nf4QhX-PQXh#+UHV!eTWj-`dR|V^k+~qGjLK89<)Yn+=9#(3\nz(D204kO1@hqC@9ysN5wIyB`eM{NR0{?DiILr^xQbd_@4CEm1eIRN3j)*P*uuSz1cw\nza(y_9@6N_4>#r=oncD(ZnM=Q9s|C2g+VzYE6$QYji9nN19D5MV~0!OksbS75dg;l8v}Ma6IF~\nz`sbv+sgitu&F9a$--ibnM6YrC7DS(Iov76Gx+pf9ihjBJ2(EV%k2(\nz+^H>~XODPF^o(7)fNz4$$>Ulg$`i#g*?m=;)vIdM6~`O*r>+#1Zvit>;mc)l%O@*V\nz(nn*v=hhm(Y8)ahDmmX94KF0FKg!=c@)ADDsqA^N=;qUgJF9kM@jAA?j$7@ZYqhzc\nzT-iSmy0jOihPBa+Huj5y&R|u1Y~O>vB6m+e5l>qVU=;usx+HlhPD1WK_osa-sCzga\nzTG;yLbY1|f{|QEkiK;@iK9@ot-ZL{xMalcoje;ZNmQP%zJ^S18eC~~|7h|UUFx8&5\nzl6|%l-c66*FBhFi4~t&iqrQe#-w5-0jTqS96SSK5Xnu;8uu4f}eQG?>u&hpaDL9yy\nzRO{ln?o6Or=ZAva^8S~XdskxLsRX8#d5?^BS=zt3{n90dABzIt2%6(S-Iz%AZ!9;o@34D%#w{98FCvf_CEI2i*kIpbfr(qA~mSc\nz-+HK<`q-j!M)8^NDi}+TUj~_Ts6g75oLuz9Dyq!SMKpW$S3c;YUPF|)+e+4*>9%TE*{`>q`l#3@4\nzE9&Bhbi!i%c6dk?{IOv1Zo8`Uz&LNyD!{+xk&*sskti(ETgA`M>DZ4#op4D|B#?1O\nzs6Qy2yF?&8XhftN(oacD0lov`1%&TN\nzr~uy)TVV(H&s)OC4}}EV0SkK7PG#R!{$1|>gm(BHrEnJCF`M|$7W{W<3NsfcFVL0$\nzdz#@l3Vpv3K>PpO-3OLnFNXpf;J>Or`W>adH^RSVZ?q%uZ#?HezeoB5#lE-3zsW7(\nzAK+}hJr$;=8clq%=oi+??>%{?E1aALy{l&M1G3h|~YEt$*99KTY#g5FP>kSR?|6G)1~#\nz{}WyQf2JU=m3G}oU5iZZaQusQB{KXv\nz0c;AtG!TprmB5FDfKe9IQ25r|)*MV0sseK(428YJ2X%bQh4w-P@If31kP{5YfZ>Bh\nz!nZ&e7uxata3=xwL1OVqj_=5S0PyP(vv@Skw-5{H&K19o!H3VI`oXAt64+khpv2>F\nzAsfMX%6;F{?D$eY;nSq}GkAh*bCKcGprkk&{_XVI&v~foCv;\nz1Uw+$FgH`vzGEctcw6wiLnDR9i2T6d%UlD~0N?|L-2CnVdymWh-K?$uFL}7SaV7!}\nzFh~cV!UgO6NRi-EI6HtgfgaxeeWPRtu>d|OW}A~4mxSqnr)^zvNdSx{+5VA%+Mxh1\nzz!C5VoB(ey80-vrXWAnLx|4<(RARC7@yEl-&HoTn;#~?=O+{qxJ>1SLL<=u-XIT!h8eDOaB%^|\nzfoV#o04zoeiAMT?t2KCO%)##I8!_27F%AQg0y^Gq9N^`DTYp%9pO?9YwK-VTH{;@r\nz|1-wG-wpW_hRDeaYwqOs6OPIS3GyL>u{!?R<_7xC7>pOLK$0EwPsF6|7{3q|FO=Jk\nzrKq=+2Uq#F(I6)=0_o}$;DrT2(m?QC`|ptB-jU+bKa-O?yQyKkFn+s?OS@gZs@C@m\nzkOeTrpmDY)#bSJn0p2I4OQd%+;HUtwv#!qO&Ieubs|\nz3QPMHmi8+w?N?aZuduZLtFW}~ISeN_O922g@CU(7TBrdPaMFSSoWTbJ4!{_22VpGu\nz^T$IzAO+n&q2K`2wu{>?fBQLv82oGjeENidpEKA?Dm;(#WZ9P#~4lo)|L_+oe\nzhpQjBiXDXU^8^Frr1`-D{SdD5rs|sCiUU)M{JR3?f+R&Ter|AaIXOAFm;_uxLIk7`\nz@jnIzRRxQn{kg%~@M55>zq9?MF3K9OEm#p52fiwGq`!+F$_E#b#eu8Z34CV4D)I*e\nzpb+wMVv-0age*ct%tZnzA})?Via0q*N{F~hO3NK|Mk1sUNHKmgj&D^W!H-3LzfxSz\nzPPH5y3b>>^elBeWS{$haMkD+d1s1wZW{e6(dReQZypd?!`y3^4G4SmTp8B^rKeO2U\nzA{2Kc5hFpyWrxCDSbA67?QX?svX\nzU|hg{`Ntjjt%r8`vmP3+?$3q&YxG69d{@>7d{cxUxDYOIq!$vWlRtRJiht7<;Ue#f\nz57t&fd4o|da1S3O7?}D4`}^{4ci!Mw367fZ@8dAelmGXRUzPkV8~-xbFLV7Z3;ZqO\nzU*7f0Tz|^~e~b8+cl|Qg-?G5pBL3xFzs&WwEbzC8e|gt0bNwv~{4L^N-u25|f6D@Y\nzi}-))U1UGr-!+^J^j`Qg|&{FnxnC)k*1Em27bwbLR%k&#z4W)A#XI+&s0m5\nz!`jA{gSZt89U=vzn7|+*Cl`Mo12aurd<&qXp~m4465-$<$4d8hjRs>spg5U*5Z(wJTo1zM0|RhDLoj_1J{O2W27z!V2=jOac%wiV7lX#&jdTJ7\nznFw&vBs^H8i#rI5fiQ)ixv3fmD}b>i6mGj<=Up%sjNSoh0X2-zF?>7=hk%P92e?il\nz%b|@7@~d5XHr4?Hqra\nzxkL0%uDG_{Ci!H7Z!-wfiyycj%s+6LOfc3BjQ4}Z{=hk>0zk!C0NC6A1IKd%T)jF2\nz0OhZC>BEHcmtE^ND5Q%h&Y<6qe@gJ3@{fUC^@-x@`))f9_3iK{4xCY4z;LDjKMsG~\nzS__BBZ=Lvm%(zReU2+^SMYnp(EC<@TLVgO*XF8~61asXy`4a|XjZ#R8XOK_PH0Ic>;Zu>n5gZcRLPbX*$\nzn1uSH@F8`8nyER5OMqYCHVFalLI{w7%a;tmK7bwI1_S^RKmw2f4grS&4L}z#0?Yv$\nzzyWXp7c#v8KOhJ=4x9qc0T+Q-APGnVt^-*>K2Qvl02RPP;0f>yXaP4w>jDOVcfdIC\nz0ayT5fDLf#En)~IgdVaFvLC_=5r#-WWFblr4TwI(6k-E83UPy=Apwx%kkgQhka$QM\nzfW(1bPM<\nz4ZQ-*gcd=|p--SK&@SjZ=m+RBxK|oEj0wgG6M@OX)L=$1TbL`%4;BWCf+fQ;Va2d2\nzSR@$;M3;y%i0%+Q\nzCTb%ZC0ZsXCf-LZOsq(3MC?S2B|b--N?b%-OWaO8PP|4!PO_gwf<%+VmIO@_L6S^T\nzK=O#Bon(?^gOrApmsFnAh!jD3j5LNci?oXL73nzX1{p0GKbaz#IhhC9DY7eM#bga+\nzgJhq`$;r9M<;YFQQRFAduaMs*Zz3Ni|4czgAw;1@VMh@_5lxXx@tC5I;u9q$B_HKs\nzN?S@SWi(|zJaK=>ig8MsAp(M\nzY4~W=Xq;%mXwqpO(DcwO)6&z5(;Crw(_W%2plzmoPe)A0N2fuDpgTi%i|#4iC_Rjx\nzn_i9Hh5j^s7JUQ#I0F#_KZ6c~2g5~%+YGG?3ygG(2N^9HgBjBqYZ%`#!I=1%beO!D\nzVwg&px|!DZu-#wNY3%dd7q_os-w-na\nzvkEG{fjEF~=ctWZ`VR#Vnc)?2JESeMz@*|gYv*izY^vdyqF\nzu^(plU{7R!#6Gp3e!tRw)c(Z%wfmxdiw(04%BIqm*w)fE\nz$9DOM#*w5W<91SZ=j^)e`R#-4n;n=Pyc}vAsU4jh?;j;RYIU^W=ocp=r%b11XC3FO\nz&I>MTE-5Y_5Qhtx<3vQwU?UPg#T#78WhwmMyPhV9JBGoxp<&K91dI_Gz;C-P9_\nz_45ShQRiDPNM1<2@HGk%_57mP#pH`$F1cKKep&qTmCIYvuFQ-Eqos\nzdGWOIA@QRL1_|Yf9EnkhOG%DN&B+Ioucwfu1f;yXqJO0_l_xbe^-G$2T35Pi`kkw+\nzS1(*$%|K+dUpsuQ_&VG5i`Un0plw`7-(W1*`=zh0wx)!l@#=qSv?8Z&wzJ6yLnVbm!t-;BLU(>3c`-b(iRs\nz)ZLf8UtG#tdbNzcEUFw*eyn_@L9e0dndY;njVg_`O^Qtqo8_AyJePf5\nz(IVYa{zB?S*-NRHWv$Y!<*#I3Rlb&cUDc-0_NZOC{Yi&<$FokI&Xz92uC{KA?%p1|\nzo_D>7-uHc8eINS+`!@zo4iXMV4bcoGzhQlo`Bw1lop;jjYKGN^UyPWI42-&rei-u~\nz`!arJf^s5xa{pxhdx`fCr!=QtPal~c|KRgsW9Hl}?d;V#fw|K8!}Bi|tQW>V`hDD5\nzy!2_`r`)B3OLfb}%Wqb^S2k9o*7mLCeU|;)xNfyRxe@e*_{)_|!Og0#dS3^(yuq(B\nz<^W3kVl#j^49*3%H}l-yD)TR$p+64rdzo*?E>7ImmCzmhU%qbr*vu2${qo0Vo|Iel\nz;1pwf!%p1P<=X+lZ{$e`gKX#Qngl`cdwfC(U^L+81WAm{`E97Va2q-+L2mu)-{_7kZ\nzJ3vT8OGnH}FU~;1#mJ;$BEjw3&Xd@gWVvTAsne-@s*(u@c`ds5toAwkm6-WsOY6%5\nzWwhje-cECJ&)1eEEdbnsakg05dY$pm;>Lo%iL#hY%u-UtTH_W#T)ZA0g~@%}^rdB9\nz53^jRJX5Q_$=)&G7`bsS|YIT$_+geaP|`o6TF~)OkMrv\nzy(?@HuJ9<^BC|o1U+>(UND>3vyzINz`2tpL*2Lz~Rcq0?aSnNMM(h)h{9EN@7$c<>\nz&rObP7__Ll$6kkHF3_H+FZnck+0F@h$lfwfkl*8i_PxF!OIVJezUh^0aieQjvNeU2\nzY_FPkFysh2ZoPg-%vG})<$R5CZyt^$m+@eO)D)gn*Ez9)Qrz&mRQOigI~Z4u`ABZI\nzxUO@W8OW$_dW(@!Hh)Ur%od~)jI!El#}(Aod#XL@~L=q#~m?s~5O)U~Mr+jEa36jLy70y#xOQ9~;k{q_#mWsLF+\nz(X3CNrJ~2|4CmiSr}`m@mWKKwrCwH-bp$p|4-`ilV0+YZ&pPyBvcdu%>k~`{3X8;<\nzMr=UC)S}hlfh((r9Gqv~`d8Gjta#oJkwH~@eoFsn75>Dku5;3^HvUd3BkP$AOXsox\nzb=%CNT&*V)r}De1&DGTnbK#t1W>?h7)Xs;+$&pi~%2{?gydGS*krBh$J3V-Z;N&_>\nzm)008zY{wxwFZBaxOv!Rt;HrWS}x30sC>{zw?g}D07AO0t%so+k?KTwt9Wux8NgX*\nzc)2L&>0Lx=!i34o);1aHp>jk-%-g$BM>R4IsM8(l)6qIG%5BRq2{CzkHeQ9!S3Xh@\nz(BBik}_WzSa$b3}NWNu%h2}vY~xmIqH$I{d&cv\nzPgV4cb@gH%mG>d6<{ucA*rx*L)W3OH>%!^Fx0IEh-PR|Sk#W_$WKLhxE17OMT724X\nz^i)3ZUaIqbn8z#Y#_UJVFN-x_o_pF@yz0|`^?+)#Z@y7r`(e`!efvR&`XnB~BY_b&\nzNT-D=;HSe(S)Vhc)kjM36Lbk;V!#5s8L$aUOlWx+5*tzY\nz8KP#gs!)8(RBFFjrw2*TB*F2dFq!wYr>i1o{jf>UOpS4R(IJIY>mT^?MdCqJxNvd5cI\nz=%O4p-knjB&4d${E?TH*fT$hV|IlWz&vf!coqRFL0j5P(+G<^Qqb;1\nzZi6ySgZ8NdYg<6<0fYXcHKV3H!;)H78MaxP2`Un4B$Z99hKr>BdS_bmU39zw!iDkbE=^IPxfD(!P}px\nz{jga^4mcfl){SSlU9DnFa9QJoU2tt>zm4LRInl)a;ZBYH9JLM~(35#4(C*~|Z{EYqdyryGvwd96UGKb3RAFVXpm)BoZlFh&pb&EerSS&6vDZt(\nzk4#6XQYEbqB?zQziMH$1n|0CAPUqBlC|dcvY2AP^PedYfk_Ng}hD\nz;>5fAy&9cVghh-l4H#UW=8)}pPdcay4dS&AA69UL`CbF6_D6_V@qerqZlS;4_)agK\nzcTZ@wP>2No$ZDz?GEc0XsWQPkp6n@!`B_=pW7qf3Ykk>dTa%Nvq8`1msSGdV?|AjP\nzCG3Uc=cvuvBQlF`NVWiE@D`xkV?&>P?U}K(@U%JOX-6wzNueHA{$e}F!hosMFAY7J\nzc?t^&-R#d*1vsbJsveFsNiksIIC}Kz@Sspb(rEIaLuhiN;)~5`202mP>(PBY\nzheX-3Ev+VXjHx*q@O7gX6\nz)+C5LzW3>wgNQ1O*Y=f^j%20&__$Bi#l2sSy-d}*1g{W&#rkGn0&kcHvjeh1hUV_I\nzrXyiJ=gpAnJkj~OX1QlkMz@Q_>Vqe{awz3n+%KiGZ5s18U+7mk`p`|}g3iqKLNh-#\nz&PJM>_t5eS+^C|ak0TYPrw6RY-q}qD>XoMU-#gzeY$o575*++2U8J4zNR#=y(yp*i\nzv=m)L%`_*cd$>B!FaR{;5`>s2$qTE3!ChBhpvOuD&+Ca+4c=n&G&iR+U7VC-^W=#S\nzeCmxnvg~lv!(nCJ{h8Q@JrZsg?mmBdtJ(QO+}-muW4#Fh(NBXOP?krEe7u*}DJ4n2_sq)qwgK*M9kn$5U-PgelMDS2>sH\nz#pXyJ-5>YpIG`>&@z^(UZ|leIL(Jw_`RD1jQRdM2Acc{tvy@7XX%F;12=i1uTXt*d\nz3DtO}t}|Pb;E$UTCc_)MNX#$!6dFWw9!s5tY>6)aHWt|oE>hxDxebccG\nzmM_d*?GHsrU5F~E*D2nVdL`DZCX{!j_$=Dj-q1;m)o&!^CA!20ez|vqi`fp@^}cEL\nzLr6;bRVmN1F#@!V|*6czV4EjjYmbZ;|TQM2}pb+mptN\nzri%=Uu=5YR>1O{7^kUn*$Fmz#!gFQZQfb;Vm7ShaHn$y)6e)PxM-+$*Xm<(s+m;2M\nzzu#f%-4W2DO!^=4sVJ6^t\nz7sgvAF|gP1J}2kQ^<&UjOOj`jVkOBQYC3x#Narg!FPEe}tA24Yxg}1$6HWu6;;g3t\nzI6na|?p$t3fSp!v!sO>0sK;js@@w#_s%6o5s(+4p>e{>o*tk^Asd;-KqrJbjw#>+9\nzysYX-ZX&g1P;#b@QKdFk0lNJ^&=#QW1Nif#c~czUCYU~IM!0a7BY4|CvpzW(?_SU$\nz_ClbGIEj?`R(4uW{PRMwWf_kv(GEg4RWv>_X``*LX0>RR7-bNZ;xP)qUQXxz6`d\nz6>{j1H)RJCMS4X2Og|M%N_eiL!!^@A9csG{agE+VSnd(-ny_-d_{1m+KAOaZ;o{Mt\nz5r0A(cL5tQV(8*Wc2zcpO0IlucKp)0Mz0zz!|t(zj5$@aRuLU{TFRVsddAx;#h-r(\nz^&5%Sez7(^J@1Fi3B42~ofvt9*dI=ip=iI^rm@|_\nz%XX7FT5Hc=4YDUp%Wna8*}b8S18?%5ZKAbqO(`!*8m-UESS94XXL_XYCF8+^4L9bl\nzM72-UZdAua=bB5X<{E?C2ICB?H~S7%3>Vj|U1Oe~s(DoBlf4BDF}*buSK?h%a$_#b\nzt(b>%zy12!(X8VB$71n`N6ACiW*=>eT(iS0E_%Fu$YRktW9ku9#3y9Ybe?{wzqxhD\nz%Rp$s``U}-oYEtVy!(MtosO}aL;J+!&YO{O8MFJ-GE0^_U!PcPn0kg2v$kV6rOo@wBCC%f%KWJ\nzT|Su_W#uCGBU>sF#k%&`cuV6XM|atRaW?*q2}eXlY|rh2Hi^P)o5V-jYFz7l`HtCD\nzaZrnL^5=wg3TEew$%u;z7K#}-t8WlBCyEH4$zN?IdFpJGHk1Jt0S&Nlr^RevN1a*(K2>dxn\nzS>GppNmwncG|r-ja@;hXG|M4larITuk#*g})tO88Aj-Rk-87)z&h#Ls{BnO{wgADY\nz;-P-1Hmk>ESWtMUa-L@xc2JAknmLJzhsds@a!}fFFn+GxlDiU8UTnup4bfJiwh9M+s!NG*`y09@XcP8(bH?F%qwqsYMzV|x&QQdmji>&7p4(d<4\nzVzumoR|iv_1(NGBR92VD(B>v7&riTUkPa3ZlC-HfxM=WBS&NUoiVJ)BCY|j53jOHi\nzJMD;DZL5T@tk-9+85I&TeJF&Be7GFi75`zW37s0uqna{3A{RvP-rW7hZ6vc9w{ogHLO$5iPao-=e=<1VT-o^kQ$vpdTQYUWQM<4r&U2\nz$z3&RFXLr&m?%S-a`VIdW`jw|hGBxvoLA?{*Hd@iov5%;D@`~WV_#~8UCkPP1($D}\nzrk1PMI_YZR+%@MFXkYtAB6|keF&H};&`~MyKKp&f;U4v+_Wr9bMBzc!G3QIWNF9H56zBF-X=~yB-7s1r9qa`nm|EW|M%}B)0qH}Iku&HayYWq@RyF@F*JIR_QWZy1xib}g~\nzrPBl(=m<#+X`8k=;73+G74=mUm6c7aaX*2qE{iu`NzI38^o7Xa2gNy-6su1dINCf?\nz^#&x5\nzNo0|dkRI2Lxs}(33b;L_P1`i\nzRPDX*oFe+UVSQ!k7-^ev%Gm9;7D2njllcNY=0*Wayzu6(Z(8j~OVleKuGL\nz2#92QeGFn>5o<18br#!eYSl?rt(1zE{}QTk2iyRH8pqEhKd&G^k*vnYUd#\nz>9Y|}E{hm8^YG2*oT_JK6ZMb!0KSqn*rpjPmSh+zO|L+|TJ=|6H$-eqn^Qp_y{xcq+QwmZf&=!tBeMk`@79t7Z@FMa;yjo7s72\nzQ=>W>1{GmCs>Lrgo}cxY=ADnR-OpYwlwpA~4op88XlZM67}#4?JWT`e=&DlO84$Sf\nz(7?PtTXw-hGFAymL$TU;hg_2~rm?25`MDYz8o7i#%GjzCWr^-R!^nK;l*TZx(pURgp>Y8Xr\nzoiqwy%6WdS3if4WVS$AzO{TAyf9#79?Sz9iMq+FrprmzZl}iilJ)3N!7FDBbYBu(^\nzl?UHE;U&_`G`gps`UVKZ+5WJT_QlRdv#M>wFH(#9}rE4QI9FtArM0KrdcL_n%j8&MUZ=8PT\nzsk3Nz?nzSEeRAF{V9z792i94LZgl6BJ2IS+svN4`$cj|c0f(+^ZObmULfv?*F;_{s\nzuygZT12L~+xhD%m(^JBYo+x&Z!@{ZSXj-FRHy>T!xWTL(dmbZu+|9z*jVe%<4NiJF\nzV=Y#_dyQi{Qx`7{azfe6qJ{6ivy4(|HoI)g&2X)t3;sMbq;$P5E2$7uq>vG~6cd%+\nzC^3@C{QQO_6Svahr5xQpt!~aM_x%Uz>@~+q6BW@VM;=zI99H+PFxyuHpE*?j?D<1m\nzc)~M*=ly(a&nvYf#oJud8pqw3d!L8J+G|{cJ3pBkng`z=D;0fw>rSSnbF#F#kaNB-&tm+\nzBdmU|$GyGK=mdtxj7t!G;%>YSO@3B}WF@oo%uN!FiIGH3Qh--bJ05Bpi`)N9\nz9&+OjlZ(eJIoU_i85XV$*=eW>sXM>q9&(EG^EQ^bLYK2fEJL}f;z}qxIrd4#(Fv#l\nz;6Imh>)FG8R|TynR^-!%9Al_Vl<0?D;8smKlSRlAp+eS4<8kWvc$jH(j?J76KhN8_\nzJuIQkA;KkSy0?CkO~$5d(G?E1slGxGog+vg-IE;CgrT*Vfq|7C@Sh_EukKIz+qa%ociweVkJ+4rf;)e_G2kdp+ddO5!G0\nzjY@dfgOt(2lwm2o7hd+Kol-8`wT1@?_Pr-Gwk1P5zmnmHlihdY4H>dd<-e11jI}W6\nzj8MG>6=pKeIQ9!*J=mswv%VvzZK)POPHP>l!~T\nzE<{D4p|{h$l0{do2Gp2#qr0i|V^S;2LU\nzkch9F{_sXCc%8=^Lu>w`SFZ#SS5xjb=a~q_OU7f6*RN(4T)bfTaea=JHM68q86q>u\nz`gG}hw3T!H1=7UEvy9~~F$6a`N!ft+i6@B<6Gxt8yaeCV(ygKRp;#q2N&fvXFGf3{\nzF~dYih}TdyTSPry*MukDJk!Y3;Ml$;3(+gNvpriqxYw5_(r~Lpc@3JS4MM(VE2tHETx{Prr+m29oX$0M1w+sj8C3=1Fg8Z-=rP*GvC_<96)03mUc_FC|*Dp<~!\ns&ISV|C0XYiUrN`$dYN9y?aNzR`(h2&ZvgT{*5O1v9)_zae5>#O0is5;bpQYW\n\nliteral 0\nHcmV?d00001\n\ndiff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py\nindex 1883715..ab799c1 100644\n--- a/Tests/test_file_jpeg.py\n+++ b/Tests/test_file_jpeg.py\n@@ -795,6 +795,20 @@ class TestFileJpeg:\n apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n assert [65504, 24] == apps_13_lengths\n \n+ def test_adobe_transform(self):\n+ with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n+ assert im.info[\"adobe_transform\"] == 1\n+\n+ with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n+ assert im.info[\"adobe_transform\"] == 2\n+\n+ # This image has been manually hexedited\n+ # so that the APP14 reports its length to be 11,\n+ # leaving no room for \"adobe_transform\"\n+ with Image.open(\"Tests/images/truncated_app14.jpg\") as im:\n+ assert \"adobe\" in im.info\n+ assert \"adobe_transform\" not in im.info\n+\n def test_icc_after_SOF(self):\n with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n assert im.info[\"icc_profile\"] == b\"profile\"\n", "FAIL_TO_PASS": ["Tests/test_file_jpeg.py::TestFileJpeg::test_adobe_transform"], "PASS_TO_PASS": ["Tests/test_file_jpeg.py::TestFileJpeg::test_sanity", "Tests/test_file_jpeg.py::TestFileJpeg::test_cmyk"]} +{"instance_id": "clb-pyc-060", "repo": "python-pillow/Pillow", "base_commit": "d0612030a0ba7aed533e1f9115bbf4bd1019f48e", "problem_statement": "Segmentation fault when creating gradient images with mode \"F\"\n\r\n\r\n### What did you do?\r\n```pycon\r\nPython 3.9.1 (default, Jan 13 2021, 15:21:08) \r\n[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux\r\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\r\n>>> import PIL\r\n>>> print(PIL.__version__)\r\n8.0.1\r\n>>> import PIL.Image as pimage\r\n>>> image1 = pimage.linear_gradient(\"L\")\r\n>>> image2 = pimage.linear_gradient(\"F\")\r\nSegmentation fault\r\n```\r\n\r\n### What did you expect to happen?\r\nNot segfaulting.\r\n\r\n### What actually happened?\r\nSegfaulted.\r\n\r\n### What are your OS, Python and Pillow versions?\r\n\r\n* OS: Red Hat 4.8.5-44\r\n* Python: Python 3.9.1\r\n* Pillow: 8.0.1\r\n\r\n\n", "image": {"image_id": "sha256:e5558c76835739376be27654c041f0fc5743476226db4150d772cfa124ff1be8", "pull_reference": "yutu0814/pyc-case-060-pillow@sha256:e5558c76835739376be27654c041f0fc5743476226db4150d772cfa124ff1be8"}, "cohort": "python50", "patch": "diff --git a/src/libImaging/Fill.c b/src/libImaging/Fill.c\nindex e4e4b43..f720602 100644\n--- a/src/libImaging/Fill.c\n+++ b/src/libImaging/Fill.c\n@@ -76,8 +76,21 @@ ImagingFillLinearGradient(const char *mode) {\n return NULL;\n }\n \n- for (y = 0; y < 256; y++) {\n- memset(im->image8[y], (unsigned char)y, 256);\n+ if (im->image8) {\n+ for (y = 0; y < 256; y++) {\n+ memset(im->image8[y], (unsigned char)y, 256);\n+ }\n+ } else {\n+ int x;\n+ for (y = 0; y < 256; y++) {\n+ for (x = 0; x < 256; x++) {\n+ if (im->type == IMAGING_TYPE_FLOAT32) {\n+ IMAGING_PIXEL_FLOAT32(im, x, y) = y;\n+ } else {\n+ IMAGING_PIXEL_INT32(im, x, y) = y;\n+ }\n+ }\n+ }\n }\n \n return im;\n@@ -103,9 +116,16 @@ ImagingFillRadialGradient(const char *mode) {\n d = (int)sqrt(\n (double)((x - 128) * (x - 128) + (y - 128) * (y - 128)) * 2.0);\n if (d >= 255) {\n- im->image8[y][x] = 255;\n- } else {\n+ d = 255;\n+ }\n+ if (im->image8) {\n im->image8[y][x] = d;\n+ } else {\n+ if (im->type == IMAGING_TYPE_FLOAT32) {\n+ IMAGING_PIXEL_FLOAT32(im, x, y) = d;\n+ } else {\n+ IMAGING_PIXEL_INT32(im, x, y) = d;\n+ }\n }\n }\n }\n", "test_patch": "diff --git a/Tests/test_image.py b/Tests/test_image.py\nindex 3fa071b..30d093e 100644\n--- a/Tests/test_image.py\n+++ b/Tests/test_image.py\n@@ -524,7 +524,7 @@ class TestImage:\n \n # Arrange\n target_file = \"Tests/images/linear_gradient.png\"\n- for mode in [\"L\", \"P\"]:\n+ for mode in [\"L\", \"P\", \"I\", \"F\"]:\n \n # Act\n im = Image.linear_gradient(mode)\n@@ -550,7 +550,7 @@ class TestImage:\n \n # Arrange\n target_file = \"Tests/images/radial_gradient.png\"\n- for mode in [\"L\", \"P\"]:\n+ for mode in [\"L\", \"P\", \"I\", \"F\"]:\n \n # Act\n im = Image.radial_gradient(mode)\n", "FAIL_TO_PASS": ["Tests/test_image.py::TestImage::test_linear_gradient", "Tests/test_image.py::TestImage::test_radial_gradient"], "PASS_TO_PASS": ["Tests/test_image.py::TestImage::test_linear_gradient_wrong_mode", "Tests/test_image.py::TestImage::test_radial_gradient_wrong_mode"]} +{"instance_id": "clb-pyc-066", "repo": "python-pillow/Pillow", "base_commit": "3fb62360e61949a2405db0771ad89f1c9a2b25e4", "problem_statement": "4.2.0+ font rendering mem leak\n### What did you do?\r\nuse font in loop and draw image \r\n### What did you expect to happen?\r\nnot leak memory\r\n### What actually happened?\r\nleak memory\r\n### What versions of Pillow and Python are you using?\r\nit doesnt happen in py3.4 pillow <= 4.1.1\r\nit does in >= 4.20\r\nImageFont.py leaks memory, it happens on default font, but even more on external loaded font with truetype\r\n\r\nwhen running the script below on version 4.2.0+ \r\nmem usage keeps increasing every cycle for : \r\n/usr/local/lib/python3.4/dist-packages/PIL/ImageFont.py:113 \r\n/usr/local/lib/python3.4/dist-packages/PIL/ImageFont.py:113: size=15.9 KiB (+15.9 KiB), count=709 (+708), average=23 B\r\n/usr/local/lib/python3.4/dist-packages/PIL/ImageFont.py:113: size=17.2 KiB (+17.2 KiB), count=768 (+767), average=23 B\r\n/usr/local/lib/python3.4/dist-packages/PIL/ImageFont.py:113: size=18.6 KiB (+18.6 KiB), count=827 (+826), average=23 B\r\n\r\n\r\n\r\n```python\r\nfrom PIL import Image, ImageFont, ImageDraw, ImageFont\r\nimport tracemalloc\r\ntracemalloc.start()\r\ncount = 0\r\nsize = 128, 128\r\n#font2 = ImageFont.truetype('/home/pi/run/fonts/04B_03__.TTF',8) ##use this with own font for more leaking\r\ntxt = Image.new('RGBA', size, (255,255,255,0))\r\nd = ImageDraw.Draw(txt)\r\nfont2 = ImageFont.load_default()\r\nwhile True :\r\n\r\n\td.text((0, 0), \"blabla\", font=font2, fill=\"white\")\r\n\tif count <= 0:\r\n\t\tsnapshot1 = tracemalloc.take_snapshot()\r\n\tcount += 1\r\n\t\r\n\r\n\tif count == 60 :\r\n\t\tsnapshot2 = tracemalloc.take_snapshot()\r\n\t\tcount = 1\r\n\t\ttop_stats = snapshot2.compare_to(snapshot1, 'lineno')\r\n\t\tprint(\"[ Top 10 differences ]\")\r\n\t\tfor stat in top_stats[:10]:\r\n\t\t\tprint(stat)\r\n```\r\n\n", "image": {"image_id": "sha256:7b21635299e99621802eba50557e2f4c87117546a29657660d02b8fcd5aecc6e", "pull_reference": "yutu0814/pyc-case-066-pillow@sha256:7b21635299e99621802eba50557e2f4c87117546a29657660d02b8fcd5aecc6e"}, "cohort": "python50", "patch": "diff --git a/_imaging.c b/_imaging.c\nindex b7726a2c..60a97aa1 100644\n--- a/_imaging.c\n+++ b/_imaging.c\n@@ -2198,26 +2198,45 @@ textwidth(ImagingFontObject* self, const unsigned char* text)\n }\n \n void _font_text_asBytes(PyObject* encoded_string, unsigned char** text){\n+ /* Allocates *text, returns a 'new reference'. Caller is required to free */\n+\n PyObject* bytes = NULL;\n+ Py_ssize_t len = 0;\n+ char *buffer;\n \n *text = NULL;\n \n if (PyUnicode_CheckExact(encoded_string)){\n bytes = PyUnicode_AsLatin1String(encoded_string);\n+ PyBytes_AsStringAndSize(bytes, &buffer, &len);\n } else if (PyBytes_Check(encoded_string)) {\n- bytes = encoded_string;\n+ PyBytes_AsStringAndSize(encoded_string, &buffer, &len);\n }\n- if (bytes) {\n- *text = (unsigned char*)PyBytes_AsString(bytes);\n+\n+ if (len) {\n+ *text = calloc(len,1);\n+ if (*text) {\n+ memcpy(*text, buffer, len);\n+ }\n+ if(bytes) {\n+ Py_DECREF(bytes);\n+ }\n return;\n }\n \n+\n #if PY_VERSION_HEX < 0x03000000\n /* likely case here is py2.x with an ordinary string.\n but this isn't defined in Py3.x */\n if (PyString_Check(encoded_string)) {\n- *text = (unsigned char *)PyString_AsString(encoded_string);\n+ PyString_AsStringAndSize(encoded_string, &buffer, &len);\n+ *text = calloc(len,1);\n+ if (*text) {\n+ memcpy(*text, buffer, len);\n+ }\n+ return;\n }\n+ \n #endif\n }\n \n@@ -2248,6 +2267,7 @@ _font_getmask(ImagingFontObject* self, PyObject* args)\n \n im = ImagingNew(self->bitmap->mode, textwidth(self, text), self->ysize);\n if (!im) {\n+ free(text);\n return NULL;\n }\n \n@@ -2273,9 +2293,11 @@ _font_getmask(ImagingFontObject* self, PyObject* args)\n x = x + glyph->dx;\n b = b + glyph->dy;\n }\n+ free(text);\n return PyImagingNew(im);\n \n failed:\n+ free(text);\n ImagingDelete(im);\n return NULL;\n }\n@@ -2285,6 +2307,7 @@ _font_getsize(ImagingFontObject* self, PyObject* args)\n {\n unsigned char* text;\n PyObject* encoded_string;\n+ PyObject* val;\n \n if (!PyArg_ParseTuple(args, \"O:getsize\", &encoded_string))\n return NULL;\n@@ -2294,7 +2317,9 @@ _font_getsize(ImagingFontObject* self, PyObject* args)\n return NULL;\n }\n \n- return Py_BuildValue(\"ii\", textwidth(self, text), self->ysize);\n+ val = Py_BuildValue(\"ii\", textwidth(self, text), self->ysize);\n+ free(text);\n+ return val;\n }\n \n static struct PyMethodDef _font_methods[] = {\ndiff --git a/_imagingft.c b/_imagingft.c\nindex 21188996..af9fb3df 100644\n--- a/_imagingft.c\n+++ b/_imagingft.c\n@@ -497,6 +497,11 @@ font_getsize(FontObject* self, PyObject* args)\n FT_Done_Glyph(glyph);\n }\n \n+ if (glyph_info) {\n+ PyMem_Free(glyph_info);\n+ glyph_info = NULL;\n+ }\n+ \n if (face) {\n \n /* left bearing */\n", "test_patch": "diff --git a/Tests/helper.py b/Tests/helper.py\nindex 65b1ca8b..989215ca 100644\n--- a/Tests/helper.py\n+++ b/Tests/helper.py\n@@ -170,6 +170,41 @@ class PillowTestCase(unittest.TestCase):\n return Image.open(outfile)\n raise IOError()\n \n+@unittest.skipIf(sys.platform.startswith('win32'), \"requires Unix or MacOS\")\n+class PillowLeakTestCase(PillowTestCase):\n+ # requires unix/osx\n+ iterations = 100 # count\n+ mem_limit = 512 # k\n+ \n+ def _get_mem_usage(self):\n+ \"\"\"\n+ Gets the RUSAGE memory usage, returns in K. Encapsulates the difference\n+ between OSX and Linux rss reporting\n+\n+ :returns; memory usage in kilobytes\n+ \"\"\"\n+ \n+ from resource import getpagesize, getrusage, RUSAGE_SELF\n+ mem = getrusage(RUSAGE_SELF).ru_maxrss\n+ if sys.platform == 'darwin':\n+ # man 2 getrusage:\n+ # ru_maxrss the maximum resident set size utilized (in bytes).\n+ return mem / 1024 # Kb\n+ else:\n+ # linux\n+ # man 2 getrusage\n+ # ru_maxrss (since Linux 2.6.32)\n+ # This is the maximum resident set size used (in kilobytes). \n+ return mem # Kb\n+\n+ def _test_leak(self, core):\n+ start_mem = self._get_mem_usage()\n+ for cycle in range(self.iterations):\n+ core()\n+ mem = (self._get_mem_usage() - start_mem)\n+ self.assertLess(mem, self.mem_limit,\n+ msg='memory usage limit exceeded in iteration %d' % cycle)\n+\n \n # helpers\n \ndiff --git a/Tests/test_file_png.py b/Tests/test_file_png.py\nindex e7b74762..200c93b7 100644\n--- a/Tests/test_file_png.py\n+++ b/Tests/test_file_png.py\n@@ -1,4 +1,4 @@\n-from helper import unittest, PillowTestCase, hopper\n+from helper import unittest, PillowTestCase, PillowLeakTestCase, hopper\n from PIL import Image, ImageFile, PngImagePlugin\n \n from io import BytesIO\n@@ -7,9 +7,6 @@ import sys\n \n codecs = dir(Image.core)\n \n-# For Truncated phng memory leak\n-MEM_LIMIT = 2 # max increase in MB\n-ITERATIONS = 100 # Leak is 56k/iteration, this will leak 5.6megs\n \n # sample png stream\n \n@@ -539,26 +536,14 @@ class TestFilePng(PillowTestCase):\n \n \n @unittest.skipIf(sys.platform.startswith('win32'), \"requires Unix or MacOS\")\n-class TestTruncatedPngPLeaks(PillowTestCase):\n+class TestTruncatedPngPLeaks(PillowLeakTestCase):\n+ mem_limit = 2*1024 # max increase in K\n+ iterations = 100 # Leak is 56k/iteration, this will leak 5.6megs\n \n def setUp(self):\n if \"zip_encoder\" not in codecs or \"zip_decoder\" not in codecs:\n self.skipTest(\"zip/deflate support not available\")\n \n- def _get_mem_usage(self):\n- from resource import getpagesize, getrusage, RUSAGE_SELF\n- mem = getrusage(RUSAGE_SELF).ru_maxrss\n- if sys.platform == 'darwin':\n- # man 2 getrusage:\n- # ru_maxrss the maximum resident set size utilized (in bytes).\n- return mem / 1024 / 1024 # megs\n- else:\n- # linux\n- # man 2 getrusage\n- # ru_maxrss (since Linux 2.6.32)\n- # This is the maximum resident set size used (in kilobytes).\n- return mem / 1024 # megs\n-\n def test_leak_load(self):\n with open('Tests/images/hopper.png', 'rb') as f:\n DATA = BytesIO(f.read(16 * 1024))\n@@ -566,13 +551,13 @@ class TestTruncatedPngPLeaks(PillowTestCase):\n ImageFile.LOAD_TRUNCATED_IMAGES = True\n with Image.open(DATA) as im:\n im.load()\n- start_mem = self._get_mem_usage()\n+\n+ def core():\n+ with Image.open(DATA) as im:\n+ im.load()\n+\n try:\n- for _ in range(ITERATIONS):\n- with Image.open(DATA) as im:\n- im.load()\n- mem = (self._get_mem_usage() - start_mem)\n- self.assertLess(mem, MEM_LIMIT, msg='memory usage limit exceeded')\n+ self._test_leak(core)\n finally:\n ImageFile.LOAD_TRUNCATED_IMAGES = False\n \ndiff --git a/Tests/test_font_leaks.py b/Tests/test_font_leaks.py\nnew file mode 100644\nindex 00000000..70933923\n--- /dev/null\n+++ b/Tests/test_font_leaks.py\n@@ -0,0 +1,34 @@\n+from __future__ import division\n+from helper import unittest, PillowLeakTestCase\n+import sys\n+from PIL import Image, features, ImageDraw, ImageFont\n+\n+@unittest.skipIf(sys.platform.startswith('win32'), \"requires Unix or MacOS\")\n+class TestTTypeFontLeak(PillowLeakTestCase):\n+ # fails at iteration 3 in master\n+ iterations = 10\n+ mem_limit = 4096 #k\n+\n+ def _test_font(self, font):\n+ im = Image.new('RGB', (255,255), 'white')\n+ draw = ImageDraw.ImageDraw(im)\n+ self._test_leak(lambda: draw.text((0, 0), \"some text \"*1024, #~10k\n+ font=font, fill=\"black\"))\n+ \n+ @unittest.skipIf(not features.check('freetype2'), \"Test requires freetype2\")\n+ def test_leak(self):\n+ ttype = ImageFont.truetype('Tests/fonts/FreeMono.ttf', 20)\n+ self._test_font(ttype)\n+\n+class TestDefaultFontLeak(TestTTypeFontLeak):\n+ # fails at iteration 37 in master\n+ iterations = 100\n+ mem_limit = 1024 #k\n+ \n+ def test_leak(self):\n+ default_font = ImageFont.load_default()\n+ self._test_font(default_font)\n+\n+\n+if __name__ == '__main__':\n+ unittest.main()\n", "FAIL_TO_PASS": ["Tests/test_font_leaks.py::TestDefaultFontLeak::test_leak"], "PASS_TO_PASS": ["Tests/test_imagefont.py::TestImageFont::test_default_font", "Tests/test_file_png.py::TestFilePng::test_sanity", "Tests/test_font_leaks.py::TestTTypeFontLeak::test_leak"]} +{"instance_id": "clb-pyc-068", "repo": "python-pillow/Pillow", "base_commit": "dc1664500be0135d83182d480af341d39b5c78d7", "problem_statement": "The PNG loader crashes trying to save palette images with tRNS color type 3 (indexed color) value after convert to RGB\n![defaktologo_bad](https://f.cloud.github.com/assets/4199178/2030235/e2a6f2ea-88f3-11e3-9d40-b86f41857491.png)\n\nValueError: too many values to unpack\n\n![valueerror](https://f.cloud.github.com/assets/4199178/2030315/05d21a00-88f5-11e3-932c-6ab1a5d0ea62.png)\n\n4.2.1.1. tRNS Transparency (PNG Specification)\nhttp://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.tRNS\n\n", "image": {"image_id": "sha256:38a579d4478242d8f8c82a87cbfec6b295062262989eb5404bb13f7535fed222", "pull_reference": "yutu0814/pyc-case-068-pillow@sha256:38a579d4478242d8f8c82a87cbfec6b295062262989eb5404bb13f7535fed222"}, "cohort": "python50", "patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex 8839a178..b0834eb8 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -4,6 +4,12 @@ Changelog (Pillow)\n 2.4.0 (unreleased)\n ------------------\n \n+- Indexed Transparency handled for conversions between L, RGB, and P modes. Fixes #510\n+ [wiredfool]\n+\n+- Conversions enabled from RGBA->P, Fixes #544\n+ [wiredfool]\n+\n - Improved icns support\n [al45tair]\n \ndiff --git a/PIL/Image.py b/PIL/Image.py\nindex 7713fe7d..18d2c826 100644\n--- a/PIL/Image.py\n+++ b/PIL/Image.py\n@@ -735,21 +735,65 @@ class Image:\n im = self.im.convert_matrix(mode, matrix)\n return self._new(im)\n \n+ if mode == \"P\" and self.mode == \"RGBA\":\n+ return self.quantize(colors)\n+\n+ trns = None\n+ delete_trns = False\n+ # transparency handling\n+ if \"transparency\" in self.info and self.info['transparency'] is not None:\n+ if self.mode in ('L', 'RGB') and mode == 'RGBA':\n+ # Use transparent conversion to promote from transparent\n+ # color to an alpha channel. \n+ return self._new(self.im.convert_transparent(\n+ mode, self.info['transparency']))\n+ elif self.mode in ('L', 'RGB', 'P') and mode in ('L', 'RGB', 'P'):\n+ t = self.info['transparency']\n+ if isinstance(t, bytes):\n+ # Dragons. This can't be represented by a single color\n+ warnings.warn('Palette images with Transparency expressed '+\n+ ' in bytes should be converted to RGBA images')\n+ delete_trns = True\n+ else:\n+ # get the new transparency color.\n+ # use existing conversions\n+ trns_im = Image()._new(core.new(self.mode, (1,1)))\n+ if self.mode == 'P':\n+ trns_im.putpalette(self.palette)\n+ trns_im.putpixel((0,0), t)\n+\n+ if mode in ('L','RGB'):\n+ trns_im = trns_im.convert(mode)\n+ else:\n+ # can't just retrieve the palette number, got to do it\n+ # after quantization. \n+ trns_im = trns_im.convert('RGB')\n+ trns = trns_im.getpixel((0,0))\n+ \n+ \n if mode == \"P\" and palette == ADAPTIVE:\n im = self.im.quantize(colors)\n new = self._new(im)\n from PIL import ImagePalette\n new.palette = ImagePalette.raw(\"RGB\", new.im.getpalette(\"RGB\"))\n+ if delete_trns:\n+ # This could possibly happen if we requantize to fewer colors.\n+ # The transparency would be totally off in that case. \n+ del(new.info['transparency'])\n+ if trns is not None:\n+ try:\n+ new.info['transparency'] = new.palette.getcolor(trns)\n+ except:\n+ # if we can't make a transparent color, don't leave the old\n+ # transparency hanging around to mess us up.\n+ del(new.info['transparency'])\n+ warnings.warn(\"Couldn't allocate palette entry for transparency\")\n return new\n \n # colorspace conversion\n if dither is None:\n dither = FLOYDSTEINBERG\n-\n- # Use transparent conversion to promote from transparent color to an alpha channel.\n- if self.mode in (\"L\", \"RGB\") and mode == \"RGBA\" and \"transparency\" in self.info:\n- return self._new(self.im.convert_transparent(mode, self.info['transparency']))\n- \n+ \n try:\n im = self.im.convert(mode, dither)\n except ValueError:\n@@ -760,9 +804,22 @@ class Image:\n except KeyError:\n raise ValueError(\"illegal conversion\")\n \n- return self._new(im)\n+ new_im = self._new(im)\n+ if delete_trns:\n+ #crash fail if we leave a bytes transparency in an rgb/l mode.\n+ del(new.info['transparency'])\n+ if trns is not None:\n+ if new_im.mode == 'P':\n+ try:\n+ new_im.info['transparency'] = new_im.palette.getcolor(trns)\n+ except:\n+ del(new_im.info['transparency'])\n+ warnings.warn(\"Couldn't allocate palette entry for transparency\")\n+ else:\n+ new_im.info['transparency'] = trns\n+ return new_im\n \n- def quantize(self, colors=256, method=0, kmeans=0, palette=None):\n+ def quantize(self, colors=256, method=None, kmeans=0, palette=None):\n \n # methods:\n # 0 = median cut\n@@ -773,7 +830,18 @@ class Image:\n # quantizer interface in a later version of PIL.\n \n self.load()\n-\n+ \n+ if method is None:\n+ # defaults:\n+ method = 0\n+ if self.mode == 'RGBA':\n+ method = 2\n+\n+ if self.mode == 'RGBA' and method != 2:\n+ # Caller specified an invalid mode. \n+ raise ValueError('Fast Octree (method == 2) is the ' +\n+ ' only valid method for quantizing RGBA images')\n+ \n if palette:\n # use palette from reference image\n palette.load()\n", "test_patch": "diff --git a/Tests/test_image_convert.py b/Tests/test_image_convert.py\nindex fd3d39bc..4d40e43b 100644\n--- a/Tests/test_image_convert.py\n+++ b/Tests/test_image_convert.py\n@@ -46,5 +46,67 @@ def test_16bit_workaround():\n im = Image.open('Tests/images/16bit.cropped.tif')\n _test_float_conversion(im.convert('I'))\n \n+def test_rgba_p():\n+ im = lena('RGBA')\n+ im.putalpha(lena('L'))\n \n+ converted = im.convert('P')\n+ comparable = converted.convert('RGBA')\n+\n+ assert_image_similar(im, comparable, 20)\n+ \n+def test_trns_p(): \n+ im = lena('P')\n+ im.info['transparency']=0\n+\n+ f = tempfile('temp.png')\n+\n+ l = im.convert('L')\n+ assert_equal(l.info['transparency'], 0) # undone\n+ assert_no_exception(lambda: l.save(f))\n+\n+\n+ rgb = im.convert('RGB')\n+ assert_equal(rgb.info['transparency'], (0,0,0)) # undone\n+ assert_no_exception(lambda: rgb.save(f))\n+ \n+def test_trns_l():\n+ im = lena('L')\n+ im.info['transparency'] = 128\n+\n+ f = tempfile('temp.png')\n+ \n+ rgb = im.convert('RGB')\n+ assert_equal(rgb.info['transparency'], (128,128,128)) # undone\n+ assert_no_exception(lambda: rgb.save(f))\n+\n+ p = im.convert('P')\n+ assert_true('transparency' in p.info)\n+ assert_no_exception(lambda: p.save(f))\n+\n+ p = assert_warning(UserWarning,\n+ lambda: im.convert('P', palette = Image.ADAPTIVE))\n+ assert_false('transparency' in p.info)\n+ assert_no_exception(lambda: p.save(f))\n+\n+ \n+def test_trns_RGB():\n+ im = lena('RGB')\n+ im.info['transparency'] = im.getpixel((0,0))\n+\n+ f = tempfile('temp.png')\n+ \n+ l = im.convert('L')\n+ assert_equal(l.info['transparency'], l.getpixel((0,0))) # undone\n+ assert_no_exception(lambda: l.save(f))\n+\n+ p = im.convert('P')\n+ assert_true('transparency' in p.info)\n+ assert_no_exception(lambda: p.save(f))\n \n+ p = assert_warning(UserWarning,\n+ lambda: im.convert('P', palette = Image.ADAPTIVE))\n+ assert_false('transparency' in p.info)\n+ assert_no_exception(lambda: p.save(f))\n+\n+\ndiff --git a/Tests/test_image_quantize.py b/Tests/test_image_quantize.py\nindex 70b5eb50..dbf68a25 100644\n--- a/Tests/test_image_quantize.py\n+++ b/Tests/test_image_quantize.py\n@@ -19,4 +19,9 @@ def test_octree_quantize():\n im = im.quantize(100, Image.FASTOCTREE)\n assert_image(im, \"P\", im.size)\n \n- assert len(im.getcolors()) == 100\n\\ No newline at end of file\n+ assert len(im.getcolors()) == 100\n+\n+def test_rgba_quantize():\n+ im = lena('RGBA')\n+ assert_no_exception(lambda: im.quantize())\n+ assert_exception(Exception, lambda: im.quantize(method=0))\ndiff --git a/Tests/tester.py b/Tests/tester.py\nindex d4309e3e..f7e2c26c 100644\n--- a/Tests/tester.py\n+++ b/Tests/tester.py\n@@ -121,9 +121,9 @@ def assert_no_exception(func):\n def assert_warning(warn_class, func):\n # note: this assert calls func three times!\n import warnings\n- def warn_error(message, category, **options):\n+ def warn_error(message, category=UserWarning, **options):\n raise category(message)\n- def warn_ignore(message, category, **options):\n+ def warn_ignore(message, category=UserWarning, **options):\n pass\n warn = warnings.warn\n result = None\n", "FAIL_TO_PASS": ["Tests/test_image_convert.py::test_rgba_p", "Tests/test_image_convert.py::test_trns_p", "Tests/test_image_convert.py::test_trns_l", "Tests/test_image_convert.py::test_trns_RGB", "Tests/test_image_quantize.py::test_rgba_quantize"], "PASS_TO_PASS": ["Tests/test_image_convert.py::test_default", "Tests/test_image_convert.py::test_8bit", "Tests/test_image_quantize.py::test_octree_quantize"]} +{"instance_id": "clb-pyc-070", "repo": "ultrajson/ultrajson", "base_commit": "9c589d1cb5dc81552aa8ee72694cb830bed099c6", "problem_statement": "'indent' parameter for `dumps` doesn't indent properly in 3.0.0\nI'm unsure if this is also a problem in other places.\r\n\r\n### What actually happened?\r\n\r\nUsing the example in `README.rst`:\r\n\r\n- ujson version 3.0.0\r\n```python\r\n>>> import ujson\r\n>>> ujson.dumps({\"foo\": \"bar\"})\r\n'{\"foo\":\"bar\"}'\r\n>>> ujson.dumps({\"foo\": \"bar\"}, indent=4)\r\n'{\\n \"foo\": \"bar\"\\n}'\r\n>>> ujson.dumps({\"foo\": \"bar\"}, indent=20)\r\n'{\\n \"foo\": \"bar\"\\n}'\r\n```\r\n\r\n- ujson version 2.0.3\r\n```python\r\n>>> import ujson\r\n>>> ujson.dumps({\"foo\": \"bar\"})\r\n'{\"foo\":\"bar\"}'\r\n>>> ujson.dumps({\"foo\": \"bar\"}, indent=4)\r\n'{\\n \"foo\": \"bar\"\\n}'\r\n>>> ujson.dumps({\"foo\": \"bar\"}, indent=20)\r\n'{\\n \"foo\": \"bar\"\\n}'\r\n```\r\n\r\n### What versions are you using?\r\n\r\n* OS: Ubuntu 18.04\r\n* Python: 3.8.1\r\n* UltraJSON: 3.0.0 (works properly in 2.0.3)\n", "image": {"image_id": "sha256:90abe0b0aa3f2bd61d589f13a17566da1044a9f66cab7ce180803cb5887f9bcb", "pull_reference": "yutu0814/pyc-case-070-ultrajson@sha256:90abe0b0aa3f2bd61d589f13a17566da1044a9f66cab7ce180803cb5887f9bcb"}, "cohort": "python50", "patch": "diff --git a/python/objToJSON.c b/python/objToJSON.c\nindex d7be6f6..5d96485 100644\n--- a/python/objToJSON.c\n+++ b/python/objToJSON.c\n@@ -783,7 +783,7 @@ PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)\n \n PRINTMARK();\n \n- if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"O|OOOOpii\", kwlist, &oinput, &oensureAscii, &oencodeHTMLChars, &oescapeForwardSlashes, &osortKeys, &encoder.indent, &allowNan, &orejectBytes))\n+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"O|OOOOiii\", kwlist, &oinput, &oensureAscii, &oencodeHTMLChars, &oescapeForwardSlashes, &osortKeys, &encoder.indent, &allowNan, &orejectBytes))\n {\n return NULL;\n }\n", "test_patch": "diff --git a/tests/test_ujson.py b/tests/test_ujson.py\nindex 9123254..0c2f4cd 100644\n--- a/tests/test_ujson.py\n+++ b/tests/test_ujson.py\n@@ -249,6 +249,13 @@ def test_encode_to_utf8():\n assert dec == json.loads(enc)\n \n \n+def test_encode_indent():\n+ test_input = '{\\n \"obj\": 31337\\n}'\n+ obj = ujson.decode(test_input)\n+ output = ujson.encode(obj, indent=4)\n+ assert test_input == output\n+\n+\n def test_decode_from_unicode():\n test_input = '{\"obj\": 31337}'\n dec1 = ujson.decode(test_input)\n", "FAIL_TO_PASS": ["tests/test_ujson.py::test_encode_indent"], "PASS_TO_PASS": ["tests/test_ujson.py::test_encode_dict_conversion", "tests/test_ujson.py::test_encode_list_conversion", "tests/test_ujson.py::test_decode_from_unicode"]} +{"instance_id": "clb-pyc-071", "repo": "ultrajson/ultrajson", "base_commit": "f26f9679f1b9d7fa2d0488e1e7b1256d9391a85f", "problem_statement": "Indented empty array/object serialization differs from stdlib\nIn most cases with `escape_forward_slashes=False` `ujson` matches the stdlib `json`, but with empty objects it doesn't.\r\n\r\n* OS: ArchLinux\r\n* Python: 3.8.5\r\n* UltraJSON: 3.2.0\r\n\r\n```python\r\nIn [4]: ujson.dumps({}, indent=1)\r\nOut[4]: '{\\n\\n}'\r\n\r\nIn [5]: ujson.dumps([], indent=1)\r\nOut[5]: '[\\n\\n]'\r\n\r\nIn [8]: json.dumps({}, indent=1)\r\nOut[8]: '{}'\r\n\r\nIn [9]: json.dumps([], indent=1)\r\nOut[9]: '[]'\r\n```\r\n\r\nIt would be nice if `ujson` could match stdlib in this case too.\n", "image": {"image_id": "sha256:cccd9f8154691264a74f0304fc6ef42e3176983d9c404de0da999c76a38cec66", "pull_reference": "yutu0814/pyc-case-071-ultrajson@sha256:cccd9f8154691264a74f0304fc6ef42e3176983d9c404de0da999c76a38cec66"}, "cohort": "python50", "patch": "diff --git a/lib/ultrajsonenc.c b/lib/ultrajsonenc.c\nindex 097e887..a0587f3 100644\n--- a/lib/ultrajsonenc.c\n+++ b/lib/ultrajsonenc.c\n@@ -665,7 +665,6 @@ static void encode(JSOBJ obj, JSONObjectEncoder *enc, const char *name, size_t c\n count = 0;\n \n Buffer_AppendCharUnchecked (enc, '[');\n- Buffer_AppendIndentNewlineUnchecked (enc);\n \n while (enc->iterNext(obj, &tc))\n {\n@@ -675,8 +674,8 @@ static void encode(JSOBJ obj, JSONObjectEncoder *enc, const char *name, size_t c\n #ifndef JSON_NO_EXTRA_WHITESPACE\n Buffer_AppendCharUnchecked (enc, ' ');\n #endif\n- Buffer_AppendIndentNewlineUnchecked (enc);\n }\n+ Buffer_AppendIndentNewlineUnchecked (enc);\n \n iterObj = enc->iterGetValue(obj, &tc);\n \n@@ -687,8 +686,11 @@ static void encode(JSOBJ obj, JSONObjectEncoder *enc, const char *name, size_t c\n }\n \n enc->iterEnd(obj, &tc);\n- Buffer_AppendIndentNewlineUnchecked (enc);\n- Buffer_AppendIndentUnchecked (enc, enc->level);\n+\n+ if (count > 0) {\n+ Buffer_AppendIndentNewlineUnchecked (enc);\n+ Buffer_AppendIndentUnchecked (enc, enc->level);\n+ }\n Buffer_AppendCharUnchecked (enc, ']');\n break;\n }\n@@ -698,7 +700,6 @@ static void encode(JSOBJ obj, JSONObjectEncoder *enc, const char *name, size_t c\n count = 0;\n \n Buffer_AppendCharUnchecked (enc, '{');\n- Buffer_AppendIndentNewlineUnchecked (enc);\n \n while ((res = enc->iterNext(obj, &tc)))\n {\n@@ -716,8 +717,8 @@ static void encode(JSOBJ obj, JSONObjectEncoder *enc, const char *name, size_t c\n #ifndef JSON_NO_EXTRA_WHITESPACE\n Buffer_AppendCharUnchecked (enc, ' ');\n #endif\n- Buffer_AppendIndentNewlineUnchecked (enc);\n }\n+ Buffer_AppendIndentNewlineUnchecked (enc);\n \n iterObj = enc->iterGetValue(obj, &tc);\n objName = enc->iterGetName(obj, &tc, &szlen);\n@@ -729,8 +730,11 @@ static void encode(JSOBJ obj, JSONObjectEncoder *enc, const char *name, size_t c\n }\n \n enc->iterEnd(obj, &tc);\n- Buffer_AppendIndentNewlineUnchecked (enc);\n- Buffer_AppendIndentUnchecked (enc, enc->level);\n+\n+ if (count > 0) {\n+ Buffer_AppendIndentNewlineUnchecked (enc);\n+ Buffer_AppendIndentUnchecked (enc, enc->level);\n+ }\n Buffer_AppendCharUnchecked (enc, '}');\n break;\n }\n", "test_patch": "diff --git a/tests/test_ujson.py b/tests/test_ujson.py\nindex b11e5d2..9d37b47 100644\n--- a/tests/test_ujson.py\n+++ b/tests/test_ujson.py\n@@ -249,11 +249,21 @@ def test_encode_to_utf8():\n assert dec == json.loads(enc)\n \n \n-def test_encode_indent():\n- test_input = '{\\n \"obj\": 31337\\n}'\n+@pytest.mark.parametrize(\n+ \"test_input\",\n+ [\n+ '{\\n \"obj\": 31337\\n}',\n+ \"{}\",\n+ \"[]\",\n+ '{\\n \"a\": {}\\n}',\n+ \"[\\n []\\n]\",\n+ ],\n+)\n+def test_encode_indent(test_input):\n obj = ujson.decode(test_input)\n output = ujson.encode(obj, indent=4)\n assert test_input == output\n+ assert output == json.dumps(obj, indent=4)\n \n \n def test_decode_from_unicode():\n", "FAIL_TO_PASS": ["tests/test_ujson.py::test_encode_indent[{}]", "tests/test_ujson.py::test_encode_indent[[]]", "tests/test_ujson.py::test_encode_indent[{\\n \"a\": {}\\n}]", "tests/test_ujson.py::test_encode_indent[[\\n []\\n]]"], "PASS_TO_PASS": ["tests/test_ujson.py::test_encode_dict_conversion", "tests/test_ujson.py::test_encode_list_conversion", "tests/test_ujson.py::test_decode_from_unicode", "tests/test_ujson.py::test_encode_indent[{\\n \"obj\": 31337\\n}]"]} +{"instance_id": "clb-pyc-075", "repo": "pygame/pygame", "base_commit": "0589ca062fa624f4bf2a9ebea7aedb2a08b37780", "problem_statement": "Proposal: pygame.time.set_event_timer method accept Event class as parameter\nNow pygame.time.set_timer(eventid, milliseconds, once) only accepts an integer as eventid parameter.\r\nOther event methods can differentiate events with the same event id by additional parameters and I can define and push user defined events with self defined parameters. As of now this is not possible for timer events.\r\nSince the number of user event ids is limited, applications with many different timer event types have to rely on other timer methods.\r\n\r\nProposal:\r\n\r\nImplementation of a new method pygame.time.set_event_timer(event, milliseconds, once) \r\nwhere the event parameter is an event created by pygame.event.Event\r\n\r\nI believe, that this would enhance the usability for applications with many different timer event types very much \r\n\r\n**Related Docs:** https://www.pygame.org/docs/ref/time.html#pygame.time.set_timer\r\n\r\n \r\n\npygame.time.set_timer() accept numevents argument\nCurrently, pygame.time.set_timer() has only two options, it can either keep sending events forever, or send once and stop.\r\nIMHO, it would be more useful if we had a way to send a particular amount of events, that can be easily specified by the user.\r\nI know a way to make this work, and I can implement it, if you all like the idea too.\r\nAnd don’t worry, I won’t break back-compat ;)\r\n\r\nPS: Event refactor PR is almost done, took me half an hour to write the description for the PR, so you can expect how long it must be\n", "image": {"image_id": "sha256:09531e41aa8f9ff6c8dfe158e64846c0c11ff89f568409e474c6be948578392b", "pull_reference": "yutu0814/pyc-case-075-pygame@sha256:09531e41aa8f9ff6c8dfe158e64846c0c11ff89f568409e474c6be948578392b"}, "cohort": "python50", "patch": "diff --git a/src_c/_pygame.h b/src_c/_pygame.h\nindex 9261ccbd9..347bb6598 100644\n--- a/src_c/_pygame.h\n+++ b/src_c/_pygame.h\n@@ -103,8 +103,8 @@ typedef enum {\n PGE_WINDOWMOVED,\n PGE_WINDOWRESIZED,\n PGE_WINDOWSIZECHANGED,\n- PGE_WINDOWMINIMISED,\n- PGE_WINDOWMAXIMISED,\n+ PGE_WINDOWMINIMIZED,\n+ PGE_WINDOWMAXIMIZED,\n PGE_WINDOWRESTORED,\n PGE_WINDOWENTER,\n PGE_WINDOWLEAVE,\n@@ -175,8 +175,8 @@ typedef enum {\n PGPOST_WINDOWMOVED,\n PGPOST_WINDOWRESIZED,\n PGPOST_WINDOWSIZECHANGED,\n- PGPOST_WINDOWMINIMISED,\n- PGPOST_WINDOWMAXIMISED,\n+ PGPOST_WINDOWMINIMIZED,\n+ PGPOST_WINDOWMAXIMIZED,\n PGPOST_WINDOWRESTORED,\n PGPOST_WINDOWENTER,\n PGPOST_WINDOWLEAVE,\ndiff --git a/src_c/constants.c b/src_c/constants.c\nindex 8fb6069d3..8ab3baadd 100644\n--- a/src_c/constants.c\n+++ b/src_c/constants.c\n@@ -400,8 +400,8 @@ MODINIT_DEFINE(constants)\n DEC_CONSTS(WINDOWMOVED, PGE_WINDOWMOVED);\n DEC_CONSTS(WINDOWRESIZED, PGE_WINDOWRESIZED);\n DEC_CONSTS(WINDOWSIZECHANGED, PGE_WINDOWSIZECHANGED);\n- DEC_CONSTS(WINDOWMINIMISED, PGE_WINDOWMINIMISED);\n- DEC_CONSTS(WINDOWMAXIMISED, PGE_WINDOWMAXIMISED);\n+ DEC_CONSTS(WINDOWMINIMIZED, PGE_WINDOWMINIMIZED);\n+ DEC_CONSTS(WINDOWMAXIMIZED, PGE_WINDOWMAXIMIZED);\n DEC_CONSTS(WINDOWRESTORED, PGE_WINDOWRESTORED);\n DEC_CONSTS(WINDOWENTER, PGE_WINDOWENTER);\n DEC_CONSTS(WINDOWLEAVE, PGE_WINDOWLEAVE);\n@@ -507,8 +507,8 @@ MODINIT_DEFINE(constants)\n DEC_CONSTS(WINDOWMOVED, -1);\n DEC_CONSTS(WINDOWRESIZED, -1);\n DEC_CONSTS(WINDOWSIZECHANGED, -1);\n- DEC_CONSTS(WINDOWMINIMISED, -1);\n- DEC_CONSTS(WINDOWMAXIMISED, -1);\n+ DEC_CONSTS(WINDOWMINIMIZED, -1);\n+ DEC_CONSTS(WINDOWMAXIMIZED, -1);\n DEC_CONSTS(WINDOWRESTORED, -1);\n DEC_CONSTS(WINDOWENTER, -1);\n DEC_CONSTS(WINDOWLEAVE, -1);\ndiff --git a/src_c/event.c b/src_c/event.c\nindex 93feec86e..b72975286 100644\n--- a/src_c/event.c\n+++ b/src_c/event.c\n@@ -45,16 +45,17 @@ static int have_registered_events = 0;\n #define JOYEVENT_DEVICE_INDEX \"device_index\"\n \n /* Define custom functions for peep events, for SDL1/2 compat */\n-#define PG_PEEP_EVENT(x, y, z) SDL_PeepEvents(x, 1, y, z, z)\n-#define PG_PEEP_EVENT_ALL(x, y) SDL_PeepEvents(x, 1, y, SDL_FIRSTEVENT, SDL_LASTEVENT)\n+#define PG_PEEP_EVENT(a, b, c, d) SDL_PeepEvents(a, b, c, d, d)\n+#define PG_PEEP_EVENT_ALL(x, y, z) \\\n+ SDL_PeepEvents(x, y, z, SDL_FIRSTEVENT, SDL_LASTEVENT)\n \n #else /* IS_SLDv1 */\n \n #define JOYEVENT_INSTANCE_ID \"joy\"\n #define JOYEVENT_DEVICE_INDEX \"joy\"\n \n-#define PG_PEEP_EVENT(x, y, z) SDL_PeepEvents(x, 1, y, SDL_EVENTMASK(z))\n-#define PG_PEEP_EVENT_ALL(x, y) SDL_PeepEvents(x, 1, y, SDL_ALLEVENTS)\n+#define PG_PEEP_EVENT(a, b, c, d) SDL_PeepEvents(a, b, c, SDL_EVENTMASK(d))\n+#define PG_PEEP_EVENT_ALL(x, y, z) SDL_PeepEvents(x, y, z, SDL_ALLEVENTS)\n \n #endif /* IS_SLDv1 */\n \n@@ -64,6 +65,8 @@ static int have_registered_events = 0;\n \n #define MAX_UINT32 0xFFFFFFFF\n \n+#define PG_GET_LIST_LEN 128\n+\n // Map joystick instance IDs to device ids for partial backwards compatibility\n static PyObject *joy_instance_map = NULL;\n \n@@ -432,10 +435,10 @@ _pg_pgevent_proxify(Uint32 type)\n return PGPOST_WINDOWRESIZED;\n case PGE_WINDOWSIZECHANGED:\n return PGPOST_WINDOWSIZECHANGED;\n- case PGE_WINDOWMINIMISED:\n- return PGPOST_WINDOWMINIMISED;\n- case PGE_WINDOWMAXIMISED:\n- return PGPOST_WINDOWMAXIMISED;\n+ case PGE_WINDOWMINIMIZED:\n+ return PGPOST_WINDOWMINIMIZED;\n+ case PGE_WINDOWMAXIMIZED:\n+ return PGPOST_WINDOWMAXIMIZED;\n case PGE_WINDOWRESTORED:\n return PGPOST_WINDOWRESTORED;\n case PGE_WINDOWENTER:\n@@ -566,10 +569,10 @@ _pg_pgevent_deproxify(Uint32 type)\n return PGE_WINDOWRESIZED;\n case PGPOST_WINDOWSIZECHANGED:\n return PGE_WINDOWSIZECHANGED;\n- case PGPOST_WINDOWMINIMISED:\n- return PGE_WINDOWMINIMISED;\n- case PGPOST_WINDOWMAXIMISED:\n- return PGE_WINDOWMAXIMISED;\n+ case PGPOST_WINDOWMINIMIZED:\n+ return PGE_WINDOWMINIMIZED;\n+ case PGPOST_WINDOWMAXIMIZED:\n+ return PGE_WINDOWMAXIMIZED;\n case PGPOST_WINDOWRESTORED:\n return PGE_WINDOWRESTORED;\n case PGPOST_WINDOWENTER:\n@@ -933,10 +936,10 @@ _pg_name_from_eventtype(int type)\n return \"WindowResized\";\n case PGE_WINDOWSIZECHANGED:\n return \"WindowSizeChanged\";\n- case PGE_WINDOWMINIMISED:\n- return \"WindowMinimised\";\n- case PGE_WINDOWMAXIMISED:\n- return \"WindowMaximised\";\n+ case PGE_WINDOWMINIMIZED:\n+ return \"WindowMinimized\";\n+ case PGE_WINDOWMAXIMIZED:\n+ return \"WindowMaximized\";\n case PGE_WINDOWRESTORED:\n return \"WindowRestored\";\n case PGE_WINDOWENTER:\n@@ -1832,7 +1835,7 @@ _pg_eventtype_as_seq(PyObject *obj, int *len)\n *len = 1;\n if (PySequence_Check(obj)) {\n *len = PySequence_Size(obj);\n- /* The retuned object gets decref'd later, so incref now */\n+ /* The returned object gets decref'd later, so incref now */\n Py_INCREF(obj);\n return obj;\n }\n@@ -1848,9 +1851,9 @@ _pg_flush_events(Uint32 type) {\n #if IS_SDLv1\n SDL_Event event;\n if (type == MAX_UINT32)\n- while (PG_PEEP_EVENT_ALL(&event, SDL_GETEVENT) == 1);\n+ while (PG_PEEP_EVENT_ALL(&event, 1, SDL_GETEVENT) == 1);\n else\n- while (PG_PEEP_EVENT(&event, SDL_GETEVENT, type) == 1);\n+ while (PG_PEEP_EVENT(&event, 1, SDL_GETEVENT, type) == 1);\n #else /* IS_SDLv2 */\n if (type == MAX_UINT32)\n SDL_FlushEvents(SDL_FIRSTEVENT, SDL_LASTEVENT);\n@@ -1927,11 +1930,93 @@ _pg_event_append_to_list(PyObject *list, SDL_Event *event)\n }\n \n static PyObject *\n-pg_event_get(PyObject *self, PyObject *args, PyObject *kwargs)\n-{\n+_pg_get_all_events(void) {\n+ SDL_Event eventbuf[PG_GET_LIST_LEN];\n+ PyObject *list;\n+ int loop, len = PG_GET_LIST_LEN;\n+\n+ list = PyList_New(0);\n+ if (!list)\n+ return PyErr_NoMemory();\n+\n+ while (len == PG_GET_LIST_LEN) {\n+ len = PG_PEEP_EVENT_ALL(eventbuf, PG_GET_LIST_LEN, SDL_GETEVENT);\n+ if (len == -1) {\n+ PyErr_SetString(pgExc_SDLError, SDL_GetError());\n+ goto error;\n+ }\n+\n+ for (loop = 0; loop < len; loop++) {\n+ if (!_pg_event_append_to_list(list, &eventbuf[loop]))\n+ goto error;\n+ }\n+ }\n+ return list;\n+\n+error:\n+ Py_DECREF(list);\n+ return NULL;\n+}\n+\n+static PyObject *\n+_pg_get_seq_events(PyObject *obj) {\n SDL_Event event;\n int loop, type, len, ret;\n- PyObject *seq = NULL, *list = NULL, *obj = NULL;\n+ PyObject *seq, *list;\n+\n+ list = PyList_New(0);\n+ if (!list)\n+ return PyErr_NoMemory();\n+\n+ seq = _pg_eventtype_as_seq(obj, &len);\n+ if (!seq)\n+ goto error;\n+\n+ for (loop = 0; loop < len; loop++) {\n+ type = _pg_eventtype_from_seq(seq, loop);\n+ if (type == -1)\n+ goto error;\n+\n+ do {\n+ ret = PG_PEEP_EVENT(&event, 1, SDL_GETEVENT, type);\n+ if (ret < 0) {\n+ PyErr_SetString(pgExc_SDLError, SDL_GetError());\n+ goto error;\n+ }\n+ else if (ret > 0) {\n+ if (!_pg_event_append_to_list(list, &event))\n+ goto error;\n+ }\n+ } while (ret);\n+#if IS_SDLv2\n+ do {\n+ ret = PG_PEEP_EVENT(&event, 1, SDL_GETEVENT,\n+ _pg_pgevent_proxify(type));\n+ if (ret < 0) {\n+ PyErr_SetString(pgExc_SDLError, SDL_GetError());\n+ goto error;\n+ }\n+ else if (ret > 0) {\n+ if (!_pg_event_append_to_list(list, &event))\n+ goto error;\n+ }\n+ } while (ret);\n+#endif /* IS_SDLv2 */\n+ }\n+ Py_DECREF(seq);\n+ return list;\n+\n+error:\n+ /* While doing a goto here, PyErr must be set */\n+ Py_DECREF(list);\n+ Py_XDECREF(seq);\n+ return NULL;\n+}\n+\n+static PyObject *\n+pg_event_get(PyObject *self, PyObject *args, PyObject *kwargs)\n+{\n+ PyObject *obj = NULL;\n int dopump = 1;\n \n static char *kwids[] = {\n@@ -1952,64 +2037,13 @@ pg_event_get(PyObject *self, PyObject *args, PyObject *kwargs)\n \n VIDEO_INIT_CHECK();\n \n- list = PyList_New(0);\n- if (!list)\n- return PyErr_NoMemory();\n-\n if (dopump)\n SDL_PumpEvents();\n \n- if (obj == NULL || obj == Py_None) {\n- while (PG_PEEP_EVENT_ALL(&event, SDL_GETEVENT) == 1) {\n- if(!_pg_event_append_to_list(list, &event))\n- goto error;\n- }\n- }\n- else {\n- seq = _pg_eventtype_as_seq(obj, &len);\n- if (!seq)\n- goto error;\n-\n- for (loop = 0; loop < len; loop++) {\n- type = _pg_eventtype_from_seq(seq, loop);\n- if (type == -1)\n- goto error;\n-\n- do {\n- ret = PG_PEEP_EVENT(&event, SDL_GETEVENT, type);\n- if (ret < 0) {\n- PyErr_SetString(pgExc_SDLError, SDL_GetError());\n- goto error;\n- }\n- else if (ret > 0) {\n- if (!_pg_event_append_to_list(list, &event))\n- goto error;\n- }\n- } while (ret);\n-#if IS_SDLv2\n- do {\n- ret = PG_PEEP_EVENT(&event, SDL_GETEVENT,\n- _pg_pgevent_proxify(type));\n- if (ret < 0) {\n- PyErr_SetString(pgExc_SDLError, SDL_GetError());\n- goto error;\n- }\n- else if (ret > 0) {\n- if (!_pg_event_append_to_list(list, &event))\n- goto error;\n- }\n- } while (ret);\n-#endif /* IS_SDLv2 */\n- }\n- Py_DECREF(seq);\n- }\n- return list;\n-\n-error:\n- /* While doing a goto here, PyErr must be set */\n- Py_DECREF(list);\n- Py_XDECREF(seq);\n- return NULL;\n+ if (obj == NULL || obj == Py_None)\n+ return _pg_get_all_events();\n+ else\n+ return _pg_get_seq_events(obj);\n }\n \n static PyObject *\n@@ -2042,7 +2076,7 @@ pg_event_peek(PyObject *self, PyObject *args, PyObject *kwargs)\n SDL_PumpEvents();\n \n if (obj == NULL || obj == Py_None) {\n- res = PG_PEEP_EVENT_ALL(&event, SDL_PEEKEVENT);\n+ res = PG_PEEP_EVENT_ALL(&event, 1, SDL_PEEKEVENT);\n if (res < 0)\n return RAISE(pgExc_SDLError, SDL_GetError());\n return pgEvent_New(res ? &event : NULL);\n@@ -2058,7 +2092,7 @@ pg_event_peek(PyObject *self, PyObject *args, PyObject *kwargs)\n Py_DECREF(seq);\n return NULL;\n }\n- res = PG_PEEP_EVENT(&event, SDL_PEEKEVENT, type);\n+ res = PG_PEEP_EVENT(&event, 1, SDL_PEEKEVENT, type);\n if (res) {\n Py_DECREF(seq);\n \n@@ -2067,8 +2101,8 @@ pg_event_peek(PyObject *self, PyObject *args, PyObject *kwargs)\n return PyInt_FromLong(1);\n }\n #if IS_SDLv2\n- res = PG_PEEP_EVENT(&event, SDL_PEEKEVENT,\n- _pg_pgevent_proxify(type));\n+ res = PG_PEEP_EVENT(&event, 1, SDL_PEEKEVENT,\n+ _pg_pgevent_proxify(type));\n if (res) {\n Py_DECREF(seq);\n \ndiff --git a/src_c/rwobject.c b/src_c/rwobject.c\nindex 1eff5e05a..6e2ab40f8 100644\n--- a/src_c/rwobject.c\n+++ b/src_c/rwobject.c\n@@ -528,6 +528,7 @@ pgRWops_FromFileObject(PyObject *obj)\n static int\n pgRWops_ReleaseObject(SDL_RWops *context)\n {\n+ int ret = 0;\n if (pgRWops_IsFileObject(context)) {\n #ifdef WITH_THREAD\n PyGILState_STATE state = PyGILState_Ensure();\n@@ -549,11 +550,10 @@ pgRWops_ReleaseObject(SDL_RWops *context)\n SDL_FreeRW(context);\n }\n else {\n- int ret;\n- if ((ret = SDL_RWclose(context)) < 0) {\n+ ret = SDL_RWclose(context);\n+ if (ret < 0) {\n PyErr_SetString(PyExc_IOError, SDL_GetError());\n Py_DECREF(fileobj);\n- return ret;\n }\n }\n \n@@ -562,13 +562,11 @@ pgRWops_ReleaseObject(SDL_RWops *context)\n #endif /* WITH_THREAD */\n }\n else {\n- int ret;\n- if ((ret = SDL_RWclose(context)) < 0) {\n+ ret = SDL_RWclose(context);\n+ if (ret < 0)\n PyErr_SetString(PyExc_IOError, SDL_GetError());\n- return ret;\n- }\n }\n- return 0;\n+ return ret;\n }\n \n #if IS_SDLv1\ndiff --git a/src_c/time.c b/src_c/time.c\nindex 5a8d9bbdc..b12d14814 100644\n--- a/src_c/time.c\n+++ b/src_c/time.c\n@@ -37,24 +37,63 @@ typedef struct pgEventTimer {\n static pgEventTimer *pg_event_timer = NULL;\n static SDL_mutex *timermutex = NULL;\n \n+static void\n+_pg_event_timer_cleanup(void)\n+{\n+ pgEventTimer *hunt, *todel;\n+ /* We can let errors silently pass in this function, because this\n+ * needs to run */\n+ SDL_LockMutex(timermutex);\n+ if (pg_event_timer) {\n+ hunt = pg_event_timer;\n+ while (hunt) {\n+ todel = hunt;\n+ hunt = hunt->next;\n+ Py_DECREF(todel->event);\n+ PyMem_Del(todel);\n+ }\n+ pg_event_timer = NULL;\n+ }\n+ SDL_UnlockMutex(timermutex);\n+ /* After we are done, we can destroy the mutex as well */\n+ SDL_DestroyMutex(timermutex);\n+ timermutex = NULL;\n+}\n+\n+static PyObject *\n+pg_time_autoinit(PyObject *self)\n+{\n+ /* register cleanup function for event timer holding structure,\n+ * allocate a mutex for this structure too */\n+ if (!timermutex && !pg_event_timer) {\n+ timermutex = SDL_CreateMutex();\n+ if (!timermutex) {\n+ PyErr_SetString(pgExc_SDLError, SDL_GetError());\n+ return PyInt_FromLong(0);\n+ }\n+ pg_RegisterQuit(_pg_event_timer_cleanup);\n+ }\n+ return PyInt_FromLong(1);\n+}\n+\n static int\n _pg_add_event_timer(pgEventObject *ev, int repeat)\n {\n pgEventTimer *new;\n \n- if (SDL_LockMutex(timermutex) < 0) {\n- /* this case will almost never happen, but still handle it */\n- PyErr_SetString(pgExc_SDLError, SDL_GetError());\n- return 0;\n- }\n-\n new = PyMem_New(pgEventTimer, 1);\n if (!new) {\n- SDL_UnlockMutex(timermutex);\n PyErr_NoMemory();\n return 0;\n }\n \n+ if (SDL_LockMutex(timermutex) < 0) {\n+ /* this case will almost never happen, but still handle it */\n+ PyMem_Del(new);\n+ PyErr_SetString(pgExc_SDLError, SDL_GetError());\n+ return 0;\n+ }\n+\n new->next = pg_event_timer;\n new->event = ev;\n new->repeat = repeat;\n@@ -70,9 +109,7 @@ _pg_remove_event_timer(pgEventObject *ev)\n {\n pgEventTimer *hunt, *prev = NULL;\n \n- if (SDL_LockMutex(timermutex) < 0)\n- return;\n-\n+ SDL_LockMutex(timermutex);\n if (pg_event_timer) {\n hunt = pg_event_timer;\n while (hunt->event->type != ev->type) {\n@@ -97,50 +134,25 @@ _pg_remove_event_timer(pgEventObject *ev)\n static pgEventTimer *\n _pg_get_event_on_timer(pgEventObject *ev)\n {\n- pgEventTimer *hunt, *ret = NULL;\n+ pgEventTimer *hunt;\n \n if (SDL_LockMutex(timermutex) < 0)\n return NULL;\n \n- if (pg_event_timer) {\n- hunt = pg_event_timer;\n- do {\n- if (hunt->event->type == ev->type) {\n- if (hunt->repeat >= 0)\n- hunt->repeat--;\n- ret = hunt;\n- break;\n+ hunt = pg_event_timer;\n+ while (hunt) {\n+ if (hunt->event->type == ev->type) {\n+ if (hunt->repeat >= 0) {\n+ hunt->repeat--;\n }\n- hunt = hunt->next;\n- } while (hunt);\n- }\n- /* Chances of it failing here are next to zero, dont do anything */\n- SDL_UnlockMutex(timermutex);\n- return ret;\n-}\n-\n-static void\n-_pg_event_timer_cleanup(void)\n-{\n- pgEventTimer *hunt, *todel;\n-\n- /* We can let errors silently pass in this function, because this\n- * needs to run */\n- SDL_LockMutex(timermutex);\n- if (pg_event_timer) {\n- hunt = pg_event_timer;\n- while (hunt) {\n- todel = hunt;\n- hunt = hunt->next;\n- Py_DECREF(todel->event);\n- PyMem_Del(todel);\n+ break;\n }\n- pg_event_timer = NULL;\n+ hunt = hunt->next;\n }\n+\n+ /* Chances of it failing here are next to zero, dont do anything */\n SDL_UnlockMutex(timermutex);\n- /* After we are done, we can destroy the mutex as well */\n- SDL_DestroyMutex(timermutex);\n- timermutex = NULL;\n+ return hunt;\n }\n \n static Uint32\n@@ -167,6 +179,9 @@ timer_callback(Uint32 interval, void *param)\n #endif\n Py_DECREF(evtimer->event->dict);\n }\n+ else\n+ evtimer->repeat = 0;\n+\n \n if (!evtimer->repeat) {\n /* This does memory cleanup */\n@@ -273,22 +288,23 @@ time_wait(PyObject *self, PyObject *arg)\n static PyObject *\n time_set_timer(PyObject *self, PyObject *args, PyObject *kwargs)\n {\n- int ticks, once = 0, repeat = 0;\n+ int ticks, loops = 0;\n PyObject *obj;\n pgEventObject *e;\n \n static char *kwids[] = {\n \"event\",\n \"millis\",\n- \"once\",\n- \"repeat\",\n+ \"loops\",\n NULL\n };\n \n- if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"Oi|ii\", kwids,\n- &obj, &ticks, &once, &repeat))\n+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"Oi|i\", kwids,\n+ &obj, &ticks, &loops))\n return NULL;\n \n+ if (!timermutex)\n+ return RAISE(pgExc_SDLError, \"pygame is not initialized\");\n \n if (PyInt_Check(obj)) {\n e = (pgEventObject *)pgEvent_New2(PyInt_AsLong(obj), NULL);\n@@ -319,13 +335,7 @@ time_set_timer(PyObject *self, PyObject *args, PyObject *kwargs)\n }\n }\n \n- /* The repeat argument will determine how many times an event is\n- * posted. If repeat was not passed, we determine the repeat argument\n- * from the once argument */\n- if (!repeat)\n- repeat = once ? 1 : 0;\n-\n- if (!_pg_add_event_timer(e, repeat)) {\n+ if (!_pg_add_event_timer(e, loops)) {\n Py_DECREF(e);\n return NULL;\n }\n@@ -539,6 +549,8 @@ ClockInit(PyObject *self)\n }\n \n static PyMethodDef _time_methods[] = {\n+ {\"__PYGAMEinit__\", (PyCFunction)pg_time_autoinit, METH_NOARGS,\n+ \"auto initialize function for time\"},\n {\"get_ticks\", (PyCFunction)time_get_ticks, METH_NOARGS,\n DOC_PYGAMETIMEGETTICKS},\n {\"delay\", time_delay, METH_VARARGS, DOC_PYGAMETIMEDELAY},\n@@ -588,17 +600,6 @@ MODINIT_DEFINE(time)\n MODINIT_ERROR;\n }\n \n- /* register cleanup function for event timer holding structure,\n- * allocate a mutex for this structure too */\n- if (!timermutex && !pg_event_timer) {\n- timermutex = SDL_CreateMutex();\n- if (!timermutex) {\n- PyErr_SetString(PyExc_ImportError, SDL_GetError());\n- MODINIT_ERROR;\n- }\n- pg_RegisterQuit(_pg_event_timer_cleanup);\n- }\n-\n /* create the module */\n #if PY3\n return PyModule_Create(&_module);\ndiff --git a/src_py/locals.py b/src_py/locals.py\nindex 5952db27c..26461b925 100644\n--- a/src_py/locals.py\n+++ b/src_py/locals.py\n@@ -576,8 +576,8 @@ __all__ = [\n 'WINDOWMOVED',\n 'WINDOWRESIZED',\n 'WINDOWSIZECHANGED',\n- 'WINDOWMINIMISED',\n- 'WINDOWMAXIMISED',\n+ 'WINDOWMINIMIZED',\n+ 'WINDOWMAXIMIZED',\n 'WINDOWRESTORED',\n 'WINDOWENTER',\n 'WINDOWLEAVE',\n", "test_patch": "diff --git a/test/event_test.py b/test/event_test.py\nindex 399f0ee00..34fcd1df6 100644\n--- a/test/event_test.py\n+++ b/test/event_test.py\n@@ -284,7 +284,7 @@ class EventModuleTest(unittest.TestCase):\n \"\"\"Ensures NUMEVENTS does not exceed the maximum SDL number of events.\n \"\"\"\n # Ref: https://www.libsdl.org/tmp/SDL/include/SDL_events.h\n- MAX_SDL_EVENTS = 0xFFFF + 1 # SDL_LASTEVENT = 0xFFFF\n+ MAX_SDL_EVENTS = 0xFFFF # SDL_LASTEVENT = 0xFFFF\n \n self.assertLessEqual(pygame.NUMEVENTS, MAX_SDL_EVENTS)\n \n@@ -345,25 +345,21 @@ class EventModuleTest(unittest.TestCase):\n \n def test_post_and_get_keydown(self):\n \"\"\"Ensure keydown events can be posted to the queue.\"\"\"\n- surf = pygame.display.set_mode((10, 10))\n- pygame.event.get()\n activemodkeys = pygame.key.get_mods()\n \n- events = []\n- events.append(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_p))\n- events.append(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_y, mod=activemodkeys))\n- events.append(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_g, unicode=\"g\"))\n- events.append(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_a, unicode=None))\n- events.append(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_m, mod=None, window=None))\n- events.append(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_e, mod=activemodkeys, unicode=\"e\"))\n+ events = [\n+ pygame.event.Event(pygame.KEYDOWN, key=pygame.K_p),\n+ pygame.event.Event(pygame.KEYDOWN, key=pygame.K_y, mod=activemodkeys),\n+ pygame.event.Event(pygame.KEYDOWN, key=pygame.K_g, unicode=\"g\"),\n+ pygame.event.Event(pygame.KEYDOWN, key=pygame.K_a, unicode=None),\n+ pygame.event.Event(pygame.KEYDOWN, key=pygame.K_m, mod=None, window=None),\n+ pygame.event.Event(pygame.KEYDOWN, key=pygame.K_e, mod=activemodkeys, unicode=\"e\")\n+ ]\n \n for e in events:\n- pygame.event.clear()\n pygame.event.post(e)\n posted_event = pygame.event.poll()\n- self.assertEqual(e.type, posted_event.type, race_condition_notification)\n- self.assertEqual(e.type, pygame.KEYDOWN, race_condition_notification)\n- self.assertEqual(e.key, posted_event.key, race_condition_notification)\n+ self.assertEqual(e, posted_event, race_condition_notification)\n \n def test_post_large_user_event(self):\n pygame.event.post(pygame.event.Event(pygame.USEREVENT, {\"a\": \"a\" * 1024}))\n@@ -372,6 +368,18 @@ class EventModuleTest(unittest.TestCase):\n self.assertEqual(e.type, pygame.USEREVENT)\n self.assertEqual(e.a, \"a\" * 1024)\n \n+ def test_post_blocked(self):\n+ \"\"\"\n+ Test blocked events are not posted. Also test whether post()\n+ returns a boolean correctly\n+ \"\"\"\n+ pygame.event.set_blocked(pygame.USEREVENT)\n+ self.assertFalse(pygame.event.post(pygame.event.Event(pygame.USEREVENT)))\n+ self.assertFalse(pygame.event.poll())\n+ pygame.event.set_allowed(pygame.USEREVENT)\n+ self.assertTrue(pygame.event.post(pygame.event.Event(pygame.USEREVENT)))\n+ self.assertEqual(pygame.event.poll(), pygame.event.Event(pygame.USEREVENT))\n+\n def test_get(self):\n \"\"\"Ensure get() retrieves all the events on the queue.\"\"\"\n event_cnt = 10\n@@ -390,6 +398,14 @@ class EventModuleTest(unittest.TestCase):\n self.assertEqual(len(queue), 1)\n self.assertEqual(queue[0].type, pygame.USEREVENT)\n \n+ TESTEVENTS = 10\n+ for _ in range(TESTEVENTS):\n+ pygame.event.post(ev)\n+ q = pygame.event.get([pygame.USEREVENT])\n+ self.assertEqual(len(q), TESTEVENTS)\n+ for event in q:\n+ self.assertEqual(event, ev)\n+\n def test_get__empty_queue(self):\n \"\"\"Ensure get() works correctly on an empty queue.\"\"\"\n expected_events = []\ndiff --git a/test/time_test.py b/test/time_test.py\nindex 8f99b1db6..da3c5c62e 100644\n--- a/test/time_test.py\n+++ b/test/time_test.py\n@@ -247,7 +247,7 @@ class TimeModuleTest(unittest.TestCase):\n Also tests if setting milliseconds to 0 stops the timer and if\n the once argument and repeat arguments work.\n \"\"\"\n- pygame.display.init()\n+ pygame.init()\n TIMER_EVENT_TYPE = pygame.event.custom_type()\n timer_event = pygame.event.Event(TIMER_EVENT_TYPE)\n delta = 50\n@@ -279,12 +279,12 @@ class TimeModuleTest(unittest.TestCase):\n pygame.time.delay(200)\n self.assertNotIn(timer_event, pygame.event.get())\n \n- # Test that the once argument works\n+ # Test that the loops=True works\n pygame.time.set_timer(TIMER_EVENT_TYPE, 10, True)\n pygame.time.delay(40)\n self.assertEqual(pygame.event.get().count(timer_event), 1)\n \n- # Test a variety of event objects, test repeat argument\n+ # Test a variety of event objects, test loops argument\n events_to_test = [\n pygame.event.Event(TIMER_EVENT_TYPE),\n pygame.event.Event(TIMER_EVENT_TYPE, foo=\"9gwz5\", baz=12,\n@@ -294,9 +294,10 @@ class TimeModuleTest(unittest.TestCase):\n repeat = 3\n millis = 50\n for e in events_to_test:\n- pygame.time.set_timer(e, millis, repeat=repeat)\n+ pygame.time.set_timer(e, millis, loops=repeat)\n pygame.time.delay(2 * millis * repeat)\n self.assertEqual(pygame.event.get().count(e), repeat)\n+ pygame.quit()\n \n def test_wait(self):\n \"\"\"Tests time.wait() function.\"\"\"\n", "FAIL_TO_PASS": ["test/time_test.py::TimeModuleTest::test_set_timer"], "PASS_TO_PASS": ["test/event_test.py::EventModuleTest::test_post_large_user_event", "test/event_test.py::EventModuleTest::test_get_type", "test/event_test.py::EventModuleTest::test_post_blocked"]} +{"instance_id": "clb-pyc-077", "repo": "pygame/pygame", "base_commit": "c09d677a6c1c2e814683576035f13c6a07d64f67", "problem_statement": "pygame.draw.rect() with width > 1 has weird corners\n**Environment:**\r\n\r\n- **Operating system** (e.g. Windows, Linux(Debian), Linux(Ubuntu), Mac): Linux (Ubuntu)\r\n- **Python version** (e.g. 3.7.9, 3.8.5) : 3.9.7\r\n- **SDL version** (e.g. SDL 2.0.12): 2.0.16\r\n- **PyGame version** (e.g. 2.0.0.dev10, 1.9.6): 2.1.0\r\n**Current behavior:**\r\n\r\n![rect](https://user-images.githubusercontent.com/617224/143325878-37b13319-d33e-4c83-9af9-407ddc6d5f59.png)\r\n\r\nOn the left is the output of \r\n\r\n```python\r\npygame.draw.rect(screen, (255, 255, 0), Rect((20, 20), (100, 100)), width=9)\r\n```\r\n\r\nThe right is what I expect. I implemented this by drawing 4 filled rects.\n", "image": {"image_id": "sha256:9033751a383ee84641f989c2efc2da75bec96025e77dda11dd9736a992a9a912", "pull_reference": "yutu0814/pyc-case-077-pygame@sha256:9033751a383ee84641f989c2efc2da75bec96025e77dda11dd9736a992a9a912"}, "cohort": "python50", "patch": "diff --git a/src_c/draw.c b/src_c/draw.c\nindex 2ac377236..7763b80c7 100644\n--- a/src_c/draw.c\n+++ b/src_c/draw.c\n@@ -74,6 +74,9 @@ static void\n draw_fillpoly(SDL_Surface *surf, int *vx, int *vy, Py_ssize_t n, Uint32 color,\n int *drawn_area);\n static void\n+draw_rect(SDL_Surface *surf, int x1, int y1, int x2, int y2, int width,\n+ Uint32 color);\n+static void\n draw_round_rect(SDL_Surface *surf, int x1, int y1, int x2, int y2, int radius,\n int width, Uint32 color, int top_left, int top_right,\n int bottom_left, int bottom_right, int *drawn_area);\n@@ -870,8 +873,7 @@ rect(PyObject *self, PyObject *args, PyObject *kwargs)\n SDL_Surface *surf = NULL;\n Uint8 rgba[4];\n Uint32 color;\n- int t, l, b, r, width = 0, radius = 0; /* Default values. */\n- int x, y, w, h; /* Fields for the rounded rect draw to \"normalize\" into */\n+ int width = 0, radius = 0; /* Default values. */\n int top_left_radius = -1, top_right_radius = -1, bottom_left_radius = -1,\n bottom_right_radius = -1;\n SDL_Rect sdlrect;\n@@ -921,37 +923,22 @@ rect(PyObject *self, PyObject *args, PyObject *kwargs)\n if ((radius <= 0 && top_left_radius <= 0 && top_right_radius <= 0 &&\n bottom_left_radius <= 0 && bottom_right_radius <= 0) ||\n abs(rect->w) < 2 || abs(rect->h) < 2) {\n- if (width > 0) {\n- l = rect->x;\n- r = rect->x + rect->w - 1;\n- t = rect->y;\n- b = rect->y + rect->h - 1;\n- points =\n- Py_BuildValue(\"((ii)(ii)(ii)(ii))\", l, t, r, t, r, b, l, b);\n- poly_args =\n- Py_BuildValue(\"(OONi)\", surfobj, colorobj, points, width);\n- if (NULL == poly_args) {\n- return NULL; /* Exception already set. */\n- }\n-\n- ret = polygon(NULL, poly_args, NULL);\n- Py_DECREF(poly_args);\n- return ret;\n+ sdlrect.x = rect->x;\n+ sdlrect.y = rect->y;\n+ sdlrect.w = rect->w;\n+ sdlrect.h = rect->h;\n+ SDL_GetClipRect(surf, &cliprect);\n+ /* SDL_FillRect respects the clip rect already, but in order to\n+ return the drawn area, we need to do this here, and keep the\n+ pointer to the result in clipped */\n+ if (!SDL_IntersectRect(&sdlrect, &cliprect, &clipped)) {\n+ return pgRect_New4(rect->x, rect->y, 0, 0);\n+ }\n+ if (width > 0 && (width * 2) < clipped.w && (width * 2) < clipped.h) {\n+ draw_rect(surf, sdlrect.x, sdlrect.y, sdlrect.x + sdlrect.w - 1,\n+ sdlrect.y + sdlrect.h - 1, width, color);\n }\n else {\n- sdlrect.x = rect->x;\n- sdlrect.y = rect->y;\n- sdlrect.w = rect->w;\n- sdlrect.h = rect->h;\n-\n- SDL_GetClipRect(surf, &cliprect);\n-\n- /* SDL_FillRect respects the clip rect already, but in order to\n- return the drawn area, we need to do this here, and keep the\n- pointer to the result in clipped */\n- if (!SDL_IntersectRect(&sdlrect, &cliprect, &clipped)) {\n- return pgRect_New4(rect->x, rect->y, 0, 0);\n- }\n pgSurface_Prep(surfobj);\n pgSurface_Lock(surfobj);\n result = SDL_FillRect(surf, &clipped, color);\n@@ -959,8 +946,8 @@ rect(PyObject *self, PyObject *args, PyObject *kwargs)\n pgSurface_Unprep(surfobj);\n if (result != 0)\n return RAISE(pgExc_SDLError, SDL_GetError());\n- return pgRect_New(&clipped);\n }\n+ return pgRect_New(&clipped);\n }\n else {\n if (!pgSurface_Lock(surfobj)) {\n@@ -969,26 +956,21 @@ rect(PyObject *self, PyObject *args, PyObject *kwargs)\n \n /* Little bit to normalize the rect: this matters for the rounded\n rects, despite not mattering for the normal rects. */\n- x = rect->x;\n- y = rect->y;\n- w = rect->w;\n- h = rect->h;\n-\n- if (w < 0) {\n- x += w;\n- w = -w;\n+ if (rect->w < 0) {\n+ rect->x += rect->w;\n+ rect->w = -rect->w;\n }\n-\n- if (h < 0) {\n- y += h;\n- h = -h;\n+ if (rect->h < 0) {\n+ rect->y += rect->h;\n+ rect->h = -rect->h;\n }\n \n- if (width > w / 2 || width > h / 2) {\n- width = MAX(w / 2, h / 2);\n+ if (width > rect->w / 2 || width > rect->h / 2) {\n+ width = MAX(rect->w / 2, rect->h / 2);\n }\n \n- draw_round_rect(surf, x, y, x + w - 1, y + h - 1, radius, width, color,\n+ draw_round_rect(surf, rect->x, rect->y, rect->x + rect->w - 1,\n+ rect->y + rect->h - 1, radius, width, color,\n top_left_radius, top_right_radius, bottom_left_radius,\n bottom_right_radius, drawn_area);\n if (!pgSurface_Unlock(surfobj)) {\n@@ -1440,8 +1422,33 @@ drawhorzline(SDL_Surface *surf, Uint32 color, int x1, int y1, int x2)\n }\n \n static void\n-drawhorzlineclip(SDL_Surface *surf, Uint32 color, int x1, int y1, int x2,\n- int *pts)\n+drawhorzlineclip(SDL_Surface *surf, Uint32 color, int x1, int y1, int x2)\n+{\n+ if (y1 < surf->clip_rect.y || y1 >= surf->clip_rect.y + surf->clip_rect.h)\n+ return;\n+\n+ if (x2 < x1) {\n+ int temp = x1;\n+ x1 = x2;\n+ x2 = temp;\n+ }\n+\n+ x1 = MAX(x1, surf->clip_rect.x);\n+ x2 = MIN(x2, surf->clip_rect.x + surf->clip_rect.w - 1);\n+\n+ if (x2 < surf->clip_rect.x || x1 >= surf->clip_rect.x + surf->clip_rect.w)\n+ return;\n+\n+ if (x1 == x2) {\n+ set_at(surf, x1, y1, color);\n+ return;\n+ }\n+ drawhorzline(surf, color, x1, y1, x2);\n+}\n+\n+static void\n+drawhorzlineclipbounding(SDL_Surface *surf, Uint32 color, int x1, int y1,\n+ int x2, int *pts)\n {\n if (y1 < surf->clip_rect.y || y1 >= surf->clip_rect.y + surf->clip_rect.h)\n return;\n@@ -1512,8 +1519,8 @@ draw_line_width(SDL_Surface *surf, Uint32 color, int x1, int y1, int x2,\n }\n while ((sign(x1 - x2, sx) != sx) || (sign(y1 - y2, sy) != sy)) {\n if (xinc)\n- drawhorzlineclip(surf, color, left_top, y1, right_bottom,\n- drawn_area);\n+ drawhorzlineclipbounding(surf, color, left_top, y1,\n+ right_bottom, drawn_area);\n else {\n for (y = left_top; y <= right_bottom; y++)\n set_and_check_rect(surf, x1, y, color, drawn_area);\n@@ -1539,8 +1546,8 @@ draw_line_width(SDL_Surface *surf, Uint32 color, int x1, int y1, int x2,\n if (xinc) {\n while (y1 != end_y && (inside_clip(surf, left_top, y1) ||\n inside_clip(surf, right_bottom, y1))) {\n- drawhorzlineclip(surf, color, left_top, y1, right_bottom,\n- drawn_area);\n+ drawhorzlineclipbounding(surf, color, left_top, y1,\n+ right_bottom, drawn_area);\n e2 = err;\n if (e2 > -dx) {\n err -= dy;\n@@ -1553,8 +1560,8 @@ draw_line_width(SDL_Surface *surf, Uint32 color, int x1, int y1, int x2,\n y1 += sy;\n }\n }\n- drawhorzlineclip(surf, color, left_top, y1, right_bottom,\n- drawn_area);\n+ drawhorzlineclipbounding(surf, color, left_top, y1,\n+ right_bottom, drawn_area);\n }\n else {\n while (x1 != end_x && (inside_clip(surf, x1, left_top) ||\n@@ -1958,14 +1965,15 @@ draw_circle_filled(SDL_Surface *surf, int x0, int y0, int radius, Uint32 color,\n /* optimisation to avoid overdrawing and repeated return rect checks:\n only draw a line if y-step is about to be decreased. */\n if (f >= 0) {\n- drawhorzlineclip(surf, color, x0 - x, y0 + y - 1, x0 + x - 1,\n- drawn_area);\n- drawhorzlineclip(surf, color, x0 - x, y0 - y, x0 + x - 1,\n- drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - x, y0 + y - 1,\n+ x0 + x - 1, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - x, y0 - y, x0 + x - 1,\n+ drawn_area);\n }\n- drawhorzlineclip(surf, color, x0 - y, y0 + x - 1, x0 + y - 1,\n- drawn_area);\n- drawhorzlineclip(surf, color, x0 - y, y0 - x, x0 + y - 1, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - y, y0 + x - 1, x0 + y - 1,\n+ drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - y, y0 - x, x0 + y - 1,\n+ drawn_area);\n }\n }\n \n@@ -1981,7 +1989,8 @@ draw_ellipse_filled(SDL_Surface *surf, int x0, int y0, int width, int height,\n return;\n }\n if (height == 1) {\n- drawhorzlineclip(surf, color, x0, y0, x0 + width - 1, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0, y0, x0 + width - 1,\n+ drawn_area);\n return;\n }\n x0 = x0 + width / 2;\n@@ -1996,10 +2005,11 @@ draw_ellipse_filled(SDL_Surface *surf, int x0, int y0, int width, int height,\n dx = 2 * height * height * x;\n dy = 2 * width * width * y;\n while (dx < dy) {\n- drawhorzlineclip(surf, color, x0 - x, y0 - y, x0 + x - x_offset,\n- drawn_area);\n- drawhorzlineclip(surf, color, x0 - x, y0 + y - y_offset,\n- x0 + x - x_offset, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x, y0 - (int)y,\n+ x0 + (int)x - x_offset, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x,\n+ y0 + (int)y - y_offset,\n+ x0 + (int)x - x_offset, drawn_area);\n if (d1 < 0) {\n x++;\n dx = dx + (2 * height * height);\n@@ -2017,10 +2027,11 @@ draw_ellipse_filled(SDL_Surface *surf, int x0, int y0, int width, int height,\n (((double)width * width) * ((y - 1) * (y - 1))) -\n ((double)width * width * height * height);\n while (y >= 0) {\n- drawhorzlineclip(surf, color, x0 - x, y0 - y, x0 + x - x_offset,\n- drawn_area);\n- drawhorzlineclip(surf, color, x0 - x, y0 + y - y_offset,\n- x0 + x - x_offset, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x, y0 - (int)y,\n+ x0 + (int)x - x_offset, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x,\n+ y0 + (int)y - y_offset,\n+ x0 + (int)x - x_offset, drawn_area);\n if (d2 > 0) {\n y--;\n dy = dy - (2 * width * width);\n@@ -2066,20 +2077,24 @@ draw_ellipse_thickness(SDL_Surface *surf, int x0, int y0, int width,\n dy_inner = 2 * (width - thickness) * (width - thickness) * y_inner;\n while (dx < dy) {\n if (line) {\n- drawhorzlineclip(surf, color, x0 - x, y0 - y, x0 + x - x_offset,\n- drawn_area);\n- drawhorzlineclip(surf, color, x0 - x, y0 + y - y_offset,\n- x0 + x - x_offset, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x, y0 - (int)y,\n+ x0 + (int)x - x_offset, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x,\n+ y0 + (int)y - y_offset,\n+ x0 + (int)x - x_offset, drawn_area);\n }\n else {\n- drawhorzlineclip(surf, color, x0 - x, y0 - y, x0 - x_inner,\n- drawn_area);\n- drawhorzlineclip(surf, color, x0 - x, y0 + y - y_offset,\n- x0 - x_inner, drawn_area);\n- drawhorzlineclip(surf, color, x0 + x - x_offset, y0 - y,\n- x0 + x_inner - x_offset, drawn_area);\n- drawhorzlineclip(surf, color, x0 + x - x_offset, y0 + y - y_offset,\n- x0 + x_inner - x_offset, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x, y0 - (int)y,\n+ x0 - (int)x_inner, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x,\n+ y0 + (int)y - y_offset, x0 - (int)x_inner,\n+ drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 + (int)x - x_offset,\n+ y0 - (int)y, x0 + (int)x_inner - x_offset,\n+ drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 + (int)x - x_offset,\n+ y0 + (int)y - y_offset,\n+ x0 + (int)x_inner - x_offset, drawn_area);\n }\n if (d1 < 0) {\n x++;\n@@ -2122,20 +2137,24 @@ draw_ellipse_thickness(SDL_Surface *surf, int x0, int y0, int width,\n ((double)width * width * height * height);\n while (y >= 0) {\n if (line) {\n- drawhorzlineclip(surf, color, x0 - x, y0 - y, x0 + x - x_offset,\n- drawn_area);\n- drawhorzlineclip(surf, color, x0 - x, y0 + y - y_offset,\n- x0 + x - x_offset, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x, y0 - (int)y,\n+ x0 + (int)x - x_offset, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x,\n+ y0 + (int)y - y_offset,\n+ x0 + (int)x - x_offset, drawn_area);\n }\n else {\n- drawhorzlineclip(surf, color, x0 - x, y0 - y, x0 - x_inner,\n- drawn_area);\n- drawhorzlineclip(surf, color, x0 - x, y0 + y - y_offset,\n- x0 - x_inner, drawn_area);\n- drawhorzlineclip(surf, color, x0 + x - x_offset, y0 - y,\n- x0 + x_inner - x_offset, drawn_area);\n- drawhorzlineclip(surf, color, x0 + x - x_offset, y0 + y - y_offset,\n- x0 + x_inner - x_offset, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x, y0 - (int)y,\n+ x0 - (int)x_inner, drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 - (int)x,\n+ y0 + (int)y - y_offset, x0 - (int)x_inner,\n+ drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 + (int)x - x_offset,\n+ y0 - (int)y, x0 + (int)x_inner - x_offset,\n+ drawn_area);\n+ drawhorzlineclipbounding(surf, color, x0 + (int)x - x_offset,\n+ y0 + (int)y - y_offset,\n+ x0 + (int)x_inner - x_offset, drawn_area);\n }\n if (d2 > 0) {\n y--;\n@@ -2314,6 +2333,21 @@ draw_fillpoly(SDL_Surface *surf, int *point_x, int *point_y,\n PyMem_Free(x_intersect);\n }\n \n+static void\n+draw_rect(SDL_Surface *surf, int x1, int y1, int x2, int y2, int width,\n+ Uint32 color)\n+{\n+ int i;\n+ for (i = 0; i < width; i++) {\n+ drawhorzlineclip(surf, color, x1, y1 + i, x2);\n+ drawhorzlineclip(surf, color, x1, y2 - i, x2);\n+ }\n+ for (i = 0; i < (y2 - y1) - 2 * width + 1; i++) {\n+ drawhorzlineclip(surf, color, x1, y1 + width + i, x1 + width - 1);\n+ drawhorzlineclip(surf, color, x2 - width + 1, y1 + width + i, x2);\n+ }\n+}\n+\n static void\n draw_round_rect(SDL_Surface *surf, int x1, int y1, int x2, int y2, int radius,\n int width, Uint32 color, int top_left, int top_right,\n", "test_patch": "diff --git a/test/draw_test.py b/test/draw_test.py\nindex 8ad7d0d18..b80884495 100644\n--- a/test/draw_test.py\n+++ b/test/draw_test.py\n@@ -4950,6 +4950,34 @@ class DrawRectMixin(object):\n \n self.assertNotEqual(color_at_pt, self.color)\n \n+ def test_rect__draw_line_width(self):\n+ surface = pygame.Surface((100, 100))\n+ color = pygame.Color(255, 255, 255)\n+ rect_width = 80\n+ rect_height = 50\n+ line_width = 10\n+ pygame.draw.rect(\n+ surface, color, pygame.Rect(0, 0, rect_width, rect_height), line_width\n+ )\n+ for i in range(line_width):\n+ self.assertEqual(surface.get_at((i, i)), color)\n+ self.assertEqual(surface.get_at((rect_width - i - 1, i)), color)\n+ self.assertEqual(surface.get_at((i, rect_height - i - 1)), color)\n+ self.assertEqual(\n+ surface.get_at((rect_width - i - 1, rect_height - i - 1)), color\n+ )\n+ self.assertEqual(surface.get_at((line_width, line_width)), (0, 0, 0))\n+ self.assertEqual(\n+ surface.get_at((rect_width - line_width - 1, line_width)), (0, 0, 0)\n+ )\n+ self.assertEqual(\n+ surface.get_at((line_width, rect_height - line_width - 1)), (0, 0, 0)\n+ )\n+ self.assertEqual(\n+ surface.get_at((rect_width - line_width - 1, rect_height - line_width - 1)),\n+ (0, 0, 0),\n+ )\n+\n def test_rect__bounding_rect(self):\n \"\"\"Ensures draw rect returns the correct bounding rect.\n \n", "FAIL_TO_PASS": ["test/draw_test.py::DrawRectTest::test_rect__draw_line_width"], "PASS_TO_PASS": ["test/draw_test.py::DrawRectTest::test_rect__fill", "test/draw_test.py::DrawRectTest::test_rect__one_pixel_lines", "test/draw_test.py::DrawRectTest::test_rect__args_without_width"]} +{"instance_id": "clb-pyc-081", "repo": "pygame/pygame", "base_commit": "71c90cdb76cd8b12a0969f5d6314315bd0223c28", "problem_statement": "pygame.freetype.Font.get_metrics does not respect style & rotation\n\r\n- [x] write a unit test based on the code below. Would go in this file. test/freetype_test.py (**good first issue**)\r\n- [x] try the C code fix below in src_c/_freetype.c\r\n\r\n---\r\n\r\nThe following python code \r\n\r\n```\r\n font = freetype.Font(os.path.join (fontdir, \"fonts\", \"sans.ttf\"), 36)\r\n print(font.get_metrics('|'))\r\n font.rotation = 90\r\n print(font.get_metrics('|'))\r\n```\r\noutput:\r\n[(3, 7, 4294967288, 26, 9.0, 0.0)]\r\n[(3, 7, 4294967288, 26, 9.0, 0.0)]\r\nThe two results are identical, which does not follow what the doc [https://www.pygame.org/docs/ref/freetype.html#pygame.freetype.Font.get_metrics](pygame.freetype.Font.get_metrics) says:\r\n**The metrics are adjusted for the current rotation, strong, and oblique settings.**\r\n\r\nI dived into the source code and found that in src_c/_freetype.c, the body in function _ftfont_getmetrics:\r\n` /*\r\n * Build the render mode with the given size and no\r\n * rotation/styles/vertical text\r\n */\r\n if (_PGFT_BuildRenderMode(self->freetype, self, &render, face_size,\r\n FT_STYLE_NORMAL, 0))\r\n goto error;`\r\nThe parameters of _PGFT_BuildRenderMode are the cause of the problem, which i think may be:\r\n`if (_PGFT_BuildRenderMode(self->freetype, self, &render, face_size,\r\n FT_STYLE_DEFAULT, self->rotation))\r\n goto error;`\r\n\r\n\r\n\n", "image": {"image_id": "sha256:4e5d69e396505fea954f28acb59dc90ef522bafab05dd484c0299e628f938720", "pull_reference": "yutu0814/pyc-case-081-pygame@sha256:4e5d69e396505fea954f28acb59dc90ef522bafab05dd484c0299e628f938720"}, "cohort": "python50", "patch": "diff --git a/src_c/_freetype.c b/src_c/_freetype.c\nindex 05e111b7a..e3cb06d06 100644\n--- a/src_c/_freetype.c\n+++ b/src_c/_freetype.c\n@@ -1412,11 +1412,11 @@ _ftfont_getmetrics(pgFontObject *self, PyObject *args, PyObject *kwds)\n ASSERT_SELF_IS_ALIVE(self);\n \n /*\n- * Build the render mode with the given size and no\n- * rotation/styles/vertical text\n+ * Build the render mode with the given size and support\n+ * for rotation/styles/size changes in text\n */\n if (_PGFT_BuildRenderMode(self->freetype, self, &render, face_size,\n- FT_STYLE_NORMAL, 0))\n+ FT_STYLE_DEFAULT, self->rotation))\n goto error;\n \n /* get metrics */\n", "test_patch": "diff --git a/test/freetype_test.py b/test/freetype_test.py\nindex e0b8803ff..34dc48726 100644\n--- a/test/freetype_test.py\n+++ b/test/freetype_test.py\n@@ -126,7 +126,7 @@ class FreeTypeFontTest(unittest.TestCase):\n self.assertRaises(OverflowError, ft.Font, file=None, size=-1)\n \n f = ft.Font(None, size=24)\n- self.assert_(f.height > 0)\n+ self.assertTrue(f.height > 0)\n self.assertRaises(IOError, f.__init__,\n os.path.join(FONTDIR, 'nonexistant.ttf'))\n \n@@ -1423,6 +1423,26 @@ class FreeTypeFontTest(unittest.TestCase):\n self.assertRaises(pygame.error, f.render_to,\n null_surface, (0, 0), \"Crash!\", size=12)\n \n+ def test_issue_565(self):\n+ \"\"\"get_metrics supporting rotation/styles/size\"\"\"\n+\n+ tests = [\n+ {'method': 'size', 'value': 36, 'msg': 'metrics same for size'},\n+ {'method': 'rotation', 'value': 90, 'msg': 'metrics same for rotation'},\n+ {'method': 'oblique', 'value': True, 'msg': 'metrics same for oblique'}\n+ ]\n+ text = \"|\"\n+\n+ def run_test(method, value, msg):\n+ font = ft.Font(self._sans_path, size=24)\n+ before = font.get_metrics(text)\n+ font.__setattr__(method, value)\n+ after = font.get_metrics(text)\n+ self.assertNotEqual(before, after, msg)\n+\n+ for test in tests:\n+ run_test(*test.values())\n+\n \n class FreeTypeTest(unittest.TestCase):\n \n", "FAIL_TO_PASS": ["test/freetype_test.py::FreeTypeFontTest::test_issue_565"], "PASS_TO_PASS": ["test/freetype_test.py::FreeTypeFontTest::test_freetype_Font_size", "test/freetype_test.py::FreeTypeFontTest::test_freetype_Font_scalable", "test/freetype_test.py::FreeTypeFontTest::test_freetype_Font_fixed_width"]} +{"instance_id": "clb-pyc-082", "repo": "pygame/pygame", "base_commit": "8a63c06f2e082b8c7e3c0fce035a0a7e4ca55d85", "problem_statement": "event.get(type) should return posted matching events without a TypeError; peek() on an empty queue should be false. Existing get and populated peek behavior should remain correct.", "image": {"image_id": "sha256:9b466d593d9252da3ccb18d5270b5e8b1dcc456daa31e67273e94d2d48c9256a", "pull_reference": "yutu0814/pyc-case-082-pygame@sha256:9b466d593d9252da3ccb18d5270b5e8b1dcc456daa31e67273e94d2d48c9256a"}, "cohort": "python50", "patch": "diff --git a/src_c/event.c b/src_c/event.c\nindex a4ae2d728..0ca8ac768 100644\n--- a/src_c/event.c\n+++ b/src_c/event.c\n@@ -1332,10 +1332,12 @@ pg_event_get(PyObject *self, PyObject *args)\n if(!_pg_event_append_to_list(list, &event))\n return NULL;\n }\n-\n- Py_DECREF(list);\n- return RAISE(PyExc_TypeError,\n- \"get type must be numeric or a sequence\");\n+ else {\n+ Py_DECREF(list);\n+ return RAISE(PyExc_TypeError,\n+ \"get type must be numeric or a sequence\");\n+ }\n+ return list;\n }\n #endif /* IS_SDLv2 */\n \n@@ -1380,9 +1382,11 @@ pg_event_peek(PyObject *self, PyObject *args)\n \n SDL_PumpEvents();\n result = SDL_PeepEvents(&event, 1, SDL_PEEKEVENT, mask);\n+ if (result < 0)\n+ return RAISE(pgExc_SDLError, SDL_GetError());\n \n if (noargs)\n- return pgEvent_New(&event);\n+ return pgEvent_New(result ? &event : NULL);\n return PyInt_FromLong(result == 1);\n }\n #else /* IS_SDLv2 */\n@@ -1403,9 +1407,10 @@ pg_event_peek(PyObject *self, PyObject *args)\n SDL_PumpEvents();\n \n if (PyTuple_Size(args) == 0) {\n- if (SDL_PeepEvents(&event, 1, SDL_PEEKEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) < 0)\n+ result = SDL_PeepEvents(&event, 1, SDL_PEEKEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT);\n+ if (result < 0)\n return RAISE(pgExc_SDLError, SDL_GetError());\n- return pgEvent_New(&event);\n+ return pgEvent_New(result ? &event : NULL);\n }\n \n type = PyTuple_GET_ITEM(args, 0);\n", "test_patch": "diff --git a/test/event_test.py b/test/event_test.py\nindex de9cb1a34..8db99a99c 100644\n--- a/test/event_test.py\n+++ b/test/event_test.py\n@@ -147,6 +147,13 @@ class EventModuleTest(unittest.TestCase):\n self.assertEqual(len(queue), event_cnt)\n self.assertTrue(all(e.type == pygame.USEREVENT for e in queue))\n \n+ def test_get_type(self):\n+ ev = pygame.event.Event(pygame.USEREVENT)\n+ pygame.event.post(ev)\n+ queue = pygame.event.get(pygame.USEREVENT)\n+ self.assertEqual(len(queue), 1)\n+ self.assertEqual(queue[0].type, pygame.USEREVENT)\n+\n def test_clear(self):\n \"\"\"Ensure clear() removes all the events on the queue.\"\"\"\n for e in events:\n@@ -188,6 +195,10 @@ class EventModuleTest(unittest.TestCase):\n \n self.assertTrue(pygame.event.peek(event_types))\n \n+ def test_peek_empty(self):\n+ pygame.event.clear()\n+ self.assertFalse(pygame.event.peek())\n+\n def test_set_allowed(self):\n \"\"\"Ensure a blocked event type can be unblocked/allowed.\"\"\"\n event = events[0]\n", "FAIL_TO_PASS": ["test/event_test.py::EventModuleTest::test_get_type", "test/event_test.py::EventModuleTest::test_peek_empty"], "PASS_TO_PASS": ["test/event_test.py::EventModuleTest::test_get", "test/event_test.py::EventModuleTest::test_peek"]} +{"instance_id": "clb-pyc-086", "repo": "pygame/pygame", "base_commit": "5f1d4528b46d7f3c368db6e1c395ffb0ae83623d", "problem_statement": "pygame.draw.polygon handles x and y direction inconsistently\nOriginally reported by: **donLorenzo (Bitbucket: [donLorenzo](https://bitbucket.org/donLorenzo), GitHub: [donLorenzo](https://github.com/donLorenzo))**\n\n----------------------------------------\n\nReported by Florian Krause on the [pygame mailing list](http://article.gmane.org/gmane.comp.python.pygame/25542):\n\n\n```\n#!plain\n\nHi there,\n\nI think I found another bug. When drawing a cross, defined as:\n\npygame.draw.polygon(screen, [255,0,0], [[11, 0], [11, 9], [20, 9], [20, 11], [11, 11], [11, 20], [9, 20], [9, 11], [0, 11], [0, 9], [9, 9], [9, 0]], 0)\n\nthe result will show a cross with 2 pixel thickness in the vertical direction, but 3 pixels thickness in the horizontal direction. Which one is \"correct\" is probably debatable, but Pygame should at least treat both directions equal, shouldn't it?\n```\n\nnote that the simple example:\n```\n#!python\n\nimport pygame\npygame.init()\nscreen = pygame.display.set_mode((100,100))\npygame.draw.polygon(screen, [255,0,0], [[0, 0], [3, 0], [3, 3], [0, 3]], 0)\npygame.display.update()\n```\nyields a 4x4 rect\n\n----------------------------------------\n- Bitbucket: https://bitbucket.org/pygame/pygame/issue/234\n\n", "image": {"image_id": "sha256:11e605344ed4675be7b010289e782843d09aa9efc3fae6d819d905c65ab7a0f3", "pull_reference": "yutu0814/pyc-case-086-pygame@sha256:11e605344ed4675be7b010289e782843d09aa9efc3fae6d819d905c65ab7a0f3"}, "cohort": "python50", "patch": "diff --git a/src_c/draw.c b/src_c/draw.c\nindex be4649a60..fe8760737 100644\n--- a/src_c/draw.c\n+++ b/src_c/draw.c\n@@ -1613,7 +1613,20 @@ draw_fillpoly(SDL_Surface *dst, int *vx, int *vy, int n, Uint32 color)\n x2 = vx[j];\n x1 = vx[i];\n }\n- else {\n+ else { // y1 == y2\n+ if ((miny < y) && (y == y1) && (y < maxy))\n+ /* special case : just draw horizontal lines */\n+ {\n+ if (vx[i] < vx[j]) {\n+ x1 = vx[i];\n+ x2 = vx[j];\n+ }\n+ else {\n+ x1 = vx[j];\n+ x2 = vx[i];\n+ }\n+ drawhorzlineclip(dst, color, x1, y, x2);\n+ }\n continue;\n }\n if ( ((y >= y1) && (y < y2)) ||\n", "test_patch": "diff --git a/test/draw_test.py b/test/draw_test.py\nindex a08d3c551..e38fda05a 100644\n--- a/test/draw_test.py\n+++ b/test/draw_test.py\n@@ -466,7 +466,6 @@ class DrawPolygonTest(unittest.TestCase):\n for y in range(10):\n if (x in range(2, 5) and y <7) or (y in range(2, 5) and x < 7):\n # we are on the border of the cross:\n- # FIXME currently the test fails here for (0, 4), (1, 4), (5, 4) and (6, 4)\n self.assertEqual(self.surface.get_at((x, y)), GREEN, msg=str((x, y)))\n else:\n # we are outside\n@@ -510,7 +509,6 @@ class DrawPolygonTest(unittest.TestCase):\n pygame.draw.rect(self.surface, RED, (0, 0, 20, 20), 0)\n pygame.draw.polygon(self.surface, GREEN, path_data, 0)\n for x in range(4, rect.width-5 +1):\n- # FIXME known to fail\n self.assertEqual(self.surface.get_at((x, 4)), GREEN) # upper inner\n \n \n", "FAIL_TO_PASS": ["test/draw_test.py::DrawPolygonTest::test_draw_symetric_cross", "test/draw_test.py::DrawPolygonTest::test_illumine_shape"], "PASS_TO_PASS": ["test/draw_test.py::DrawPolygonTest::test_draw_square", "test/draw_test.py::DrawPolygonTest::test_draw_diamond"]} +{"instance_id": "clb-pyc-088", "repo": "pygame/pygame", "base_commit": "cd173f0ebf77e2b652de1a20a5f3eccf78e8cf12", "problem_statement": "Segfault on surface.get_bounding_rect()\nOriginally reported by: **Anonymous**\n\n----------------------------------------\n\nHi!\n\nI keep getting a strange segfault using the surface.get_bounding_rect() method.\n\nI'm attaching a test case for it. It reliably produces a segmentation fault on my system:\nWindows 7 x64\nPython 2.7.5 x64\npygame-1.9.2a0.win-amd64-py2.7 (from lfd.uci.edu)\nSDL 1.2.15.0\nand\nSDL 1.2.14.0\n\nAlso tried:\nPython 2.7.5 32bit\npygame 1.9.1-py2.7\nSDL 1.2.15.0\nand\nSDL 1.2.14.0\n\n----------------------------------------\n- Bitbucket: https://bitbucket.org/pygame/pygame/issue/180\n\n", "image": {"image_id": "sha256:f3743031c6dbfbb51c85a00c5494a2e837a6715609e300b96305cfb04d928d49", "pull_reference": "yutu0814/pyc-case-088-pygame@sha256:f3743031c6dbfbb51c85a00c5494a2e837a6715609e300b96305cfb04d928d49"}, "cohort": "python50", "patch": "diff --git a/src/surface.c b/src/surface.c\nindex aa6b7b9a9..a38e77122 100644\n--- a/src/surface.c\n+++ b/src/surface.c\n@@ -1988,6 +1988,15 @@ surf_get_abs_parent (PyObject *self)\n static PyObject *\n surf_get_bounding_rect (PyObject *self, PyObject *args, PyObject *kwargs)\n {\n+#if SDL_BYTEORDER == SDL_LIL_ENDIAN\n+ const int BYTE0 = 0;\n+ const int BYTE1 = 1;\n+ const int BYTE2 = 2;\n+#else\n+ const int BYTE0 = 2;\n+ const int BYTE1 = 1;\n+ const int BYTE2 = 0;\n+#endif\n PyObject *rect;\n SDL_Surface *surf = PySurface_AsSurface (self);\n SDL_PixelFormat *format = surf->format;\n@@ -1997,6 +2006,7 @@ surf_get_bounding_rect (PyObject *self, PyObject *args, PyObject *kwargs)\n int min_x, min_y, max_x, max_y;\n int min_alpha = 1;\n int found_alpha = 0;\n+ Uint32 value;\n Uint8 r, g, b, a;\n int has_colorkey = 0;\n Uint8 keyr, keyg, keyb;\n@@ -2033,7 +2043,24 @@ surf_get_bounding_rect (PyObject *self, PyObject *args, PyObject *kwargs)\n for (y = max_y - 1; y >= min_y; --y) {\n for (x = min_x; x < max_x; ++x) {\n pixel = (pixels + y * surf->pitch) + x*format->BytesPerPixel;\n- SDL_GetRGBA (*((Uint32*)pixel), surf->format, &r, &g, &b, &a);\n+ switch (format->BytesPerPixel) {\n+\n+ case 1:\n+ value = *pixel;\n+ break;\n+ case 2:\n+ value = *(Uint16 *)pixel;\n+ break;\n+ case 3:\n+ value = pixel[BYTE0];\n+ value |= pixel[BYTE1] << 8;\n+ value |= pixel[BYTE2] << 16;\n+ break;\n+ default:\n+ assert(format->BytesPerPixel == 4);\n+ value = *(Uint32 *)pixel;\n+ }\n+ SDL_GetRGBA (value, surf->format, &r, &g, &b, &a);\n if ((a >= min_alpha && has_colorkey == 0) ||\n (has_colorkey != 0 && (r != keyr || g != keyg || b != keyb))) {\n found_alpha = 1;\n@@ -2049,7 +2076,24 @@ surf_get_bounding_rect (PyObject *self, PyObject *args, PyObject *kwargs)\n for (x = max_x - 1; x >= min_x; --x) {\n for (y = min_y; y < max_y; ++y) {\n pixel = (pixels + y * surf->pitch) + x*format->BytesPerPixel;\n- SDL_GetRGBA (*((Uint32*)pixel), surf->format, &r, &g, &b, &a);\n+ switch (format->BytesPerPixel) {\n+\n+ case 1:\n+ value = *pixel;\n+ break;\n+ case 2:\n+ value = *(Uint16 *)pixel;\n+ break;\n+ case 3:\n+ value = pixel[BYTE0];\n+ value |= pixel[BYTE1] << 8;\n+ value |= pixel[BYTE2] << 16;\n+ break;\n+ default:\n+ assert(format->BytesPerPixel == 4);\n+ value = *(Uint32 *)pixel;\n+ }\n+ SDL_GetRGBA (value, surf->format, &r, &g, &b, &a);\n if ((a >= min_alpha && has_colorkey == 0) ||\n (has_colorkey != 0 && (r != keyr || g != keyg || b != keyb))) {\n found_alpha = 1;\n@@ -2066,7 +2110,24 @@ surf_get_bounding_rect (PyObject *self, PyObject *args, PyObject *kwargs)\n min_y = y;\n for (x = min_x; x < max_x; ++x) {\n pixel = (pixels + y * surf->pitch) + x*format->BytesPerPixel;\n- SDL_GetRGBA (*((Uint32*)pixel), surf->format, &r, &g, &b, &a);\n+ switch (format->BytesPerPixel) {\n+\n+ case 1:\n+ value = *pixel;\n+ break;\n+ case 2:\n+ value = *(Uint16 *)pixel;\n+ break;\n+ case 3:\n+ value = pixel[BYTE0];\n+ value |= pixel[BYTE1] << 8;\n+ value |= pixel[BYTE2] << 16;\n+ break;\n+ default:\n+ assert(format->BytesPerPixel == 4);\n+ value = *(Uint32 *)pixel;\n+ }\n+ SDL_GetRGBA (value, surf->format, &r, &g, &b, &a);\n if ((a >= min_alpha && has_colorkey == 0) ||\n (has_colorkey != 0 && (r != keyr || g != keyg || b != keyb))) {\n found_alpha = 1;\n@@ -2082,7 +2143,24 @@ surf_get_bounding_rect (PyObject *self, PyObject *args, PyObject *kwargs)\n min_x = x;\n for (y = min_y; y < max_y; ++y) {\n pixel = (pixels + y * surf->pitch) + x*format->BytesPerPixel;\n- SDL_GetRGBA (*((Uint32*)pixel), surf->format, &r, &g, &b, &a);\n+ switch (format->BytesPerPixel) {\n+\n+ case 1:\n+ value = *pixel;\n+ break;\n+ case 2:\n+ value = *(Uint16 *)pixel;\n+ break;\n+ case 3:\n+ value = pixel[BYTE0];\n+ value |= pixel[BYTE1] << 8;\n+ value |= pixel[BYTE2] << 16;\n+ break;\n+ default:\n+ assert(format->BytesPerPixel == 4);\n+ value = *(Uint32 *)pixel;\n+ }\n+ SDL_GetRGBA (value, surf->format, &r, &g, &b, &a);\n if ((a >= min_alpha && has_colorkey == 0) ||\n (has_colorkey != 0 && (r != keyr || g != keyg || b != keyb))) {\n found_alpha = 1;\n", "test_patch": "diff --git a/test/surface_test.py b/test/surface_test.py\nindex 19f30d83f..4bf24c907 100644\n--- a/test/surface_test.py\n+++ b/test/surface_test.py\n@@ -165,6 +165,15 @@ class SurfaceTypeTest(unittest.TestCase):\n self.assertEqual(bound_rect.width, 31)\n self.assertEqual(bound_rect.height, 31)\n \n+ # Issue #180\n+ pygame.display.init()\n+ try:\n+ surf = pygame.Surface((4, 1), 0, 8)\n+ surf.fill((255, 255, 255))\n+ surf.get_bounding_rect() # Segfault.\n+ finally:\n+ pygame.quit()\n+\n def test_copy(self):\n \n # __doc__ (as of 2008-06-25) for pygame.surface.Surface.copy:\n", "FAIL_TO_PASS": ["test/surface_test.py::SurfaceTypeTest::test_get_bounding_rect"], "PASS_TO_PASS": ["test/surface_test.py::SurfaceTypeTest::test_copy", "test/surface_test.py::SurfaceTypeTest::test_get_bytesize", "test/surface_test.py::SurfaceTypeTest::test_get_rect"]} +{"instance_id": "clb-pyc-090", "repo": "pygame/pygame", "base_commit": "6e5ca4a046fde6c21b0386281e25a83b3c8f9ba3", "problem_statement": "freetype.Font.get_rect() ignores style defaults when the style argument is not given\nOriginally reported by: **Lenard Lindstrom (Bitbucket: [llindstrom](https://bitbucket.org/llindstrom), GitHub: [llindstrom](https://github.com/llindstrom))**\n\n----------------------------------------\n\nThe text boundary rectangle returned by *freetype.Font.get_rect()* should match the boundary of the same text rendered directly to a surface. This permits accurate text positioning. To work properly, *get_rect()* should calculate the text boundary to reflect text style, such as **underline**. Instead, it ignores the style settings for the *Font* object when the *style* argument is omitted.\n\nIn the *get_rect()* C function *_ftfont_getrect()* of **_freetype.c**, the *style* variable defaults to *0* instead of *FT_STYLE_DEFAULT*. Consequently, by default, no styles are used.\n\nA unit test which reproduces the bug will be added to **freetype_test.py**\n\n----------------------------------------\n- Bitbucket: https://bitbucket.org/pygame/pygame/issue/242\n\n", "image": {"image_id": "sha256:150ec56758ae844eb1b5e23a435ebd2c0bd9b72b55416b8a5cfa417ed7bb1df4", "pull_reference": "yutu0814/pyc-case-090-pygame@sha256:150ec56758ae844eb1b5e23a435ebd2c0bd9b72b55416b8a5cfa417ed7bb1df4"}, "cohort": "python50", "patch": "diff --git a/src/_freetype.c b/src/_freetype.c\nindex ae05a337d..8ec3bb6b2 100644\n--- a/src/_freetype.c\n+++ b/src/_freetype.c\n@@ -1418,7 +1418,7 @@ _ftfont_getrect(PgFontObject *self, PyObject *args, PyObject *kwds)\n \n FontRenderMode render;\n Angle_t rotation = self->rotation;\n- int style = 0;\n+ int style = FT_STYLE_DEFAULT;\n \n if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O|iO&O&\", kwlist,\n &textobj, &style,\n", "test_patch": "diff --git a/test/freetype_test.py b/test/freetype_test.py\nindex 9624be274..8aa5a4fd0 100644\n--- a/test/freetype_test.py\n+++ b/test/freetype_test.py\n@@ -1257,6 +1257,66 @@ class FreeTypeFontTest(unittest.TestCase):\n s = 'M' * 100000 # Way too long for an SDL surface\n self.assertRaises(pygame.error, font.render, s, (0, 0, 0))\n \n+ def test_issue_242(self):\n+ \"\"\"Issue #242: get_rect() uses 0 as default style\"\"\"\n+\n+ # Issue #242: freetype.Font.get_rect() ignores style defaults when\n+ # the style argument is not given\n+ #\n+ # The text boundary rectangle returned by freetype.Font.get_rect()\n+ # should match the boundary of the same text rendered directly to a\n+ # surface. This permits accurate text positioning. To work properly,\n+ # get_rect() should calculate the text boundary to reflect text style,\n+ # such as underline. Instead, it ignores the style settings for the\n+ # Font object when the style argument is omitted.\n+ # \n+ # When the style argument is not given, freetype.get_rect() uses\n+ # unstyled text when calculating the boundary rectangle. This is\n+ # because _ftfont_getrect(), in _freetype.c, set the default\n+ # style to 0 rather than FT_STYLE_DEFAULT.\n+ #\n+ font = self._TEST_FONTS['sans']\n+\n+ # Try wide style on a wide character.\n+ prev_style = font.wide\n+ font.wide = True\n+ try:\n+ rect = font.get_rect('M', size=64)\n+ surf, rrect = font.render(None, size=64)\n+ self.assertEqual(rect, rrect)\n+ finally:\n+ font.wide = prev_style\n+\n+ # Try strong style on several wide characters.\n+ prev_style = font.strong\n+ font.strong = True\n+ try:\n+ rect = font.get_rect('Mm_', size=64)\n+ surf, rrect = font.render(None, size=64)\n+ self.assertEqual(rect, rrect)\n+ finally:\n+ font.strong = prev_style\n+\n+ # Try oblique style on a tall, narrow character.\n+ prev_style = font.oblique\n+ font.oblique = True\n+ try:\n+ rect = font.get_rect('|', size=64)\n+ surf, rrect = font.render(None, size=64)\n+ self.assertEqual(rect, rrect)\n+ finally:\n+ font.oblique = prev_style\n+\n+ # Try underline style on a glyphless character.\n+ prev_style = font.underline\n+ font.underline = True\n+ try:\n+ rect = font.get_rect(' ', size=64)\n+ surf, rrect = font.render(None, size=64)\n+ self.assertEqual(rect, rrect)\n+ finally:\n+ font.underline = prev_style\n+\n def test_garbage_collection(self):\n \"\"\"Check reference counting on returned new references\"\"\"\n def ref_items(seq):\n", "FAIL_TO_PASS": ["test/freetype_test.py::FreeTypeFontTest::test_issue_242"], "PASS_TO_PASS": ["test/freetype_test.py::FreeTypeFontTest::test_freetype_Font_get_rect", "test/freetype_test.py::FreeTypeFontTest::test_freetype_Font_style", "test/freetype_test.py::FreeTypeFontTest::test_freetype_Font_render_mono"]} +{"instance_id": "clb-pyc-091", "repo": "pygame/pygame", "base_commit": "e26f569b1f3e28d935327b7dfc4cb10e722a9d09", "problem_statement": "For a string with trailing spaces, freetype ignores the last space in boundary calculations\nOriginally reported by: **Lenard Lindstrom (Bitbucket: [llindstrom](https://bitbucket.org/llindstrom), GitHub: [llindstrom](https://github.com/llindstrom))**\n\n----------------------------------------\n\nFor non-rotated horizontal text, a string of one space, \" \", will produce a zero width rectangle or surface. A string of two spaces produces a rectangle or surface of only one space in\nwidth.\n\nFix: include the advance of a terminating space of a string in the calculation of the text boundary. Normally only the bitmap width of the last character in a string is used when determining the text boundary. This avoids boundary padding, empty rows or columns. But a space is nothing but padding; its bitmap has width and height of zero. So make an exception for the trailing space and use its advance to extend the boundary.\n\nAn test for the bug will be included in the unit tests.\n\n----------------------------------------\n- Bitbucket: https://bitbucket.org/pygame/pygame/issue/243\n\n", "image": {"image_id": "sha256:f416079adbe2fdc2542d0842b9d09f7f0b4fab0032a8de19fd08abd9b93b2777", "pull_reference": "yutu0814/pyc-case-091-pygame@sha256:f416079adbe2fdc2542d0842b9d09f7f0b4fab0032a8de19fd08abd9b93b2777"}, "cohort": "python50", "patch": "diff --git a/docs/reST/ref/freetype.rst b/docs/reST/ref/freetype.rst\nindex a566c4cf7..f65a6a848 100644\n--- a/docs/reST/ref/freetype.rst\n+++ b/docs/reST/ref/freetype.rst\n@@ -422,7 +422,7 @@ The :mod:`freetype` module is new in Pygame 1.9.2\n width, height = surf.get_size()\n line_spacing = font.get_sized_height() + 2\n x, y = 0, line_spacing\n- space = font.get_rect(' ' * 2) # second space given width 0\n+ space = font.get_rect(' ')\n for word in words:\n bounds = font.get_rect(word)\n if x + bounds.width + bounds.x >= width:\ndiff --git a/src/freetype/ft_layout.c b/src/freetype/ft_layout.c\nindex acc6f8627..95d53cb44 100644\n--- a/src/freetype/ft_layout.c\n+++ b/src/freetype/ft_layout.c\n@@ -371,6 +371,30 @@ position_glyphs(Layout *ftext)\n \n }\n \n+ /* Deal with the special case of a trailing space.\n+ *\n+ * In determining the bounding box of the text, the above loop omits\n+ * the advance of the last character from the calculation. This is\n+ * intensional. For a printing character with a bitmap, it avoids\n+ * padding of the boundary. But a space is nothing but padding, so\n+ * a trailing space gets left out. This adds it in.\n+ */\n+ if (n_glyphs > 0 && /* conditional && */\n+ (glyph_array + n_glyphs - 1)->glyph->image->bitmap.width == 0) {\n+ if (pen.x < min_x) {\n+ min_x = pen.x;\n+ }\n+ else if (pen.x > max_x) {\n+ max_x = pen.x;\n+ }\n+ if (pen.y < min_y) {\n+ min_y = pen.y;\n+ }\n+ else if (pen.y > max_y) {\n+ max_y = pen.y;\n+ }\n+ }\n+\n fill_text_bounding_box(ftext, pen, min_x, max_x, min_y, max_y, top);\n }\n \n", "test_patch": "diff --git a/test/freetype_test.py b/test/freetype_test.py\nindex d885ed68f..2648ce66b 100644\n--- a/test/freetype_test.py\n+++ b/test/freetype_test.py\n@@ -1311,7 +1311,7 @@ class FreeTypeFontTest(unittest.TestCase):\n prev_style = font.underline\n font.underline = True\n try:\n- rect = font.get_rect(' ', size=64)\n+ rect = font.get_rect(' ', size=64)\n surf, rrect = font.render(None, size=64)\n self.assertEqual(rect, rrect)\n finally:\n@@ -1340,6 +1340,18 @@ class FreeTypeFontTest(unittest.TestCase):\n font.underline_adjustment = adj\n s, r = font.render(\"Amazon\", size=19)\n \n+ def test_issue_243(self):\n+ \"\"\"Issue Y: trailing space ignored in boundary calculation\"\"\"\n+\n+ # Issue #243: For a string with trailing spaces, freetype ignores the\n+ # last space in boundary calculations\n+ #\n+ font = self._TEST_FONTS['fixed']\n+ r1 = font.get_rect(\" \", size=64)\n+ self.assertTrue(r1.width > 1)\n+ r2 = font.get_rect(\" \", size=64)\n+ self.assertEqual(r2.width, 2 * r1.width)\n+\n def test_garbage_collection(self):\n \"\"\"Check reference counting on returned new references\"\"\"\n def ref_items(seq):\n", "FAIL_TO_PASS": ["test/freetype_test.py::FreeTypeFontTest::test_issue_243"], "PASS_TO_PASS": ["test/freetype_test.py::FreeTypeFontTest::test_freetype_Font_get_rect", "test/freetype_test.py::FreeTypeFontTest::test_freetype_Font_render_mono", "test/freetype_test.py::FreeTypeFontTest::test_issue_242"]} +{"instance_id": "clb-pyc-094", "repo": "pygame/pygame", "base_commit": "2d7786bc2453561a696281299104f95814e676b3", "problem_statement": "Method Surface.fill can segfault is passed an out-of-bounds boundary rectange\nOriginally reported by: **Lenard Lindstrom (Bitbucket: [llindstrom](https://bitbucket.org/llindstrom), GitHub: [llindstrom](https://github.com/llindstrom))**\n\n----------------------------------------\n\nThe //Surface.fill// method can segfault when doing a\n//BLEND_RGB_ADD// fill if the optional boundary rectangle goes\noutside of the surface.\n\nThis addresses Pygame mailing list messages:\n\nhttp://www.mail-archive.com/pygame-users@seul.org/msg09485.html\n\nand\n\nhttp://www.mail-archive.com/pygame-users@seul.org/msg09485.html\n\nThe cause is that the custom fill methods in surface_blit.c do no\nboundary checks.\n\n----------------------------------------\n- Bitbucket: https://bitbucket.org/pygame/pygame/issue/93\n\n", "image": {"image_id": "sha256:6f72fe9350d7b0d377698ec01aa208bde1889947464acad69e141599c1692d9c", "pull_reference": "yutu0814/pyc-case-094-pygame@sha256:6f72fe9350d7b0d377698ec01aa208bde1889947464acad69e141599c1692d9c"}, "cohort": "python50", "patch": "diff --git a/src/surface.c b/src/surface.c\nindex eea770749..8ec65f869 100644\n--- a/src/surface.c\n+++ b/src/surface.c\n@@ -1436,7 +1436,7 @@ surf_fill (PyObject *self, PyObject *args, PyObject *keywds)\n rect = &temp;\n }\n \n- if (rect->w < 0 || rect->h < 0) {\n+ if (rect->w < 0 || rect->h < 0 || rect->x > surf->w || rect->y > surf->h) {\n sdlrect.x = sdlrect.y = 0;\n sdlrect.w = sdlrect.h = 0;\n }\n@@ -1446,6 +1446,26 @@ surf_fill (PyObject *self, PyObject *args, PyObject *keywds)\n sdlrect.w = rect->w;\n sdlrect.h = rect->h;\n \n+\n+\n+\n+ // clip the rect to be within the surface.\n+ if (sdlrect.x < 0) {\n+ sdlrect.x = 0;\n+ }\n+ if (sdlrect.y < 0) {\n+ sdlrect.y = 0;\n+ }\n+\n+ if(sdlrect.x + sdlrect.w > surf->w) {\n+ sdlrect.w = sdlrect.w + (surf->w - (sdlrect.x + sdlrect.w));\n+ }\n+ if(sdlrect.y + sdlrect.h > surf->h) {\n+ sdlrect.h = sdlrect.h + (surf->h - (sdlrect.y + sdlrect.h));\n+ }\n+\n+\n+\n if (blendargs != 0) {\n \n /* \n", "test_patch": "diff --git a/test/surface_test.py b/test/surface_test.py\nindex a0fa54d11..1224ced53 100644\n--- a/test/surface_test.py\n+++ b/test/surface_test.py\n@@ -1527,6 +1527,42 @@ class SurfaceBlendTest (unittest.TestCase):\n (dst.get_at((x, y)), tst.get_at((x, y)),\n x, y))\n \n+\n+\n+\n+ def test_blit_blend_big_rect(self):\n+ \"\"\" test that an oversized rect works ok.\n+ \"\"\"\n+ color = (1, 2, 3, 255)\n+ area = (1, 1, 30, 30)\n+ s1 = pygame.Surface((4, 4), 0, 32)\n+ r = s1.fill(special_flags=pygame.BLEND_ADD, color=color, rect=area)\n+ self.assertEquals(pygame.Rect((1, 1, 3, 3)), r)\n+ self.assert_(s1.get_at((0, 0)) == (0, 0, 0, 255))\n+ self.assert_(s1.get_at((1, 1)) == color)\n+\n+\n+ black = pygame.Color(\"black\")\n+ red = pygame.Color(\"red\")\n+ self.assertNotEqual(black, red)\n+\n+ surf = pygame.Surface((10, 10), 0, 32)\n+ surf.fill(black)\n+ subsurf = surf.subsurface(pygame.Rect(0, 1, 10, 8))\n+ self.assertEqual(surf.get_at((0, 0)), black)\n+ self.assertEqual(surf.get_at((0, 9)), black)\n+\n+ subsurf.fill(red, (0, -1, 10, 1), pygame.BLEND_RGB_ADD)\n+ self.assertEqual(surf.get_at((0, 0)), black)\n+ self.assertEqual(surf.get_at((0, 9)), black)\n+\n+ subsurf.fill(red, (0, 8, 10, 1), pygame.BLEND_RGB_ADD)\n+ self.assertEqual(surf.get_at((0, 0)), black)\n+ self.assertEqual(surf.get_at((0, 9)), black)\n+\n+\n+\n+\n def test_GET_PIXELVALS(self):\n # surface.h GET_PIXELVALS bug regarding whether of not\n # a surface has per-pixel alpha. Looking at the Amask\n", "FAIL_TO_PASS": ["test/surface_test.py::SurfaceBlendTest::test_blit_blend_big_rect"], "PASS_TO_PASS": ["test/surface_test.py::SurfaceTypeTest::test_copy", "test/surface_test.py::SurfaceTypeTest::test_get_bytesize", "test/surface_test.py::SurfaceTypeTest::test_get_rect"]} +{"instance_id": "clb-pyc-137", "repo": "pygobject/pycairo", "base_commit": "9ebff889d4c68927ab1c152b6ae7c8327283b6ed", "problem_statement": "assertion error on invalid value for Surface.set_device_scale\nRather than an exception.\r\n```Python\r\nsurface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)\r\nsurface.set_device_scale(1, 0)\r\n```\r\n```\r\npython: /build/buildd/cairo-1.13.0~20140204/src/cairo-surface.c:1700: cairo_surface_set_device_scale: Assertion `status == CAIRO_STATUS_SUCCESS' failed.\r\n```\n", "image": {"image_id": "sha256:b4603765359d41448fa3d87f060d41236f069e73bc953b52ab072d8783418944", "pull_reference": "yutu0814/pyc-case-137-pycairo@sha256:b4603765359d41448fa3d87f060d41236f069e73bc953b52ab072d8783418944"}, "cohort": "python50", "patch": "diff --git a/cairo/surface.c b/cairo/surface.c\nindex f8fbf11..8c815bc 100644\n--- a/cairo/surface.c\n+++ b/cairo/surface.c\n@@ -323,11 +323,18 @@ surface_set_device_offset (PycairoSurface *o, PyObject *args) {\n static PyObject *\n surface_set_device_scale (PycairoSurface *o, PyObject *args) {\n double x_scale, y_scale;\n+ cairo_matrix_t transform;\n \n if (!PyArg_ParseTuple (args, \"dd:Surface.set_device_scale\",\n \t\t\t &x_scale, &y_scale))\n return NULL;\n \n+ /* cairo asserts the following without reporting an error back.\n+ * Since we don't want things to crash in Python replicate the logic here.\n+ */\n+ cairo_matrix_init_scale (&transform, x_scale, y_scale);\n+ RETURN_NULL_IF_CAIRO_ERROR (cairo_matrix_invert (&transform));\n+\n cairo_surface_set_device_scale (o->surface, x_scale, y_scale);\n Py_RETURN_NONE;\n \n", "test_patch": "diff --git a/tests/test_surface.py b/tests/test_surface.py\nindex d5287c2..7938e4d 100644\n--- a/tests/test_surface.py\n+++ b/tests/test_surface.py\n@@ -69,6 +69,10 @@ def test_surface_set_device_scale():\n ret = surface.set_device_scale(5.0, 3.0)\n assert ret is None\n \n+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)\n+ with pytest.raises(cairo.Error):\n+ surface.set_device_scale(1, 0)\n+\n \n @pytest.mark.skipif(not cairo.HAS_PNG_FUNCTIONS, reason=\"not png support\")\n def test_image_surface_create_for_data_array():\n", "FAIL_TO_PASS": ["tests/test_surface.py::test_surface_set_device_scale"], "PASS_TO_PASS": ["tests/test_surface.py::test_surface_get_device_scale", "tests/test_surface.py::test_surface_get_content", "tests/test_surface.py::test_surface_get_format"]} +{"instance_id": "clb-pyc-138", "repo": "pygobject/pycairo", "base_commit": "afee8cfba448e8c6c100afc6015d31c6aa37e172", "problem_statement": "Add RasterSourcePattern\nWe can track the lifetime of the callbacks set there through set_user_data.\r\nWe can ignore the callback data imo. It's not per callback which rules out passing *args through and python closures should work fine.\n", "image": {"image_id": "sha256:070d14e959d62f2f50cecf0d12900951f15be77f94e57ad208c3fecd43426b9f", "pull_reference": "yutu0814/pyc-case-138-pycairo@sha256:070d14e959d62f2f50cecf0d12900951f15be77f94e57ad208c3fecd43426b9f"}, "cohort": "python50", "patch": "diff --git a/NEWS b/NEWS\nindex bd0679e..b033225 100644\n--- a/NEWS\n+++ b/NEWS\n@@ -5,6 +5,7 @@\n \n New Features:\n * Add :meth:`Surface.map_to_image` and :meth:`Surface.unmap_image` :bug:`51`\n+ * Add :class:`RasterSourcePattern` :bug:`48`\n \n Changes:\n * Pycairo instances wrapping the same underlying cairo object now compare\ndiff --git a/cairo/cairomodule.c b/cairo/cairomodule.c\nindex 04df650..b618957 100644\n--- a/cairo/cairomodule.c\n+++ b/cairo/cairomodule.c\n@@ -236,6 +236,8 @@ PYCAIRO_MOD_INIT(_cairo)\n return PYCAIRO_MOD_ERROR_VAL;\n if (PyType_Ready(&PycairoMeshPattern_Type) < 0)\n return PYCAIRO_MOD_ERROR_VAL;\n+ if (PyType_Ready(&PycairoRasterSourcePattern_Type) < 0)\n+ return PYCAIRO_MOD_ERROR_VAL;\n \n if (PyType_Ready(&PycairoRectangleInt_Type) < 0)\n return PYCAIRO_MOD_ERROR_VAL;\n@@ -354,6 +356,9 @@ PYCAIRO_MOD_INIT(_cairo)\n Py_INCREF(&PycairoRadialGradient_Type);\n PyModule_AddObject(m, \"MeshPattern\",\n (PyObject *)&PycairoMeshPattern_Type);\n+ Py_INCREF(&PycairoRasterSourcePattern_Type);\n+ PyModule_AddObject(m, \"RasterSourcePattern\",\n+ (PyObject *)&PycairoRasterSourcePattern_Type);\n \n Py_INCREF(&PycairoRectangleInt_Type);\n PyModule_AddObject(m, \"RectangleInt\", (PyObject *)&PycairoRectangleInt_Type);\ndiff --git a/cairo/pattern.c b/cairo/pattern.c\nindex d53b261..ef09e92 100644\n--- a/cairo/pattern.c\n+++ b/cairo/pattern.c\n@@ -65,6 +65,9 @@ PycairoPattern_FromPattern (cairo_pattern_t *pattern, PyObject *base) {\n case CAIRO_PATTERN_TYPE_MESH:\n type = &PycairoMeshPattern_Type;\n break;\n+ case CAIRO_PATTERN_TYPE_RASTER_SOURCE:\n+ type = &PycairoRasterSourcePattern_Type;\n+ break;\n default:\n type = &PycairoPattern_Type;\n break;\n@@ -911,3 +914,318 @@ PyTypeObject PycairoMeshPattern_Type = {\n 0, /* tp_is_gc */\n 0, /* tp_bases */\n };\n+\n+\n+static PyObject *\n+raster_source_pattern_new (PyTypeObject *type, PyObject *args, PyObject *kwds) {\n+ cairo_content_t content;\n+ int width, height;\n+\n+ if (!PyArg_ParseTuple (args, \"iii:RasterSourcePattern.__new__\",\n+ &content, &width, &height))\n+ return NULL;\n+\n+ return PycairoPattern_FromPattern (\n+ cairo_pattern_create_raster_source (NULL, content, width, height), NULL);\n+}\n+\n+static const cairo_user_data_key_t raster_source_acquire_key;\n+static const cairo_user_data_key_t raster_source_release_key;\n+\n+static void\n+_decref_destroy_func (void *user_data) {\n+ PyGILState_STATE gstate = PyGILState_Ensure ();\n+ Py_DECREF (user_data);\n+ PyGILState_Release (gstate);\n+}\n+\n+static void\n+_raster_source_release_func (cairo_pattern_t *pattern,\n+ void *callback_data,\n+ cairo_surface_t *surface) {\n+ void *user_data;\n+ PyObject *pysurface, *result;\n+ PyGILState_STATE gstate;\n+\n+ pattern = (cairo_pattern_t *)callback_data;\n+\n+ user_data = cairo_pattern_get_user_data (\n+ pattern, &raster_source_release_key);\n+ /* in case there is a acquire callback but no release one, this gets called\n+ * anyway so we can free the surface\n+ */\n+ if (user_data == NULL) {\n+ cairo_surface_destroy (surface);\n+ return;\n+ }\n+\n+ gstate = PyGILState_Ensure ();\n+\n+ pysurface = PycairoSurface_FromSurface (\n+ cairo_surface_reference (surface), NULL);\n+ if (pysurface == NULL)\n+ goto error;\n+\n+ result = PyObject_CallFunction ((PyObject *)user_data, \"(O)\", pysurface);\n+ if (result == NULL)\n+ goto error;\n+\n+ if (result != Py_None) {\n+ Py_DECREF (result);\n+ PyErr_SetString (PyExc_TypeError,\n+ \"Return value of release callback needs to be None\");\n+ result = NULL;\n+ goto error;\n+ }\n+\n+ Py_DECREF (pysurface);\n+ PyGILState_Release (gstate);\n+ cairo_surface_destroy (surface);\n+ return;\n+error:\n+ if (PyErr_Occurred ()) {\n+ PyErr_Print ();\n+ PyErr_Clear ();\n+ }\n+ Py_XDECREF (pysurface);\n+ PyGILState_Release (gstate);\n+ cairo_surface_destroy (surface);\n+ return;\n+}\n+\n+static cairo_surface_t*\n+_raster_source_acquire_func (cairo_pattern_t *pattern, void *callback_data,\n+ cairo_surface_t *target,\n+ const cairo_rectangle_int_t *extents) {\n+ void *user_data;\n+ PyGILState_STATE gstate;\n+ PyObject *result;\n+ PyObject *pypattern = NULL, *pysurface = NULL, *pyrect = NULL;\n+ cairo_surface_t *result_surface;\n+\n+ /* https://bugs.freedesktop.org/show_bug.cgi?id=101866\n+ * If something changes the callback data, we are screwed, but not much\n+ * we can do to detect that..\n+ */\n+ pattern = (cairo_pattern_t *)callback_data;\n+\n+ gstate = PyGILState_Ensure ();\n+\n+ user_data = cairo_pattern_get_user_data (\n+ pattern, &raster_source_acquire_key);\n+ if (user_data == NULL)\n+ goto error;\n+\n+ pypattern = PycairoPattern_FromPattern (\n+ cairo_pattern_reference (pattern), NULL);\n+ if (pattern == NULL)\n+ goto error;\n+\n+ pysurface = PycairoSurface_FromSurface (\n+ cairo_surface_reference (target), NULL);\n+ if (pysurface == NULL)\n+ goto error;\n+\n+ pyrect = PycairoRectangleInt_FromRectangleInt (extents);\n+ if (pyrect == NULL)\n+ goto error;\n+\n+ result = PyObject_CallFunction (\n+ (PyObject *)user_data, \"(OOO)\", pypattern, pysurface, pyrect);\n+\n+ if (result != NULL) {\n+ if (!PyObject_TypeCheck (result, &PycairoSurface_Type)) {\n+ Py_DECREF (result);\n+ PyErr_SetString (PyExc_TypeError,\n+ \"Return value of acquire callback needs to be of type Surface\");\n+ result = NULL;\n+ }\n+ }\n+\n+ if (result == NULL)\n+ goto error;\n+\n+ Py_DECREF (pypattern);\n+ Py_DECREF (pysurface);\n+ Py_DECREF (pyrect);\n+ result_surface = ((PycairoSurface *)result)->surface;\n+ cairo_surface_reference (result_surface);\n+ Py_DECREF (result);\n+ PyGILState_Release (gstate);\n+ return result_surface;\n+\n+error:\n+ if (PyErr_Occurred ()) {\n+ PyErr_Print ();\n+ PyErr_Clear ();\n+ }\n+ Py_XDECREF (pypattern);\n+ Py_XDECREF (pysurface);\n+ Py_XDECREF (pyrect);\n+ PyGILState_Release (gstate);\n+ return NULL;\n+}\n+\n+static PyObject *\n+raster_source_pattern_set_acquire (PycairoRasterSourcePattern *obj,\n+ PyObject *args) {\n+ PyObject *acquire_callable, *release_callable;\n+ cairo_status_t status;\n+ cairo_pattern_t *pattern;\n+ void *callback_data;\n+ cairo_raster_source_acquire_func_t acquire_func;\n+ cairo_raster_source_release_func_t release_func;\n+ void *acquire_user_data, *release_user_data;\n+\n+ if (!PyArg_ParseTuple (args, \"OO:RasterSourcePattern.set_acquire\",\n+ &acquire_callable, &release_callable))\n+ return NULL;\n+\n+ pattern = obj->pattern;\n+\n+ callback_data = cairo_raster_source_pattern_get_callback_data (pattern);\n+ if (callback_data != NULL && callback_data != pattern) {\n+ PyErr_SetString (PyExc_RuntimeError,\n+ \"Callback is set, but not through Pycairo. Replacing not supported.\");\n+ return NULL;\n+ }\n+\n+ if (!PyCallable_Check (acquire_callable) && acquire_callable != Py_None) {\n+ PyErr_SetString (\n+ PyExc_TypeError, \"argument needs to be a callable or None\");\n+ return NULL;\n+ }\n+\n+ if (!PyCallable_Check (release_callable) && release_callable != Py_None) {\n+ PyErr_SetString (\n+ PyExc_TypeError, \"argument needs to be a callable or None\");\n+ return NULL;\n+ }\n+\n+ if (acquire_callable == Py_None) {\n+ acquire_func = NULL;\n+ acquire_user_data = NULL;\n+ } else {\n+ acquire_func = _raster_source_acquire_func;\n+ acquire_user_data = acquire_callable;\n+ }\n+\n+ if (release_callable == Py_None) {\n+ release_func = NULL;\n+ release_user_data = NULL;\n+ } else {\n+ release_func = _raster_source_release_func;\n+ release_user_data = release_callable;\n+ }\n+\n+ /* in case acquire is set we have to clean up anyway */\n+ if (acquire_func != NULL && release_func == NULL) {\n+ release_func = _raster_source_release_func;\n+ }\n+\n+ status = cairo_pattern_set_user_data (\n+ pattern, &raster_source_acquire_key, acquire_user_data,\n+ (acquire_user_data) ? _decref_destroy_func : NULL);\n+ RETURN_NULL_IF_CAIRO_ERROR (status);\n+ if (acquire_user_data != NULL)\n+ Py_INCREF (acquire_user_data);\n+\n+ status = cairo_pattern_set_user_data (\n+ pattern, &raster_source_release_key, release_user_data,\n+ (release_user_data) ? _decref_destroy_func : NULL);\n+ if (status != CAIRO_STATUS_SUCCESS) {\n+ cairo_pattern_set_user_data (\n+ pattern, &raster_source_acquire_key, NULL, NULL);\n+ RETURN_NULL_IF_CAIRO_ERROR (status);\n+ }\n+ if (release_user_data != NULL)\n+ Py_INCREF (release_user_data);\n+\n+ cairo_raster_source_pattern_set_callback_data (pattern, pattern);\n+\n+ Py_BEGIN_ALLOW_THREADS;\n+ cairo_raster_source_pattern_set_acquire (\n+ pattern, acquire_func, release_func);\n+ Py_END_ALLOW_THREADS;\n+\n+ Py_RETURN_NONE;\n+}\n+\n+static PyObject *\n+raster_source_pattern_get_acquire (PycairoRasterSourcePattern *obj) {\n+ cairo_pattern_t *pattern;\n+ void *user_data;\n+ PyObject *acquire_callable, *release_callable;\n+\n+ pattern = obj->pattern;\n+\n+ user_data = cairo_pattern_get_user_data (\n+ pattern, &raster_source_acquire_key);\n+ if (user_data == NULL) {\n+ acquire_callable = Py_None;\n+ } else {\n+ acquire_callable = user_data;\n+ }\n+\n+ user_data = cairo_pattern_get_user_data (\n+ pattern, &raster_source_release_key);\n+ if (user_data == NULL) {\n+ release_callable = Py_None;\n+ } else {\n+ release_callable = user_data;\n+ }\n+\n+ return Py_BuildValue (\"(OO)\", acquire_callable, release_callable);\n+}\n+\n+static PyMethodDef raster_source_pattern_methods[] = {\n+ {\"set_acquire\",\n+ (PyCFunction)raster_source_pattern_set_acquire, METH_VARARGS},\n+ {\"get_acquire\",\n+ (PyCFunction)raster_source_pattern_get_acquire, METH_NOARGS},\n+ {NULL, NULL, 0, NULL},\n+};\n+\n+PyTypeObject PycairoRasterSourcePattern_Type = {\n+ PyVarObject_HEAD_INIT(NULL, 0)\n+ \"cairo.RasterSourcePattern\", /* tp_name */\n+ sizeof(PycairoRasterSourcePattern), /* tp_basicsize */\n+ 0, /* tp_itemsize */\n+ 0, /* tp_dealloc */\n+ 0, /* tp_print */\n+ 0, /* tp_getattr */\n+ 0, /* tp_setattr */\n+ 0, /* tp_compare */\n+ 0, /* tp_repr */\n+ 0, /* tp_as_number */\n+ 0, /* tp_as_sequence */\n+ 0, /* tp_as_mapping */\n+ 0, /* tp_hash */\n+ 0, /* tp_call */\n+ 0, /* tp_str */\n+ 0, /* tp_getattro */\n+ 0, /* tp_setattro */\n+ 0, /* tp_as_buffer */\n+ Py_TPFLAGS_DEFAULT, /* tp_flags */\n+ 0, /* tp_doc */\n+ 0, /* tp_traverse */\n+ 0, /* tp_clear */\n+ 0, /* tp_richcompare */\n+ 0, /* tp_weaklistoffset */\n+ 0, /* tp_iter */\n+ 0, /* tp_iternext */\n+ raster_source_pattern_methods, /* tp_methods */\n+ 0, /* tp_members */\n+ 0, /* tp_getset */\n+ &PycairoPattern_Type, /* tp_base */\n+ 0, /* tp_dict */\n+ 0, /* tp_descr_get */\n+ 0, /* tp_descr_set */\n+ 0, /* tp_dictoffset */\n+ 0, /* tp_init */\n+ 0, /* tp_alloc */\n+ (newfunc)raster_source_pattern_new, /* tp_new */\n+ 0, /* tp_free */\n+ 0, /* tp_is_gc */\n+ 0, /* tp_bases */\n+};\ndiff --git a/cairo/private.h b/cairo/private.h\nindex c031555..7ed5149 100644\n--- a/cairo/private.h\n+++ b/cairo/private.h\n@@ -79,6 +79,9 @@ PyObject *PycairoPattern_FromPattern (cairo_pattern_t *pattern,\n typedef PycairoPattern PycairoMeshPattern;\n extern PyTypeObject PycairoMeshPattern_Type;\n \n+typedef PycairoPattern PycairoRasterSourcePattern;\n+extern PyTypeObject PycairoRasterSourcePattern_Type;\n+\n extern PyTypeObject PycairoRectangleInt_Type;\n PyObject *PycairoRectangleInt_FromRectangleInt (\n const cairo_rectangle_int_t *rectangle_int);\ndiff --git a/docs/reference/patterns.rst b/docs/reference/patterns.rst\nindex 3737ee3..0d82318 100644\n--- a/docs/reference/patterns.rst\n+++ b/docs/reference/patterns.rst\n@@ -607,3 +607,107 @@ class MeshPattern(:class:`Pattern`)\n \n Valid values for corner_num are from 0 to 3 and identify the corners\n as explained in :class:`MeshPattern`.\n+\n+\n+class RasterSourcePattern(:class:`Pattern`)\n+===========================================\n+\n+The raster source provides the ability to supply arbitrary pixel data whilst\n+rendering. The pixels are queried at the time of rasterisation by means of\n+user callback functions, allowing for the ultimate flexibility. For example,\n+in handling compressed image sources, you may keep a MRU cache of decompressed\n+images and decompress sources on the fly and discard old ones to conserve\n+memory.\n+\n+For the raster source to be effective, you must at least specify the acquire\n+and release callbacks which are used to retrieve the pixel data for the region\n+of interest and demark when it can be freed afterwards. Other callbacks are\n+provided for when the pattern is copied temporarily during rasterisation, or\n+more permanently as a snapshot in order to keep the pixel data available for\n+printing.\n+\n+\n+.. class:: RasterSourcePattern(content, width, height)\n+\n+ :param Content content:\n+ content type for the pixel data that will be returned. Knowing the\n+ content type ahead of time is used for analysing the operation and\n+ picking the appropriate rendering path.\n+ :param int width:\n+ maximum size of the sample area\n+ :param int height:\n+ maximum size of the sample area\n+ :raises Error:\n+ :rtype: RasterSourcePattern\n+\n+ Creates a new user pattern for providing pixel data.\n+\n+ Use the setter functions to associate callbacks with the returned pattern.\n+\n+ .. versionadded:: 1.15\n+\n+ .. method:: set_acquire(acquire, release)\n+\n+ :param callable acquire:\n+ acquire callback or :obj:`None` to unset it\n+ :param callable release:\n+ (optional) release callback or :obj:`None`\n+ :raises Error:\n+\n+ Specifies the callbacks used to generate the image surface for a\n+ rendering operation (acquire) and the function used to cleanup that\n+ surface afterwards.\n+\n+ The acquire callback should create a surface (preferably an image\n+ surface created to match the target using\n+ :meth:`Surface.create_similar_image`) that defines at least the region\n+ of interest specified by extents. The surface is allowed to be the\n+ entire sample area, but if it does contain a subsection of the sample\n+ area, the surface extents should be provided by setting the device\n+ offset (along with its width and height) using\n+ :meth:`Surface.set_device_offset`.\n+\n+ .. function:: acquire(pattern, target, extents)\n+\n+ :param Pattern pattern:\n+ the pattern being rendered from\n+ :param Surface target:\n+ the rendering target surface\n+ :param RectangleInt extents:\n+ rectangular region of interest in pixels in sample space\n+ :rtype: Surface\n+\n+ This function is called when a pattern is being rendered from. It\n+ should create a surface that provides the pixel data for the\n+ region of interest as defined by extents, though the surface\n+ itself does not have to be limited to that area. For convenience\n+ the surface should probably be of image type, created with\n+ :meth:`Surface.create_similar_image` for the target (which enables\n+ the number of copies to be reduced during transfer to the device).\n+ Another option, might be to return a similar surface to the target\n+ for explicit handling by the application of a set of cached\n+ sources on the device. The region of sample data provided should\n+ be defined using :meth:`Surface.set_device_offset` to specify the\n+ top-left corner of the sample data (along with width and height of\n+ the surface).\n+\n+ .. function:: release(pattern, surface)\n+\n+ :param Pattern pattern:\n+ the pattern being rendered from\n+ :param Surface surface:\n+ the surface created during acquire\n+\n+ This function is called when the pixel data is no longer being\n+ accessed by the pattern for the rendering operation.\n+\n+ .. versionadded:: 1.15\n+\n+ .. method:: get_acquire()\n+\n+ :returns: a (acquire, release) tuple of callables or None as set\n+ through :meth:`set_acquire`\n+\n+ Queries the current acquire and release callbacks.\n+\n+ .. versionadded:: 1.15\n", "test_patch": "diff --git a/tests/test_pattern.py b/tests/test_pattern.py\nindex ff538df..4263516 100644\n--- a/tests/test_pattern.py\n+++ b/tests/test_pattern.py\n@@ -2,6 +2,52 @@ import cairo\n import pytest\n \n \n+def test_raster_source():\n+ pattern = cairo.RasterSourcePattern(cairo.Content.COLOR, 2, 2)\n+ assert isinstance(pattern, cairo.RasterSourcePattern)\n+ assert issubclass(cairo.RasterSourcePattern, cairo.Pattern)\n+\n+ was_called = []\n+\n+ def acquire_callback(pattern, target, extents):\n+ surface = target.create_similar_image(\n+ cairo.FORMAT_ARGB32, extents.width, extents.height)\n+ surface.set_device_offset(extents.x, extents.y)\n+ context = cairo.Context(surface)\n+ context.set_source_rgb(1, 0, 0)\n+ context.paint()\n+ was_called.append(\"acquire\")\n+ return surface\n+\n+ def release_callback(surface):\n+ was_called.append(\"release\")\n+ return None\n+\n+ pattern.set_acquire(None, release_callback)\n+ assert pattern.get_acquire() == (None, release_callback)\n+\n+ pattern.set_acquire(acquire_callback, None)\n+ assert pattern.get_acquire() == (acquire_callback, None)\n+\n+ pattern.set_acquire(None, None)\n+ assert pattern.get_acquire() == (None, None)\n+\n+ pattern.set_acquire(acquire_callback, release_callback)\n+ assert pattern.get_acquire() == (acquire_callback, release_callback)\n+\n+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10)\n+ context = cairo.Context(surface)\n+ context.set_source(pattern)\n+ context.paint()\n+ assert was_called == [\"acquire\", \"release\"]\n+\n+ with pytest.raises(TypeError):\n+ pattern.set_acquire(None, object())\n+\n+ with pytest.raises(TypeError):\n+ pattern.set_acquire(object(), None)\n+\n+\n def test_cmp_hash():\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10)\n context = cairo.Context(surface)\n", "FAIL_TO_PASS": ["tests/test_pattern.py::test_raster_source"], "PASS_TO_PASS": ["tests/test_pattern.py::test_cmp_hash", "tests/test_pattern.py::test_get_extend", "tests/test_pattern.py::test_get_filter"]} +{"instance_id": "clb-pyc-139", "repo": "pygobject/pycairo", "base_commit": "b780969870a9dd8b42b88c8317679e125b5e2aae", "problem_statement": "device crasher\nThis crashes, I guess the surface needs to explicitly keep the device alive:\r\n\r\n```\r\nf = io.BytesIO()\r\ndev = cairo.ScriptDevice(f)\r\nsurface = cairo.ScriptSurface(dev, cairo.Content.COLOR_ALPHA, 42, 10)\r\nsurface.get_device()\r\n```\r\n\r\nthe docs are not clear..\n", "image": {"image_id": "sha256:3ca1ea28317ca091b21d56022d7a8a3e5a08a2950640a83e4449595bd032c86a", "pull_reference": "yutu0814/pyc-case-139-pycairo@sha256:3ca1ea28317ca091b21d56022d7a8a3e5a08a2950640a83e4449595bd032c86a"}, "cohort": "python50", "patch": "diff --git a/cairo/surface.c b/cairo/surface.c\nindex 517db53..e16480e 100644\n--- a/cairo/surface.c\n+++ b/cairo/surface.c\n@@ -294,7 +294,7 @@ surface_get_device (PycairoSurface *o) {\n cairo_device_t *device = cairo_surface_get_device (o->surface);\n if (device == NULL)\n Py_RETURN_NONE;\n- return PycairoDevice_FromDevice (device);\n+ return PycairoDevice_FromDevice (cairo_device_reference (device));\n }\n \n static PyObject *\n", "test_patch": "diff --git a/tests/test_surface.py b/tests/test_surface.py\nindex 7f69f96..1d222b7 100644\n--- a/tests/test_surface.py\n+++ b/tests/test_surface.py\n@@ -242,6 +242,15 @@ def test_script_surface():\n assert b\"paint\" in f.getvalue()\n \n \n+def test_script_device_device_ref():\n+ f = io.BytesIO()\n+ dev = cairo.ScriptDevice(f)\n+ surface = cairo.ScriptSurface(dev, cairo.Content.COLOR_ALPHA, 42, 10)\n+ del dev\n+ for i in range(10):\n+ surface.get_device()\n+\n+\n def test_script_surface_create_for_target():\n # paint the script proxy\n f = io.BytesIO()\n", "FAIL_TO_PASS": ["tests/test_surface.py::test_script_device_device_ref"], "PASS_TO_PASS": ["tests/test_device.py::test_get_device", "tests/test_surface.py::test_script_surface", "tests/test_surface.py::test_script_surface_create_for_target"]} +{"instance_id": "clb-pyc-141", "repo": "pygobject/pycairo", "base_commit": "eeea4de31f9c8f4496f5695ee0258040b401f0b4", "problem_statement": "Matrix multiply operator typecheck missing \nhttps://bugs.freedesktop.org/show_bug.cgi?id=89162\n", "image": {"image_id": "sha256:058270e42edd92e8231b22ec7536f033a17bf3bb0e9a674a6fe4793b6c6488ae", "pull_reference": "yutu0814/pyc-case-141-pycairo@sha256:058270e42edd92e8231b22ec7536f033a17bf3bb0e9a674a6fe4793b6c6488ae"}, "cohort": "python50", "patch": "diff --git a/cairo/matrix.c b/cairo/matrix.c\nindex 91e8aa1..d6431c6 100644\n--- a/cairo/matrix.c\n+++ b/cairo/matrix.c\n@@ -108,6 +108,10 @@ matrix_multiply (PycairoMatrix *o, PyObject *args) {\n static PyObject *\n matrix_operator_multiply (PycairoMatrix *o, PycairoMatrix *o2) {\n cairo_matrix_t result;\n+ if (PyObject_IsInstance((PyObject *)o2, (PyObject *)&PycairoMatrix_Type) <= 0) {\n+ PyErr_SetString(PyExc_TypeError, \"matrix can only multiply another matrix\");\n+ return NULL;\n+ }\n cairo_matrix_multiply (&result, &o->matrix, &o2->matrix);\n return PycairoMatrix_FromMatrix (&result);\n }\n@@ -326,7 +330,12 @@ PyTypeObject PycairoMatrix_Type = {\n 0, /* tp_getattro */\n 0, /* tp_setattro */\n 0, /* tp_as_buffer */\n+#if PY_MAJOR_VERSION < 3\n+ Py_TPFLAGS_DEFAULT |\n+ Py_TPFLAGS_CHECKTYPES, /* tp_flags */\n+#else\n Py_TPFLAGS_DEFAULT, /* tp_flags */\n+#endif\n NULL, /* tp_doc */\n 0, /* tp_traverse */\n 0, /* tp_clear */\n", "test_patch": "diff --git a/tests/test_api.py b/tests/test_api.py\nindex 20bb058..bc9ca03 100644\n--- a/tests/test_api.py\n+++ b/tests/test_api.py\n@@ -61,6 +61,16 @@ def test_matrix():\n m.scale(1.5, 2.5)\n m.translate(10, 20)\n \n+ with pytest.raises(TypeError):\n+ m * 42\n+\n+ with pytest.raises(TypeError):\n+ m + 42\n+\n+ assert m != 42\n+ assert m == m\n+ assert m != cairo.Matrix()\n+\n \n def test_path():\n # AttributeError: 'module' object has no attribute 'Path'\n", "FAIL_TO_PASS": ["tests/test_api.py::test_matrix"], "PASS_TO_PASS": ["tests/test_api.py::test_context", "tests/test_api.py::test_error", "tests/test_api.py::test_pattern"]} +{"instance_id": "clb-pyc-142", "repo": "pygobject/pycairo", "base_commit": "cd6b840aeab1515343a71a997b0a2ce48fce6d82", "problem_statement": "Memory leak in ImageSurface.get_data\nWhen creating an ImageSurface in a loop and calling `get_data()` on it, memory leaks.\r\nIt's about 5KB in resident memory, shown by the mem function, and about 1MB of virtual memory, observable in htop, which is about the size of the surface.\r\n\r\nCalling `get_data` in the loop on the same SurfaceImage does not allocate more memory.\r\n\r\n```python\r\n#!/usr/bin/env python3\r\n\r\nimport cairo\r\nimport resource\r\n\r\ndef mem():\r\n print(\"Memory usage: {:.0f}M\".format(\r\n resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))\r\n\r\nmem()\r\n\r\nfor i in range(10000):\r\n s = cairo.ImageSurface(cairo.FORMAT_ARGB32, 500, 500)\r\n s.get_data()\r\n\r\nmem()\r\n#input()\r\n```\r\n\r\nI'm using Python 3.6.1 and the latest commit from master as well as 1.13.2+5+gcd6b840-1 (from the ArchLinux repos).\n", "image": {"image_id": "sha256:020d2f34e4341dd12b010801affd93f55ec641d516486848b26389ba8e785c4a", "pull_reference": "yutu0814/pyc-case-142-pycairo@sha256:020d2f34e4341dd12b010801affd93f55ec641d516486848b26389ba8e785c4a"}, "cohort": "python50", "patch": "diff --git a/cairo/bufferproxy.c b/cairo/bufferproxy.c\nnew file mode 100644\nindex 0000000..ff2c2ed\n--- /dev/null\n+++ b/cairo/bufferproxy.c\n@@ -0,0 +1,135 @@\n+/* -*- mode: C; c-basic-offset: 2 -*-\n+ *\n+ * Pycairo - Python bindings for cairo\n+ *\n+ * Copyright © 2017 Christoph Reiter\n+ *\n+ * This library is free software; you can redistribute it and/or\n+ * modify it either under the terms of the GNU Lesser General Public\n+ * License version 2.1 as published by the Free Software Foundation\n+ * (the \"LGPL\") or, at your option, under the terms of the Mozilla\n+ * Public License Version 1.1 (the \"MPL\"). If you do not alter this\n+ * notice, a recipient may use your version of this file under either\n+ * the MPL or the LGPL.\n+ *\n+ * You should have received a copy of the LGPL along with this library\n+ * in the file COPYING-LGPL-2.1; if not, write to the Free Software\n+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n+ * You should have received a copy of the MPL along with this library\n+ * in the file COPYING-MPL-1.1\n+ *\n+ * The contents of this file are subject to the Mozilla Public License\n+ * Version 1.1 (the \"License\"); you may not use this file except in\n+ * compliance with the License. You may obtain a copy of the License at\n+ * http://www.mozilla.org/MPL/\n+ *\n+ * This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY\n+ * OF ANY KIND, either express or implied. See the LGPL or the MPL for\n+ * the specific language governing rights and limitations.\n+ */\n+\n+#define PY_SSIZE_T_CLEAN\n+#include \n+\n+#include \"config.h\"\n+#include \"private.h\"\n+\n+#if PY_MAJOR_VERSION >= 3\n+\n+typedef struct {\n+ PyObject_HEAD\n+ PyObject *exporter;\n+ void *buf;\n+ Py_ssize_t len;\n+} Pycairo_BufferProxy;\n+\n+static PyTypeObject Pycairo_BufferProxyType = {\n+ PyVarObject_HEAD_INIT(NULL, 0)\n+ \"cairo._BufferProxy\",\n+ sizeof(Pycairo_BufferProxy),\n+};\n+\n+static int\n+buffer_proxy_getbuffer(PyObject *exporter, Py_buffer *view, int flags)\n+{\n+ Pycairo_BufferProxy *self = (Pycairo_BufferProxy *)exporter;\n+\n+ return PyBuffer_FillInfo (view, exporter, self->buf, self->len, 0, 0);\n+}\n+\n+static PyBufferProcs Pycairo_BufferProxy_as_buffer = {\n+ (getbufferproc)buffer_proxy_getbuffer,\n+ (releasebufferproc)0,\n+};\n+\n+PyObject *\n+buffer_proxy_create_view(PyObject *exporter, void *buf, Py_ssize_t len) {\n+ PyObject *memoryview;\n+ PyObject *obj;\n+ Pycairo_BufferProxy *self;\n+\n+ obj = (PyObject *)PyObject_GC_New(Pycairo_BufferProxy,\n+ &Pycairo_BufferProxyType);\n+ if (obj == NULL)\n+ return NULL;\n+\n+ self = (Pycairo_BufferProxy *)obj;\n+ Py_INCREF(exporter);\n+ self->exporter = exporter;\n+ self->buf = buf;\n+ self->len = len;\n+ PyObject_GC_Track(obj);\n+\n+ memoryview = PyMemoryView_FromObject (obj);\n+ Py_DECREF(obj);\n+\n+ return memoryview;\n+}\n+\n+static int\n+buffer_proxy_traverse(PyObject* obj, visitproc visit, void *arg)\n+{\n+ Pycairo_BufferProxy *self = (Pycairo_BufferProxy *)obj;\n+\n+ Py_VISIT(self->exporter);\n+ return 0;\n+}\n+\n+static int\n+buffer_proxy_clear(PyObject *obj)\n+{\n+ Pycairo_BufferProxy *self = (Pycairo_BufferProxy *)obj;\n+\n+ Py_CLEAR(self->exporter);\n+ return 0;\n+}\n+\n+static void\n+buffer_proxy_dealloc(PyObject* obj)\n+{\n+ Pycairo_BufferProxy *self = (Pycairo_BufferProxy *)obj;\n+\n+ PyObject_GC_UnTrack(obj);\n+\n+ self->buf = NULL;\n+ self->len = 0;\n+ Py_DECREF(self->exporter);\n+\n+ Py_TYPE(obj)->tp_free(obj);\n+}\n+#endif\n+\n+int\n+init_buffer_proxy (void) {\n+#if PY_MAJOR_VERSION >= 3\n+ Pycairo_BufferProxyType.tp_as_buffer = &Pycairo_BufferProxy_as_buffer;\n+ Pycairo_BufferProxyType.tp_dealloc = &buffer_proxy_dealloc;\n+ Pycairo_BufferProxyType.tp_traverse = &buffer_proxy_traverse;\n+ Pycairo_BufferProxyType.tp_clear = &buffer_proxy_clear;\n+ Pycairo_BufferProxyType.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC;\n+\n+ if (PyType_Ready(&Pycairo_BufferProxyType) < 0)\n+ return -1;\n+#endif\n+ return 0;\n+}\ndiff --git a/cairo/cairomodule.c b/cairo/cairomodule.c\nindex f5dd61d..d2fd13b 100644\n--- a/cairo/cairomodule.c\n+++ b/cairo/cairomodule.c\n@@ -315,6 +315,9 @@ PYCAIRO_MOD_INIT(_cairo)\n if (m == NULL)\n return PYCAIRO_MOD_ERROR_VAL;\n \n+ if(init_buffer_proxy() < 0)\n+ return PYCAIRO_MOD_ERROR_VAL;\n+\n if(init_enums(m) < 0)\n return PYCAIRO_MOD_ERROR_VAL;\n \ndiff --git a/cairo/private.h b/cairo/private.h\nindex d2910f0..100fc39 100644\n--- a/cairo/private.h\n+++ b/cairo/private.h\n@@ -193,6 +193,10 @@ int Pycairo_Check_Status (cairo_status_t status);\n \n PyObject *error_get_type(void);\n \n+int init_buffer_proxy(void);\n+\n+PyObject *buffer_proxy_create_view(PyObject *exporter, void *buf, Py_ssize_t len);\n+\n /* int enums */\n \n int init_enums(PyObject *module);\ndiff --git a/cairo/surface.c b/cairo/surface.c\nindex bf86774..4354fd8 100644\n--- a/cairo/surface.c\n+++ b/cairo/surface.c\n@@ -765,7 +765,6 @@ image_surface_format_stride_for_width (PyObject *self, PyObject *args) {\n static PyObject *\n image_surface_get_data (PycairoImageSurface *o) {\n #if PY_MAJOR_VERSION >= 3\n- Py_buffer view;\n cairo_surface_t *surface;\n int height, stride;\n unsigned char * buffer;\n@@ -777,10 +776,8 @@ image_surface_get_data (PycairoImageSurface *o) {\n }\n height = cairo_image_surface_get_height (surface);\n stride = cairo_image_surface_get_stride (surface);\n- if (PyBuffer_FillInfo (&view, (PyObject *)o, buffer, height * stride, 0, 0) < 0)\n- return NULL;\n \n- return PyMemoryView_FromBuffer (&view);\n+ return buffer_proxy_create_view((PyObject *)o, buffer, height * stride);\n #else\n return PyBuffer_FromReadWriteObject((PyObject *)o, 0, Py_END_OF_BUFFER);\n #endif\ndiff --git a/setup.py b/setup.py\nindex f568bf9..4188889 100755\n--- a/setup.py\n+++ b/setup.py\n@@ -230,6 +230,7 @@ def main():\n cairo_ext = Extension(\n name='cairo._cairo',\n sources=[\n+ 'cairo/bufferproxy.c',\n 'cairo/error.c',\n 'cairo/cairomodule.c',\n 'cairo/context.c',\n", "test_patch": "diff --git a/tests/test_surface.py b/tests/test_surface.py\nindex 8aec540..00253c5 100644\n--- a/tests/test_surface.py\n+++ b/tests/test_surface.py\n@@ -2,6 +2,7 @@\n \n import io\n import os\n+import sys\n import array\n import tempfile\n import struct\n@@ -10,6 +11,15 @@ import cairo\n import pytest\n \n \n+def test_image_surface_get_data_refcount():\n+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10)\n+ assert sys.getrefcount(surface) == 2\n+ d = surface.get_data()\n+ assert sys.getrefcount(surface) == 3\n+ del d\n+ assert sys.getrefcount(surface) == 2\n+\n+\n def test_surface_get_content():\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10)\n assert surface.get_content() == cairo.Content.COLOR_ALPHA\n", "FAIL_TO_PASS": ["tests/test_surface.py::test_image_surface_get_data_refcount"], "PASS_TO_PASS": ["tests/test_surface.py::test_surface_get_content", "tests/test_surface.py::test_surface_get_format", "tests/test_surface.py::test_image_surface_png_obj_roundtrip"]} +{"instance_id": "clb-pyc-156", "repo": "ghaering/pysqlite", "base_commit": "d7c44a6b62ccf27ae2a006d32dc25cd49ca45320", "problem_statement": "Implement limits\n_From [philippe...@gmail.com](https://code.google.com/u/102219890224326646040/) on March 18, 2011 02:38:14_\n\nSee http://code.google.com/r/philippemay-limits/ Gerhard, if you agree, would be great to merge.\n\n_Original issue: http://code.google.com/p/pysqlite/issues/detail?id=33_\n\n", "image": {"image_id": "sha256:b50c96b41175954a45f6372c0271846b3ebe4c3c74422ad91b0d025f38b82ac0", "pull_reference": "yutu0814/pyc-case-156-pysqlite@sha256:b50c96b41175954a45f6372c0271846b3ebe4c3c74422ad91b0d025f38b82ac0"}, "cohort": "python50", "patch": "diff --git a/doc/sphinx/sqlite3.rst b/doc/sphinx/sqlite3.rst\nindex e057687..6f03e97 100644\n--- a/doc/sphinx/sqlite3.rst\n+++ b/doc/sphinx/sqlite3.rst\n@@ -353,6 +353,24 @@ Connection Objects\n one. All necessary constants are available in the :mod:`sqlite3` module.\n \n \n+.. method:: Connection.get_limit(limit_id)\n+\n+ This routine returns the current value of the limit specified by the\n+ constant limit_id.\n+\n+ Please consult the SQLite documentation about the possible values for the\n+ limit_id parameter.\n+\n+\n+.. method:: Connection.set_limit(limit_id, new_value)\n+\n+ This routine sets a new value for the limit specified by the\n+ constant limit_id.\n+\n+ Please consult the SQLite documentation about the possible values for the\n+ limit_id parameter.\n+\n+\n .. method:: Connection.set_progress_handler(handler, n)\n \n This routine registers a callback. The callback is invoked for every *n*\ndiff --git a/src/connection.c b/src/connection.c\nindex 537e488..8b96c6d 100644\n--- a/src/connection.c\n+++ b/src/connection.c\n@@ -1018,6 +1018,48 @@ static int _progress_handler(void* user_arg)\n return rc;\n }\n \n+static PyObject* pysqlite_connection_get_limit(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)\n+{\n+ int limit_id, new_val;\n+\n+ static char *kwlist[] = { \"limit_id\", NULL };\n+ int retval;\n+\n+ if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {\n+ return NULL;\n+ }\n+\n+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"i:get_limit\",\n+ kwlist, &limit_id)) {\n+ return NULL;\n+ }\n+\n+ retval = sqlite3_limit(self->db, limit_id, -1);\n+\n+ return PyInt_FromLong(retval);\n+}\n+\n+static PyObject* pysqlite_connection_set_limit(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)\n+{\n+ int limit_id, new_val;\n+\n+ static char *kwlist[] = { \"limit_id\", \"new_val\", NULL };\n+ int retval;\n+\n+ if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {\n+ return NULL;\n+ }\n+\n+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"ii:set_limit\",\n+ kwlist, &limit_id, &new_val)) {\n+ return NULL;\n+ }\n+\n+ retval = sqlite3_limit(self->db, limit_id, new_val);\n+\n+ return PyInt_FromLong(retval);\n+}\n+\n static PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)\n {\n PyObject* authorizer_cb;\n@@ -1609,6 +1651,10 @@ static PyMethodDef connection_methods[] = {\n PyDoc_STR(\"Creates a new function. Non-standard.\")},\n {\"create_aggregate\", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,\n PyDoc_STR(\"Creates a new aggregate. Non-standard.\")},\n+ {\"set_limit\", (PyCFunction)pysqlite_connection_set_limit, METH_VARARGS|METH_KEYWORDS,\n+ PyDoc_STR(\"Sets SQLite limit. Non-standard.\")},\n+ {\"get_limit\", (PyCFunction)pysqlite_connection_get_limit, METH_VARARGS|METH_KEYWORDS,\n+ PyDoc_STR(\"Gets SQLite limit. Non-standard.\")},\n {\"set_authorizer\", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,\n PyDoc_STR(\"Sets authorizer callback. Non-standard.\")},\n #ifdef HAVE_LOAD_EXTENSION\n", "test_patch": "diff --git a/lib/test/hooks.py b/lib/test/hooks.py\nindex e7cd49d..60adb5b 100644\n--- a/lib/test/hooks.py\n+++ b/lib/test/hooks.py\n@@ -152,10 +152,31 @@ class ProgressTests(unittest.TestCase):\n con.execute(\"select 1 union select 2 union select 3\").fetchall()\n self.assertEqual(action, 0, \"progress handler was not cleared\")\n \n+class LimitTests(unittest.TestCase):\n+ def CheckGetLimit(self):\n+ \"\"\"\n+ Test that the get limit method return something useful.\n+ \"\"\"\n+ con = sqlite.connect(\":memory:\")\n+ val = con.get_limit(sqlite.SQLITE_LIMIT_VARIABLE_NUMBER)\n+ self.assertTrue(val > 0)\n+\n+ def CheckSetLimit(self):\n+ \"\"\"\n+ Test that the set limit method actally changes limits.\n+ \"\"\"\n+ con = sqlite.connect(\":memory:\")\n+ oldval = con.get_limit(sqlite.SQLITE_LIMIT_VARIABLE_NUMBER)\n+ con.set_limit(sqlite.SQLITE_LIMIT_VARIABLE_NUMBER, oldval - 1)\n+ newval = con.get_limit(sqlite.SQLITE_LIMIT_VARIABLE_NUMBER)\n+\n+ self.assertEqual(newval, oldval - 1)\n+\n def suite():\n collation_suite = unittest.makeSuite(CollationTests, \"Check\")\n progress_suite = unittest.makeSuite(ProgressTests, \"Check\")\n- return unittest.TestSuite((collation_suite, progress_suite))\n+ limit_suite = unittest.makeSuite(LimitTests, \"Check\")\n+ return unittest.TestSuite((collation_suite, progress_suite, limit_suite))\n \n def test():\n runner = unittest.TextTestRunner()\n", "FAIL_TO_PASS": ["lib/test/hooks.py::LimitTests::CheckGetLimit", "lib/test/hooks.py::LimitTests::CheckSetLimit"], "PASS_TO_PASS": ["lib/test/hooks.py::CollationTests::CheckCreateCollationNotCallable", "lib/test/hooks.py::ProgressTests::CheckProgressHandlerUsed", "lib/test/hooks.py::ProgressTests::CheckCancelOperation"]} +{"instance_id": "clb-pyc-159", "repo": "astrofrog/fast-histogram", "base_commit": "085efdad6570e25440beab781ef70e1f81605c12", "problem_statement": "Weighted histogram differs from numpy unless the data is explicity copied.\nFirst, thanks for the great library. I suspect I am hitting a memory issue. Unless I explictly copy the arrays before passing them to histogram2D, the results differ from numpy. So far, I only saw this happen when I am using the weighted version of the 2Dhistogram. Code and output follows\r\n\r\n```python\r\n#! /usr/bin/env python\r\nimport numpy as np\r\nimport fast_histogram as ft\r\n\r\nprint(f\"Numpy version {np.__version__}\")\r\nprint(f\"Fast-histogram version {ft.__version__}\")\r\n\r\n# Initial data\r\n#######################################################\r\nnbins=100\r\nmax_val=17.64\r\nmin_val=0.0\r\nset_range=[[min_val, max_val],[min_val, max_val]]\r\nwith np.load(\"data.npz\") as d:\r\n pot = d[\"pot\"]\r\n displ_new = d[\"displ_new\"]\r\n bond_ind = d[\"bond_ind\"]\r\n\r\n\r\n# Without copy\r\nprint(\"NOT EXPLICITLY COPYING THE DATA\")\r\npot_array = pot[:, bond_ind[0,0], bond_ind[0,1]]\r\narr1 = displ_new[:,bond_ind[0,0]]\r\narr2 = displ_new[:,bond_ind[0,1]]\r\n\r\n#Run the histograms\r\nh_np = np.histogram2d(arr1, arr2, nbins, range=set_range, weights=pot_array)[0]\r\nh_ft = ft.histogram2d(arr1, arr2, nbins, range=set_range, weights=pot_array)\r\n\r\nprint(\"===FAST-HIST===\")\r\nprint(h_ft)\r\nprint(\"===NUMPY===\")\r\nprint(h_np)\r\n\r\n\r\n# With copy\r\nprint(\"EXPLICITLY COPYING THE DATA\")\r\npot_array = pot[:, bond_ind[0,0], bond_ind[0,1]].copy()\r\narr1 = displ_new[:,bond_ind[0,0]].copy()\r\narr2 = displ_new[:,bond_ind[0,1]].copy()\r\n\r\n#Run the histograms\r\nh_np = np.histogram2d(arr1, arr2, nbins, range=set_range, weights=pot_array)[0]\r\nh_ft = ft.histogram2d(arr1, arr2, nbins, range=set_range, weights=pot_array)\r\n\r\nprint(\"===FAST-HIST===\")\r\nprint(h_ft)\r\nprint(\"===NUMPY===\")\r\nprint(h_np)\r\n```\r\n\r\nwith output \r\n\r\n```\r\nNumpy version 1.18.1\r\nFast-histogram version 0.8\r\nNOT EXPLICITLY COPYING THE DATA\r\n===FAST-HIST===\r\n[[0. 0. 0. ... 0. 0. 0. ]\r\n [0.0425809 0. 0. ... 0. 0. 0. ]\r\n [0. 0. 0.01108671 ... 0. 0. 0. ]\r\n ...\r\n [0. 0. 0. ... 0. 0. 0. ]\r\n [0. 0. 0. ... 0. 0. 0. ]\r\n [0. 0. 0. ... 0. 0. 0. ]]\r\n===NUMPY===\r\n[[0. 0. 0. ... 0. 0. 0. ]\r\n [0.00524697 0.11627543 0.00218829 ... 0. 0. 0. ]\r\n [0. 0.0233833 0.08906353 ... 0. 0. 0. ]\r\n ...\r\n [0. 0. 0. ... 0. 0. 0. ]\r\n [0. 0. 0. ... 0. 0. 0. ]\r\n [0. 0. 0. ... 0. 0. 0. ]]\r\nEXPLICITLY COPYING THE DATA\r\n===FAST-HIST===\r\n[[0. 0. 0. ... 0. 0. 0. ]\r\n [0.00524697 0.11627543 0.00218829 ... 0. 0. 0. ]\r\n [0. 0.0233833 0.08906353 ... 0. 0. 0. ]\r\n ...\r\n [0. 0. 0. ... 0. 0. 0. ]\r\n [0. 0. 0. ... 0. 0. 0. ]\r\n [0. 0. 0. ... 0. 0. 0. ]]\r\n===NUMPY===\r\n[[0. 0. 0. ... 0. 0. 0. ]\r\n [0.00524697 0.11627543 0.00218829 ... 0. 0. 0. ]\r\n [0. 0.0233833 0.08906353 ... 0. 0. 0. ]\r\n ...\r\n [0. 0. 0. ... 0. 0. 0. ]\r\n [0. 0. 0. ... 0. 0. 0. ]\r\n [0. 0. 0. ... 0. 0. 0. ]]\r\n```\r\n\r\nThe data file necessary to run the code is attached. Due to github restrictions, I had to zip it first.\r\n[data.npz.zip](https://github.com/astrofrog/fast-histogram/files/4671735/data.npz.zip)\r\n\r\n\n", "image": {"image_id": "sha256:6c5fb4016d7c9713831eb383ae90b667367d51538afd93fd0bdfd6edefa11313", "pull_reference": "yutu0814/pyc-case-159-fast-histogram@sha256:6c5fb4016d7c9713831eb383ae90b667367d51538afd93fd0bdfd6edefa11313"}, "cohort": "python50", "patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex 9874643..1def2eb 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -1,3 +1,11 @@\n+0.9 (unreleased)\n+----------------\n+\n+- Fixed a bug that caused incorrect results in the weighted\n+ 1-d histogram and the weighted and unweighted 2-d histogram\n+ functions if using arrays with different layouts in memory.\n+ [#52]\n+\n 0.8 (2020-01-07)\n ----------------\n \ndiff --git a/fast_histogram/_histogram_core.c b/fast_histogram/_histogram_core.c\nindex 8d4f68b..77512bf 100644\n--- a/fast_histogram/_histogram_core.c\n+++ b/fast_histogram/_histogram_core.c\n@@ -302,7 +302,8 @@ static PyObject *_histogram2d(PyObject *self, PyObject *args) {\n do {\n \n /* Get the inner loop data/stride/count values */\n- npy_intp stride = *strideptr;\n+ npy_intp stride0 = strideptr[0];\n+ npy_intp stride1 = strideptr[1];\n npy_intp size = *innersizeptr;\n \n /* This is a typical inner loop for NPY_ITER_EXTERNAL_LOOP */\n@@ -317,8 +318,8 @@ static PyObject *_histogram2d(PyObject *self, PyObject *args) {\n count[iy + ny * ix] += 1.;\n }\n \n- dataptr[0] += stride;\n- dataptr[1] += stride;\n+ dataptr[0] += stride0;\n+ dataptr[1] += stride1;\n }\n \n } while (iternext(iter));\n@@ -451,7 +452,8 @@ static PyObject *_histogram1d_weighted(PyObject *self, PyObject *args) {\n do {\n \n /* Get the inner loop data/stride/count values */\n- npy_intp stride = *strideptr;\n+ npy_intp stride0 = strideptr[0];\n+ npy_intp stride1 = strideptr[1];\n npy_intp size = *innersizeptr;\n \n /* This is a typical inner loop for NPY_ITER_EXTERNAL_LOOP */\n@@ -465,8 +467,8 @@ static PyObject *_histogram1d_weighted(PyObject *self, PyObject *args) {\n count[ix] += tw;\n }\n \n- dataptr[0] += stride;\n- dataptr[1] += stride;\n+ dataptr[0] += stride0;\n+ dataptr[1] += stride1;\n }\n \n } while (iternext(iter));\n@@ -610,7 +612,9 @@ static PyObject *_histogram2d_weighted(PyObject *self, PyObject *args) {\n do {\n \n /* Get the inner loop data/stride/count values */\n- npy_intp stride = *strideptr;\n+ npy_intp stride0 = strideptr[0];\n+ npy_intp stride1 = strideptr[1];\n+ npy_intp stride2 = strideptr[2];\n npy_intp size = *innersizeptr;\n \n /* This is a typical inner loop for NPY_ITER_EXTERNAL_LOOP */\n@@ -626,9 +630,9 @@ static PyObject *_histogram2d_weighted(PyObject *self, PyObject *args) {\n count[iy + ny * ix] += tw;\n }\n \n- dataptr[0] += stride;\n- dataptr[1] += stride;\n- dataptr[2] += stride;\n+ dataptr[0] += stride0;\n+ dataptr[1] += stride1;\n+ dataptr[2] += stride2;\n }\n \n } while (iternext(iter));\n", "test_patch": "diff --git a/fast_histogram/tests/test_histogram.py b/fast_histogram/tests/test_histogram.py\nindex f4c86a6..198f49b 100644\n--- a/fast_histogram/tests/test_histogram.py\n+++ b/fast_histogram/tests/test_histogram.py\n@@ -201,3 +201,32 @@ def test_array_bins():\n histogram2d([1, 2, 3], [1, 2 ,3], bins=[edges, edges],\n range=[(0, 10), (0, 10)])\n assert exc.value.args[0] == 'bins should be an iterable of two integers'\n+\n+\n+def test_mixed_strides():\n+\n+ # Make sure all functions work properly when passed arrays with mismatched\n+ # strides.\n+\n+ x = np.random.random((30, 20, 40, 50))[:, 10, :, 20]\n+ y = np.random.random((30, 40, 50))[:, :, 10]\n+ z = np.random.random((30, 10, 5, 80, 90))[:, 5, 2, ::2, 22]\n+\n+ assert x.shape == y.shape and x.shape == z.shape\n+ assert x.strides != y.strides and y.strides != z.strides and z.strides != x.strides\n+\n+ result_1 = histogram1d(x, bins=10, range=(0, 1))\n+ result_2, _ = np.histogram(x, bins=10, range=(0, 1))\n+ np.testing.assert_equal(result_1, result_2)\n+\n+ result_3 = histogram1d(x, weights=y, bins=10, range=(0, 1))\n+ result_4, _ = np.histogram(x, weights=y, bins=10, range=(0, 1))\n+ np.testing.assert_equal(result_3, result_4)\n+\n+ result_5 = histogram2d(x, y, bins=(10, 10), range=[(0, 1), (0, 1)])\n+ result_6, _, _ = np.histogram2d(x.ravel(), y.ravel(), bins=(10, 10), range=[(0, 1), (0, 1)])\n+ np.testing.assert_equal(result_5, result_6)\n+\n+ result_7 = histogram2d(x, y, weights=z, bins=(10, 10), range=[(0, 1), (0, 1)])\n+ result_8, _, _ = np.histogram2d(x.ravel(), y.ravel(), weights=z.ravel(), bins=(10, 10), range=[(0, 1), (0, 1)])\n+ np.testing.assert_equal(result_7, result_8)\n", "FAIL_TO_PASS": ["fast_histogram/tests/test_histogram.py::test_mixed_strides"], "PASS_TO_PASS": ["fast_histogram/tests/test_histogram.py::test_nd_arrays", "fast_histogram/tests/test_histogram.py::test_list", "fast_histogram/tests/test_histogram.py::test_non_contiguous"]} +{"instance_id": "clb-pyc-160", "repo": "astrofrog/fast-histogram", "base_commit": "76b6f57a27f31cdefc23444f91611a00c9b4332d", "problem_statement": "Incorrect work for 3d np.array\nI'm going to use your package because it is exactly what I need (I just need to add normalization). I found out that `histogram1d()` works incorrectly with 3d np.arrays. \r\nHere is an example of my test:\r\n```\r\nfrom future import division\r\nfrom fast_histogram import histogram1d\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef pdf_from_array_np(array, bins, range):\r\npdf, _ = np.histogram(array, bins=bins, range=range, normed=1)\r\nreturn pdf\r\n\r\ndef pdf_from_array(array, bins, range):\r\npdf = histogram1d(array, bins=bins, range=range)\r\nnorm = np.sum(pdf)/bins\r\nreturn pdf/norm\r\n\r\narr = np.random.uniform(-0.5, 0.5, 64**3)\r\narr = arr.reshape((64, 64, 64))\r\nx = np.linspace(-0.5, 0.5, 100)\r\npdf_np = pdf_from_array_np(arr, 100, [-0.5, 0.5])\r\nplt.plot(x, pdf_np, label='np')\r\npdf_fast = pdf_from_array(arr, 100, [-0.5, 0.5])\r\nplt.plot(x, pdf_fast, label='fast')\r\nplt.legend()\r\nplt.show()\r\nprint(np.sum((pdf_fast-pdf_np)**2))\r\n```\r\n![figure_1](https://user-images.githubusercontent.com/26126781/42704521-5d10feae-868d-11e8-899c-afab42ccc8cf.png)\r\n\r\n\r\n \n", "image": {"image_id": "sha256:137667158630a877c17512394db970de833e35f35720c82c792bda08c712a10e", "pull_reference": "yutu0814/pyc-case-160-fast-histogram@sha256:137667158630a877c17512394db970de833e35f35720c82c792bda08c712a10e"}, "cohort": "python50", "patch": "diff --git a/CHANGES.rst b/CHANGES.rst\nindex 246a4e8..16aaa5a 100644\n--- a/CHANGES.rst\n+++ b/CHANGES.rst\n@@ -1,7 +1,8 @@\n 0.5 (unreleased)\n ----------------\n \n-- No changes yet.\n+- Fix bug that caused histograms of n-dimensional arrays to\n+ not be computed correctly. [#21]\n \n 0.4 (2018-02-12)\n ----------------\ndiff --git a/fast_histogram/histogram.py b/fast_histogram/histogram.py\nindex afde42e..3fca89b 100644\n--- a/fast_histogram/histogram.py\n+++ b/fast_histogram/histogram.py\n@@ -50,6 +50,9 @@ def histogram1d(x, bins, range, weights=None):\n \n x = np.ascontiguousarray(x, np.float)\n \n+ if x.ndim > 1:\n+ x = x.ravel()\n+\n if weights is None:\n return _histogram1d(x, nx, xmin, xmax)\n else:\n@@ -114,6 +117,12 @@ def histogram2d(x, y, bins, range, weights=None):\n x = np.ascontiguousarray(x, np.float)\n y = np.ascontiguousarray(y, np.float)\n \n+ if x.ndim > 1:\n+ x = x.ravel()\n+\n+ if y.ndim > 1:\n+ y = y.ravel()\n+\n if weights is None:\n return _histogram2d(x, y, nx, xmin, xmax, ny, ymin, ymax)\n else:\n", "test_patch": "diff --git a/fast_histogram/tests/test_histogram.py b/fast_histogram/tests/test_histogram.py\nindex 2215f02..0771e6a 100644\n--- a/fast_histogram/tests/test_histogram.py\n+++ b/fast_histogram/tests/test_histogram.py\n@@ -85,3 +85,21 @@ def test_2d_compare_with_numpy(size, nx, xmin, xmax, ny, ymin, ymax, weights):\n range=((xmin, xmax), (ymin, ymax)))\n \n np.testing.assert_equal(fast, reference)\n+\n+\n+def test_nd_arrays():\n+\n+ x = np.random.random(1000)\n+\n+ result_1d = histogram1d(x, bins=10, range=(0, 1))\n+ result_3d = histogram1d(x.reshape((10, 10, 10)), bins=10, range=(0, 1))\n+\n+ np.testing.assert_equal(result_1d, result_3d)\n+\n+ y = np.random.random(1000)\n+\n+ result_1d = histogram2d(x, y, bins=(10, 10), range=[(0, 1), (0, 1)])\n+ result_3d = histogram2d(x.reshape((10, 10, 10)), y.reshape((10, 10, 10)),\n+ bins=(10, 10), range=[(0, 1), (0, 1)])\n+\n+ np.testing.assert_equal(result_1d, result_3d)\n", "FAIL_TO_PASS": ["fast_histogram/tests/test_histogram.py::test_nd_arrays"], "PASS_TO_PASS": ["fast_histogram/tests/test_histogram.py::test_1d_compare_with_numpy", "fast_histogram/tests/test_histogram.py::test_2d_compare_with_numpy"]} +{"instance_id": "clb-pyc-174", "repo": "spglib/spglib", "base_commit": "9458171a2eb9bea9036632a408da7b269ea07bbb", "problem_statement": "Segmentation fault in `v2.0.1` for a specific cell input\n## Describe the bug\r\n\r\nSegmentation fault when calling `spglib.get_symmetry` for a specific cell input after pip installing `v2.0.1`. Previous versions are fine.\r\n\r\n## To Reproduce\r\n\r\nThe script below causes a segmentation fault on Linux and MacOS systems (**works fine on Windows**) with the following GNU debugger output:\r\n```\r\nThread 1 \"python\" received signal SIGSEGV, Segmentation fault.\r\n0x00007fffab38f91e in get_symmetry_with_site_tensors (equivalent_atoms=equivalent_atoms@entry=0x555558c8cd40, permutations=permutations@entry=0x7fffffffbc88, primitive_lattice=primitive_lattice@entry=0x555558cf8770, cell=cell@entry=0x555558cdad90, with_time_reversal=with_time_reversal@entry=1, is_axial=is_axial@entry=0, symprec=symprec@entry=0.10000000000000001, angle_tolerance=angle_tolerance@entry=5, mag_symprec=mag_symprec@entry=-1, max_size=2592) at src/spglib.c:1787\r\n```\r\n\r\n```python\r\nimport spglib #v2.0.1\r\nimport numpy as np\r\n\r\n# Cell data taken from task \"mp-806965\" in the Materials Project database.\r\n\r\ndata = (\r\n (\r\n np.array(\r\n [\r\n [5.2419100e00, 0.0000000e00, 0.0000000e00],\r\n [-3.4590000e-03, 5.6005340e00, 0.0000000e00],\r\n [-2.6184020e00, -1.8789800e00, 1.1148141e01],\r\n ]\r\n ),\r\n np.array(\r\n [\r\n [0.730776, 0.31474, 0.510679],\r\n [0.943931, 0.414234, 0.832868],\r\n [0.056367, 0.524886, 0.155721],\r\n [0.829407, 0.834674, 0.662821],\r\n [0.665078, 0.665214, 0.316142],\r\n [0.49794, 0.497249, 0.995771],\r\n [0.332764, 0.334746, 0.669724],\r\n [0.001174, 0.996383, 0.002809],\r\n [0.181127, 0.169218, 0.349259],\r\n [0.697256, 0.577902, 0.159052],\r\n [0.308683, 0.416793, 0.832813],\r\n [0.366841, 0.258942, 0.50616],\r\n [0.325228, 0.466901, 0.290137],\r\n [0.188427, 0.691028, 0.042737],\r\n [0.452284, 0.963256, 0.296948],\r\n [0.318269, 0.200207, 0.036324],\r\n [0.647716, 0.725678, 0.498078],\r\n [0.025986, 0.916766, 0.83257],\r\n [0.862965, 0.366944, 0.373363],\r\n [0.976455, 0.141503, 0.623984],\r\n [0.989161, 0.872155, 0.371099],\r\n [0.112981, 0.629933, 0.630065],\r\n [0.981407, 0.10434, 0.16776],\r\n [0.683769, 0.794257, 0.959752],\r\n [0.550973, 0.033926, 0.704626],\r\n [0.812861, 0.30269, 0.957533],\r\n [0.689973, 0.527716, 0.707103],\r\n ]\r\n ),\r\n [1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],\r\n [\r\n 0.001,\r\n 0.001,\r\n 0.001,\r\n 1.927,\r\n 1.947,\r\n 1.94,\r\n 1.94,\r\n 1.928,\r\n 1.949,\r\n -0.084,\r\n -0.079,\r\n -0.085,\r\n 0.002,\r\n 0.008,\r\n 0.01,\r\n -0.002,\r\n -0.004,\r\n -0.001,\r\n 0.002,\r\n 0.008,\r\n 0.011,\r\n -0.001,\r\n -0.005,\r\n -0.003,\r\n -0.003,\r\n 0.005,\r\n 0.006,\r\n ],\r\n ),\r\n 0.1, # symprec\r\n 5.0, # angle_tol\r\n)\r\n\r\nd = spglib.get_symmetry(data[0], symprec=data[1], angle_tolerance=data[2])\r\n\r\n```\r\n\r\n## Environment\r\n \r\n- Python version: Tested with 3.8, 3.9, 3.10, and 3.11\r\n- Spglib's version: 2.0.1\r\n\r\n\n", "image": {"image_id": "sha256:370afac41f58090a6e2e5b252836e1f5aedc8a31127910c403ce5782eb0c89a1", "pull_reference": "yutu0814/pyc-case-174-spglib@sha256:370afac41f58090a6e2e5b252836e1f5aedc8a31127910c403ce5782eb0c89a1"}, "cohort": "python50", "patch": "diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md\nindex 3e239e5..ce928e8 100644\n--- a/.github/ISSUE_TEMPLATE/bug_report.md\n+++ b/.github/ISSUE_TEMPLATE/bug_report.md\n@@ -24,9 +24,9 @@ If spglib returns different results by changing `symprec`, `angle_tolerance`, or\n \n \n ## Environment\n- \n-- Python version: \n-- Spglib's version: \n+\n+- Python version:\n+- Spglib's version:\n \n ## Additional context\n \ndiff --git a/doc/magnetic_symmetry_flags.md b/doc/magnetic_symmetry_flags.md\nindex 828024b..6b14f5d 100644\n--- a/doc/magnetic_symmetry_flags.md\n+++ b/doc/magnetic_symmetry_flags.md\n@@ -30,10 +30,10 @@\n - `tensor_rank=1`\n - `with_time_reversal=true`: {math}`1' \\circ \\mathbf{m} = -\\mathbf{m}`\n - `is_axial=true`: {math}`(\\mathbf{R}, \\mathbf{v}) \\circ \\mathbf{m} = (\\mathrm{det} \\mathbf{R}) \\mathbf{R} \\mathbf{m}`\n- - `is_axial=true`: {math}`(\\mathbf{R}, \\mathbf{v}) \\circ \\mathbf{m} = \\mathbf{R} \\mathbf{m}`\n+ - `is_axial=false`: {math}`(\\mathbf{R}, \\mathbf{v}) \\circ \\mathbf{m} = \\mathbf{R} \\mathbf{m}`\n - `with_time_reversal=false`: {math}`1' \\circ \\mathbf{m} = \\mathbf{m}`\n - `is_axial=true`: {math}`(\\mathbf{R}, \\mathbf{v}) \\circ \\mathbf{m} = (\\mathrm{det} \\mathbf{R}) \\mathbf{R} \\mathbf{m}`\n- - `is_axial=true`: {math}`(\\mathbf{R}, \\mathbf{v}) \\circ \\mathbf{m} = \\mathbf{R} \\mathbf{m}`\n+ - `is_axial=false`: {math}`(\\mathbf{R}, \\mathbf{v}) \\circ \\mathbf{m} = \\mathbf{R} \\mathbf{m}`\n \n \n \n

Methods inherited from class java.lang.Object

\n-clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait\n+clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait\n \n \n \n@@ -1122,7 +1116,7 @@ public float[] getValue_floatarray(java.lang.String str)\n \n \n \n-
    \n+
      \n
    • \n

      close

      \n
      public void close()
      \n@@ -1136,20 +1130,6 @@ public float[] getValue_floatarray(java.lang.String str)\n \n
    • \n
    \n-\n-\n-\n-
      \n-
    • \n-

      finalize

      \n-
      protected void finalize()
      \n-
      Attempts to close the interpreter if it hasn't been correctly closed.
      \n-
      \n-
      Overrides:
      \n-
      finalize in class java.lang.Object
      \n-
      \n-
    • \n-
    \n \n
\n \ndiff --git a/src/jep/ClassList.java b/src/jep/ClassList.java\nindex 53224db..b24ef9f 100755\n--- a/src/jep/ClassList.java\n+++ b/src/jep/ClassList.java\n@@ -155,6 +155,13 @@ public class ClassList implements ClassEnquirer {\n */\n private void loadClassList() throws JepException {\n String version = System.getProperty(\"java.version\");\n+\n+ /*\n+ * The thread's context ClassLoader is useful if resources have a\n+ * different ClassLoader than classes (e.g. tomcat), while the Jep.class\n+ * ClassLoader is useful if running inside an OSGi container as a Bundle\n+ * (e.g. eclipse).\n+ */\n ClassLoader[] classloadersToTry = new ClassLoader[] {\n Thread.currentThread().getContextClassLoader(),\n Jep.class.getClassLoader() };\ndiff --git a/src/jep/Jep.java b/src/jep/Jep.java\nindex 3bd72f8..816abcb 100644\n--- a/src/jep/Jep.java\n+++ b/src/jep/Jep.java\n@@ -55,10 +55,7 @@ import jep.python.PyObject;\n */\n public final class Jep implements Closeable {\n \n- private static final String THREAD_WARN = \"JEP WARNING: \"\n- + \"Unsafe reuse of thread \";\n-\n- private static final String REUSE_WARN = \" for another Python interpreter.\\nPlease close() the previous Jep instance to ensure stability.\";\n+ private static final String THREAD_WARN = \"JEP THREAD WARNING: \";\n \n private boolean closed = false;\n \n@@ -261,8 +258,12 @@ public final class Jep implements Closeable {\n * avoid this scenario.\n */\n Thread current = Thread.currentThread();\n- String warn = THREAD_WARN + current.getName() + REUSE_WARN;\n- System.err.println(warn);\n+ StringBuilder warning = new StringBuilder(THREAD_WARN)\n+ .append(\"Unsafe reuse of thread \")\n+ .append(current.getName())\n+ .append(\" for another Python sub-interpreter.\\n\")\n+ .append(\"Please close() the previous Jep instance to ensure stability.\");\n+ System.err.println(warning.toString());\n }\n \n if (cl == null)\n@@ -1085,10 +1086,27 @@ public final class Jep implements Closeable {\n if (this.closed)\n return;\n \n- /*\n- * close() seems to get away with not checking isValidThread() since it\n- * does very little JNI interaction, mostly just cpython code\n- */\n+ if (!Thread.currentThread().equals(thread)) {\n+ /*\n+ * TODO: Possibly throw a JepException if this is detected. This is\n+ * inherently unsafe, the thread state information inside Python can\n+ * get screwed up if a sub-interpreter is closed from a different\n+ * thread. Py_EndInterpreter is assuming that the interpreter is\n+ * being ended from the same thread. If close() is called from a\n+ * different thread, at best you will lose a little bit of memory,\n+ * at worst you will screw up Python's internal tracking of thread\n+ * state, which could lead to freezes or crashes.\n+ * \n+ * This remains a warning for the time being to provide time for\n+ * applications to be updated to avoid this scenario.\n+ */\n+ Thread current = Thread.currentThread();\n+ StringBuilder warning = new StringBuilder(THREAD_WARN)\n+ .append(\"Unsafe close() of Python sub-interpreter by thread \")\n+ .append(current.getName())\n+ .append(\".\\nPlease close() from the creating thread to ensure stability.\");\n+ System.err.println(warning);\n+ }\n \n // close all the PyObjects we created\n for (int i = 0; i < this.pythonObjects.size(); i++)\n@@ -1103,11 +1121,4 @@ public final class Jep implements Closeable {\n \n private native void close(long tstate);\n \n- /**\n- * Attempts to close the interpreter if it hasn't been correctly closed.\n- */\n- @Override\n- protected void finalize() {\n- this.close();\n- }\n }\ndiff --git a/src/jep/jep.c b/src/jep/jep.c\nindex 2480444..24aa1ee 100644\n--- a/src/jep/jep.c\n+++ b/src/jep/jep.c\n@@ -226,7 +226,7 @@ JNIEXPORT void JNICALL Java_jep_Jep_setClassLoader\n */\n JNIEXPORT void JNICALL Java_jep_Jep_close\n (JNIEnv *env, jobject obj, jlong tstate) {\n- pyembed_thread_close((intptr_t) tstate);\n+ pyembed_thread_close(env, (intptr_t) tstate);\n }\n \n \ndiff --git a/src/jep/pyembed.c b/src/jep/pyembed.c\nindex 71c1195..c62a35d 100644\n--- a/src/jep/pyembed.c\n+++ b/src/jep/pyembed.c\n@@ -309,10 +309,9 @@ intptr_t pyembed_thread_init(JNIEnv *env, jobject cl, jobject caller) {\n }\n \n \n-void pyembed_thread_close(intptr_t _jepThread) {\n+void pyembed_thread_close(JNIEnv *env, intptr_t _jepThread) {\n JepThread *jepThread;\n PyObject *tdict, *key;\n- JNIEnv *env;\n \n jepThread = (JepThread *) _jepThread;\n if(!jepThread) {\n@@ -320,12 +319,6 @@ void pyembed_thread_close(intptr_t _jepThread) {\n return;\n }\n \n- env = jepThread->env;\n- if(!env) {\n- printf(\"WARNING: thread_close, invalid env pointer.\\n\");\n- return;\n- }\n-\n PyEval_AcquireThread(jepThread->tstate);\n \n key = PyString_FromString(DICT_KEY);\ndiff --git a/src/jep/pyembed.h b/src/jep/pyembed.h\nindex f70d53a..878710f 100644\n--- a/src/jep/pyembed.h\n+++ b/src/jep/pyembed.h\n@@ -67,13 +67,13 @@ void pyembed_startup(void);\n void pyembed_shutdown(void);\n \n intptr_t pyembed_thread_init(JNIEnv*, jobject, jobject);\n-void pyembed_thread_close(intptr_t);\n+void pyembed_thread_close(JNIEnv*, intptr_t);\n \n void pyembed_close(void);\n void pyembed_run(JNIEnv*, intptr_t, char*);\n jobject pyembed_invoke_method(JNIEnv*, intptr_t,const char*, jobjectArray, jintArray);\n jobject pyembed_invoke(JNIEnv*, PyObject*, jobjectArray, jintArray);\n-void pyembed_eval(JNIEnv *, intptr_t, char*);\n+void pyembed_eval(JNIEnv*, intptr_t, char*);\n int pyembed_compile_string(JNIEnv*, intptr_t, char*);\n void pyembed_setloader(JNIEnv*, intptr_t, jobject);\n jobject pyembed_getvalue(JNIEnv*, intptr_t, char*);\n", "test_patch": "diff --git a/src/jep/test/CloseLifecycleSupport.java b/src/jep/test/CloseLifecycleSupport.java\nnew file mode 100644\n--- /dev/null\n+++ b/src/jep/test/CloseLifecycleSupport.java\n@@ -0,0 +1,52 @@\n+package jep.test;\n+\n+import jep.Jep;\n+import jep.JepException;\n+import java.nio.charset.StandardCharsets;\n+import java.nio.file.Files;\n+import java.nio.file.Path;\n+import java.util.Collections;\n+import java.util.Locale;\n+\n+final class CloseLifecycleSupport {\n+ private CloseLifecycleSupport() {}\n+\n+ static Path newMarker() throws Exception {\n+ Path marker = Files.createTempFile(\"jep-close-097-\", \".txt\");\n+ Files.delete(marker);\n+ return marker;\n+ }\n+\n+ static void installSentinel(Jep jep, Path marker) throws Exception {\n+ jep.set(\"_case097_marker\", marker.toAbsolutePath().toString());\n+ jep.eval(\"import os\");\n+ jep.eval(\"_case097_fd = os.open(_case097_marker, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 384)\");\n+ jep.eval(\"class _CloseSentinel(object):\\n\"\n+ + \" def __del__(self, writer=os.write, closer=os.close, descriptor=_case097_fd):\\n\"\n+ + \" writer(descriptor, b'CLOSED\\\\n')\\n\"\n+ + \" closer(descriptor)\\n\");\n+ jep.eval(\"_case097_sentinel = _CloseSentinel()\");\n+ jep.eval(\"_case097_value = 42\");\n+ Object value = jep.getValue(\"_case097_value\");\n+ if (!(value instanceof Number) || ((Number)value).intValue() != 42)\n+ throw new AssertionError(\"Interpreter initialization did not complete\");\n+ }\n+\n+ static void assertNativeClosed(Path marker) throws Exception {\n+ if (!Files.exists(marker)\n+ || !Files.readAllLines(marker, StandardCharsets.UTF_8).equals(Collections.singletonList(\"CLOSED\")))\n+ throw new AssertionError(\"Python sub-interpreter was not torn down exactly once\");\n+ }\n+\n+ static void assertUseRejected(Jep jep) throws Exception {\n+ try {\n+ jep.eval(\"_case097_value = 99\");\n+ } catch (JepException expected) {\n+ if (expected.getMessage() != null\n+ && expected.getMessage().toLowerCase(Locale.ROOT).contains(\"closed\"))\n+ return;\n+ throw new AssertionError(\"Use failed for a reason other than closed state\", expected);\n+ }\n+ throw new AssertionError(\"Closed interpreter remained usable\");\n+ }\n+}\ndiff --git a/src/jep/test/TestCloseLifecycle.java b/src/jep/test/TestCloseLifecycle.java\nnew file mode 100644\n--- /dev/null\n+++ b/src/jep/test/TestCloseLifecycle.java\n@@ -0,0 +1,36 @@\n+package jep.test;\n+\n+import jep.Jep;\n+import java.nio.file.Files;\n+import java.nio.file.Path;\n+\n+public final class TestCloseLifecycle {\n+ public static void main(String[] args) throws Exception {\n+ if (args.length != 1 || !(\"same-thread\".equals(args[0]) || \"double-close\".equals(args[0])))\n+ throw new AssertionError(\"Expected a close lifecycle mode\");\n+ Path marker = CloseLifecycleSupport.newMarker();\n+ try {\n+ Jep jep = new Jep(false, \".\");\n+ CloseLifecycleSupport.installSentinel(jep, marker);\n+ jep.close();\n+ CloseLifecycleSupport.assertNativeClosed(marker);\n+ CloseLifecycleSupport.assertUseRejected(jep);\n+ if (\"double-close\".equals(args[0])) {\n+ jep.close();\n+ CloseLifecycleSupport.assertNativeClosed(marker);\n+ }\n+ // A fresh interpreter must still work on the same owner thread.\n+ Jep next = new Jep(false, \".\");\n+ try {\n+ next.eval(\"value = 42\");\n+ if (((Number)next.getValue(\"value\")).intValue() != 42)\n+ throw new AssertionError(\"New interpreter did not work after close\");\n+ } finally {\n+ next.close();\n+ }\n+ } finally {\n+ Files.deleteIfExists(marker);\n+ }\n+ System.out.println(\"LIFECYCLE_OK:\" + args[0]);\n+ }\n+}\ndiff --git a/src/jep/test/TestCloseTerminatedThread.java b/src/jep/test/TestCloseTerminatedThread.java\nnew file mode 100644\n--- /dev/null\n+++ b/src/jep/test/TestCloseTerminatedThread.java\n@@ -0,0 +1,46 @@\n+package jep.test;\n+\n+import jep.Jep;\n+import java.nio.file.Files;\n+import java.nio.file.Path;\n+\n+public final class TestCloseTerminatedThread {\n+ public static void main(String[] args) throws Exception {\n+ for (int i = 0; i < 3; i++) {\n+ final Path marker = CloseLifecycleSupport.newMarker();\n+ final Jep[] holder = new Jep[1];\n+ final Throwable[] failure = new Throwable[1];\n+ Thread creator = new Thread(new Runnable() {\n+ @Override\n+ public void run() {\n+ try {\n+ holder[0] = new Jep(false, \".\");\n+ CloseLifecycleSupport.installSentinel(holder[0], marker);\n+ } catch (Throwable error) {\n+ failure[0] = error;\n+ }\n+ }\n+ }, \"jep-creator-\" + i);\n+ creator.setDaemon(true);\n+ try {\n+ creator.start();\n+ creator.join(15000);\n+ if (creator.isAlive())\n+ throw new AssertionError(\"Creator thread did not terminate within 15 seconds\");\n+ if (failure[0] != null)\n+ throw new AssertionError(\"Jep creation failed\", failure[0]);\n+ if (holder[0] == null)\n+ throw new AssertionError(\"Jep instance was not created\");\n+ System.out.println(\"CLOSING:\" + i);\n+ System.out.flush();\n+ holder[0].close();\n+ CloseLifecycleSupport.assertNativeClosed(marker);\n+ CloseLifecycleSupport.assertUseRejected(holder[0]);\n+ System.out.println(\"CLOSE_STEP:\" + i);\n+ } finally {\n+ Files.deleteIfExists(marker);\n+ }\n+ }\n+ System.out.println(\"CLOSE_OK\");\n+ }\n+}\ndiff --git a/tests/__init__.py b/tests/__init__.py\n--- a/tests/__init__.py\n+++ b/tests/__init__.py\n@@ -11,3 +11,6 @@\n from .test_dir import *\n from .test_numpy import *\n \n+\n+from .test_close_terminated_thread import *\n+from .test_close_lifecycle import *\ndiff --git a/tests/jep_pipe.py b/tests/jep_pipe.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/jep_pipe.py\n@@ -0,0 +1,44 @@\n+from __future__ import print_function\n+\n+import os\n+import subprocess\n+\n+\n+def run_child(argv, expected_markers=(), timeout_seconds=60, log_name=None):\n+ process = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n+ timed_out = False\n+ try:\n+ stdout, stderr = process.communicate(timeout=timeout_seconds)\n+ except subprocess.TimeoutExpired:\n+ timed_out = True\n+ process.kill()\n+ stdout, stderr = process.communicate()\n+ out = stdout.decode(\"utf-8\", \"replace\")\n+ err = stderr.decode(\"utf-8\", \"replace\")\n+ diagnostics = \"exit={0}\\nstdout:\\n{1}\\nstderr:\\n{2}\".format(process.returncode, out, err)\n+ directory = os.environ.get(\"BENCHMARK_CHILD_LOG_DIR\")\n+ if directory and log_name:\n+ if not os.path.isdir(directory):\n+ os.makedirs(directory)\n+ with open(os.path.join(directory, log_name + \".log\"), \"w\", encoding=\"utf-8\") as log:\n+ log.write(diagnostics)\n+ if timed_out:\n+ raise AssertionError(\"Child process timed out after {0}s\\n{1}\".format(timeout_seconds, diagnostics))\n+ if process.returncode != 0:\n+ raise AssertionError(\"Child JVM failed\\n\" + diagnostics)\n+ lines = out.splitlines()\n+ for marker in expected_markers:\n+ if lines.count(marker) != 1:\n+ raise AssertionError(\"Missing or duplicate completion marker: {0}\\n{1}\".format(marker, diagnostics))\n+ return stdout\n+\n+\n+def jep_pipe(argv):\n+ return run_child(argv)\n+\n+\n+def build_java_process_cmd(java_test_name, *args):\n+ from java.lang import System\n+ return [\"java\", \"-ea\", \"-cp\", System.getProperty(\"java.class.path\"),\n+ \"-Djava.library.path=\" + System.getProperty(\"java.library.path\"),\n+ \"-XX:ErrorFile=/results/hs_err-%p.log\", java_test_name] + list(args)\ndiff --git a/tests/test_close_lifecycle.py b/tests/test_close_lifecycle.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/test_close_lifecycle.py\n@@ -0,0 +1,12 @@\n+import unittest\n+from tests.jep_pipe import build_java_process_cmd, run_child\n+\n+\n+class TestCloseLifecycle(unittest.TestCase):\n+ def test_same_thread_close(self):\n+ run_child(build_java_process_cmd(\"jep.test.TestCloseLifecycle\", \"same-thread\"),\n+ [\"LIFECYCLE_OK:same-thread\"], log_name=\"same-thread\")\n+\n+ def test_double_close(self):\n+ run_child(build_java_process_cmd(\"jep.test.TestCloseLifecycle\", \"double-close\"),\n+ [\"LIFECYCLE_OK:double-close\"], log_name=\"double-close\")\ndiff --git a/tests/test_close_terminated_thread.py b/tests/test_close_terminated_thread.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/test_close_terminated_thread.py\n@@ -0,0 +1,9 @@\n+import unittest\n+from tests.jep_pipe import build_java_process_cmd, run_child\n+\n+\n+class TestCloseTerminatedThread(unittest.TestCase):\n+ def test_close_terminated_thread(self):\n+ run_child(build_java_process_cmd(\"jep.test.TestCloseTerminatedThread\"),\n+ [\"CLOSE_STEP:0\", \"CLOSE_STEP:1\", \"CLOSE_STEP:2\", \"CLOSE_OK\"],\n+ log_name=\"terminated-thread\")\n", "FAIL_TO_PASS": ["test_close_terminated_thread.TestCloseTerminatedThread.test_close_terminated_thread"], "PASS_TO_PASS": ["test_array.TestArray.test_slice", "test_array.TestArray.test_read_file", "test_call.TestTypes.test_string", "test_call.TestTypes.test_enum", "test_call.TestTypes.test_long", "test_call.TestTypes.test_double", "test_call.TestTypes.test_float", "test_call.TestTypes.test_intobj", "test_call.TestTypes.test_getobj", "test_call.TestTypes.test_getstring_array", "test_call.TestTypes.test_string_string_array", "test_call.TestTypes.test_int_array", "test_call.TestTypes.test_bool_array", "test_call.TestTypes.test_short_array", "test_call.TestTypes.test_float_array", "test_call.TestTypes.test_object_array", "test_call.TestTypes.test_equals", "test_compare.TestCompare.test_int_compare", "test_compare.TestCompare.test_date_compare", "test_dir.TestDir.test_dir_list", "test_exceptions.TestExceptions.test_number_format", "test_exceptions.TestExceptions.test_io_exception", "test_exceptions.TestExceptions.test_null_pointer_exception", "test_exceptions.TestExceptions.test_import_error", "test_exceptions.TestExceptions.test_index_error", "test_exceptions.TestExceptions.test_io_error", "test_exceptions.TestExceptions.test_type_error", "test_exceptions.TestExceptions.test_value_err", "test_exceptions.TestExceptions.test_arithmetic_error", "test_import.TestImport.test_java_sql", "test_import.TestImport.test_not_found", "test_import.TestImport.test_restricted_classloader", "test_import.TestImport.test_without_restricted_classloader", "test_import.TestImport.test_class_import", "test_jdbc.TestJdbc.test_java_sql", "test_jdbc.TestJdbc.test_dbapi_primitives", "test_jdbc.TestJdbc.test_datetime", "test_jdbc.TestJdbc.test_batch", "test_lists.TestLists.test_sequence", "test_lists.TestLists.test_len", "test_lists.TestLists.test_loop", "test_lists.TestLists.test_contains", "test_lists.TestLists.test_getitem", "test_lists.TestLists.test_getslice", "test_lists.TestLists.test_setitem", "test_lists.TestLists.test_setslice", "test_lists.TestLists.test_add", "test_lists.TestLists.test_addequals", "test_lists.TestLists.test_multiply", "test_lists.TestLists.test_multiplyequals", "test_maps.TestMaps.test_map", "test_numpy.TestNumpy.testSetGet", "test_numpy.TestNumpy.testArgReturn", "test_numpy.TestNumpy.testMultiDimensional", "test_numpy.TestNumpy.testArrayParams", "test_regressions.TestRegressions.test_out", "test_regressions.TestRegressions.test_byte_value", "test_types.TestFields.test_string", "test_types.TestFields.test_boolean_field", "test_types.TestFields.test_short_field", "test_types.TestFields.test_int_field", "test_types.TestFields.test_long_field", "test_types.TestFields.test_double_field", "test_types.TestFields.test_float_field", "test_types.TestFields.test_byte_field", "test_types.TestFields.test_char_field", "test_types.TestFields.test_class_field", "test_types.TestFields.test_static_string", "test_types.TestFields.test_static_boolean_field", "test_types.TestFields.test_static_short_field", "test_types.TestFields.test_static_int_field", "test_types.TestFields.test_static_long_field", "test_types.TestFields.test_static_double_field", "test_types.TestFields.test_static_float_field", "test_types.TestFields.test_static_byte_field", "test_types.TestFields.test_static_char_field", "test_types.TestFields.test_static_class_field", "test_types.TestFields.test_equals", "test_close_lifecycle.TestCloseLifecycle.test_same_thread_close", "test_close_lifecycle.TestCloseLifecycle.test_double_close"]} +{"instance_id": "clb-javac-099", "repo": "ninia/jep", "base_commit": "b1ab138dd6d492c7547e24d0b117aeafb112613d", "problem_statement": "Java setter method invocation fails in an OSGi environment after a bundle redeploy\nHi, I'm testing jep in an OSGi environment.\nIn a bundle of mine I use Jep to invoke a python function that returns at the end of computation a simple java bean tree.\nThe Java bean tree is instantiated from mirrorred Python objects that are used during the computation and which get converted recursively before returning from Jep. \n\nThis is how I dynamically instantiate a Java bean from the corresponding Python object:\n\n```\ndef load_java_obj(self, j_class_name):\n package_and_class = j_class_name.rsplit(\".\", 1)\n class_name = package_and_class[1]\n java_module = importlib.import_module(package_and_class[0])\n java_type = getattr(java_module, class_name)\n return java_type()\n```\n\nand here is how I call the setter method:\n\n```\nouter_obj = load_java_obj(\"org.example.MyBean\")\nnested_obj = load_java_obj(\"org.example.MyNestedBean\")\n# populate nested_obj properties\nsetFunct = getattr(outer_obj, \"setter_name\")\nsetFunct(nested_obj)\n```\n\nI am experiencing the following issue: the above code starts to fail if I redeploy the bundle declaring the Java classes. In the code when the redeploy takes place I create a new Jep instance and I pass the correct class loader, but after the redeploy any call to the setter methods that accept a java bean from Python leads to the following error message: Incorrect object type at 1\n\nI am pretty sure it's not me passing in the wrong class loader to the Jep instance, in fact if I change the setters to accept a java.lang.Object and cast to the correct type within the setter body, the assignement succeeds, meaning that the objects created by Python (Jep) are instances of the classes defined by the appropriate class loader, otherwise I would experience a ClassCastException.\n\nThe error message is raised by the native C code of Jep which makes an assignement compatibility check for method arguments before calling a java method from python. \n\n```\n // check object itself is assignable to that type.\n if(!(*env)->IsAssignableFrom(env,\n ((PyJobject_Object *) param)->clazz,\n paramType)) {\n PyErr_Format(PyExc_TypeError,\n \"Incorrect object type at %i.\",\n pos + 1);\n return ret;\n }\n```\n\nThis is why, changing the setter method parameter from a specific type to java.lang.Object makes the invocation successfull in spite of the bundle redeploy.\n\nIn practice, it appears that after a bundle redeploy the Jep C code is not correctly recognizing the java bean class anymore, as if the Java class had been defined by a different class loader. But as already written, I am passing in the correct class loader to the new Jep instance. My worry is that Jep is somehow leaking class loaders and re-using the previously passed class loader which is of course invalid after the bundle redeploy. \n\nAs a work around to this problem, instead of calling the Java setter on the bean from Python/Jep, I am now using a more generic helper method in Java which I inwoke from Jep/Python passing in the target object, the setter name, and the setter argument. In this way, by using reflection in Java for invoking the setter, I am bypassing the assignment compatibility check mentioned before.\nAlternatively, I could simply comment out such check from the C code and rebuild.\n\nAny idea or recommendation? Any test I can do to help you diagnose the problem?\n\nThanks in advance.\nMatteo.\n\n", "image": {"image_id": "sha256:502cb2beb42e3c90413016c2d2ab33dc53fec30912f04ef8eadd47caeae629ee", "pull_reference": "yutu0814/javac-case-099-jep@sha256:502cb2beb42e3c90413016c2d2ab33dc53fec30912f04ef8eadd47caeae629ee"}, "cohort": "java_author11", "patch": "diff --git a/src/jep/pyembed.c b/src/jep/pyembed.c\r\nindex fd7cdfe..2b84efd 100644\r\n--- a/src/jep/pyembed.c\r\n+++ b/src/jep/pyembed.c\r\n@@ -278,12 +278,13 @@ intptr_t pyembed_thread_init(JNIEnv *env, jobject cl, jobject caller) {\r\n Py_INCREF(globals);\r\n \r\n // init static module\r\n- jepThread->modjep = initjep();\r\n- jepThread->globals = globals;\r\n- jepThread->env = env;\r\n- jepThread->classloader = (*env)->NewGlobalRef(env, cl);\r\n- jepThread->caller = (*env)->NewGlobalRef(env, caller);\r\n- jepThread->printStack = 0;\r\n+ jepThread->modjep = initjep();\r\n+ jepThread->globals = globals;\r\n+ jepThread->env = env;\r\n+ jepThread->classloader = (*env)->NewGlobalRef(env, cl);\r\n+ jepThread->caller = (*env)->NewGlobalRef(env, caller);\r\n+ jepThread->printStack = 0;\r\n+ jepThread->fqnToPyJmethods = NULL;\r\n \r\n if((tdict = PyThreadState_GetDict()) != NULL) {\r\n PyObject *key, *t;\r\n@@ -333,6 +334,10 @@ void pyembed_thread_close(intptr_t _jepThread) {\r\n if(jepThread->globals) {\r\n Py_DECREF(jepThread->globals);\r\n }\r\n+ if(jepThread->fqnToPyJmethods) {\r\n+ PyDict_Clear(jepThread->fqnToPyJmethods);\r\n+ Py_DECREF(jepThread->fqnToPyJmethods); \r\n+ }\r\n if(jepThread->modjep) {\r\n PyObject *moddict = PyModule_GetDict(jepThread->modjep);\r\n /*\r\ndiff --git a/src/jep/pyembed.h b/src/jep/pyembed.h\r\nindex e559f8a..f70d53a 100644\r\n--- a/src/jep/pyembed.h\r\n+++ b/src/jep/pyembed.h\r\n@@ -57,6 +57,8 @@ struct __JepThread {\r\n jobject classloader;\r\n jobject caller; /* Jep instance that called us. */\r\n int printStack;\r\n+ PyObject *fqnToPyJmethods; /* a dictionary of fully qualified Java \r\n+ classnames to PyJmethods on the class */\r\n };\r\n typedef struct __JepThread JepThread;\r\n \r\ndiff --git a/src/jep/pyjobject.c b/src/jep/pyjobject.c\r\nindex e4f3f9f..1496fb7 100755\r\n--- a/src/jep/pyjobject.c\r\n+++ b/src/jep/pyjobject.c\r\n@@ -80,8 +80,6 @@ static jmethodID objectHashCode = 0;\r\n static jmethodID classGetMethods = 0;\r\n static jmethodID classGetFields = 0;\r\n static jmethodID classGetName = 0;\r\n-static PyObject *classnamePyJMethodsDict = NULL;\r\n-\r\n \r\n /*\r\n * MSVC requires tp_base to be set at runtime instead of in\r\n@@ -251,6 +249,7 @@ static int pyjobject_init(JNIEnv *env, PyJobject_Object *pyjob) {\r\n PyObject *pyClassName = NULL;\r\n PyObject *pyAttrName = NULL;\r\n \r\n+ JepThread *jepThread;\r\n PyObject *cachedMethodList = NULL;\r\n \r\n (*env)->PushLocalFrame(env, 20);\r\n@@ -325,11 +324,17 @@ static int pyjobject_init(JNIEnv *env, PyJobject_Object *pyjob) {\r\n * synchronized and multiple threads will not alter the dictionary at the\r\n * same time.\r\n */\r\n- if(classnamePyJMethodsDict == NULL) {\r\n- classnamePyJMethodsDict = PyDict_New();\r\n+ jepThread = pyembed_get_jepthread();\r\n+ if(jepThread == NULL) {\r\n+ goto EXIT_ERROR;\r\n+ }\r\n+ if(jepThread->fqnToPyJmethods == NULL) {\r\n+ PyObject *methodCache = PyDict_New();\r\n+ Py_INCREF(methodCache);\r\n+ jepThread->fqnToPyJmethods = methodCache;\r\n }\r\n \r\n- cachedMethodList = PyDict_GetItem(classnamePyJMethodsDict, pyClassName);\r\n+ cachedMethodList = PyDict_GetItem(jepThread->fqnToPyJmethods, pyClassName);\r\n if(cachedMethodList == NULL) {\r\n PyObject *pyjMethodList = NULL;\r\n pyjMethodList = PyList_New(0);\r\n@@ -375,7 +380,7 @@ static int pyjobject_init(JNIEnv *env, PyJobject_Object *pyjob) {\r\n Py_DECREF(pymethod);\r\n (*env)->DeleteLocalRef(env, rmethod);\r\n } // end of looping over available methods\r\n- PyDict_SetItem(classnamePyJMethodsDict, pyClassName, pyjMethodList);\r\n+ PyDict_SetItem(jepThread->fqnToPyJmethods, pyClassName, pyjMethodList);\r\n cachedMethodList = pyjMethodList;\r\n (*env)->DeleteLocalRef(env, methodArray);\r\n } // end of setting up cache for this Java Class\r\n", "test_patch": "diff --git a/src/jep/test/TestClassLoaderMethodCache.java b/src/jep/test/TestClassLoaderMethodCache.java\nnew file mode 100644\nindex 0000000..0000000\n--- /dev/null\n+++ b/src/jep/test/TestClassLoaderMethodCache.java\n@@ -0,0 +1,99 @@\n+package jep.test;\n+\n+import java.io.File;\n+import java.io.FileWriter;\n+import java.net.URL;\n+import java.net.URLClassLoader;\n+\n+import javax.tools.JavaCompiler;\n+import javax.tools.ToolProvider;\n+\n+import jep.Jep;\n+\n+/** Regression test for per-ClassLoader Java method caches. */\n+public class TestClassLoaderMethodCache {\n+\n+ public static void main(String[] args) throws Exception {\n+ File root = makeTempDirectory();\n+ try {\n+ File first = compileVariant(root, \"first\");\n+ File second = compileVariant(root, \"second\");\n+ URLClassLoader firstLoader = new URLClassLoader(\n+ new URL[] { first.toURI().toURL() },\n+ TestClassLoaderMethodCache.class.getClassLoader());\n+ URLClassLoader secondLoader = new URLClassLoader(\n+ new URL[] { second.toURI().toURL() },\n+ TestClassLoaderMethodCache.class.getClassLoader());\n+ try {\n+ runVariant(firstLoader, \"first\", \"first\");\n+ runVariant(secondLoader, \"second\", \"second\");\n+ } finally {\n+ firstLoader.close();\n+ secondLoader.close();\n+ }\n+ System.out.println(\"CLASSLOADER_CACHE_OK\");\n+ } finally {\n+ deleteRecursively(root);\n+ }\n+ }\n+\n+ private static void runVariant(ClassLoader loader, String method,\n+ String expected) throws Exception {\n+ Jep jep = new Jep(false, \".\", loader);\n+ try {\n+ jep.eval(\"from jep import forName\");\n+ jep.eval(\"Sample = forName('cacheprobe.Sample')\");\n+ jep.eval(\"result = Sample().\" + method + \"()\");\n+ Object value = jep.getValue(\"result\");\n+ if (!expected.equals(value)) {\n+ throw new AssertionError(\"unexpected result: \" + value);\n+ }\n+ } finally {\n+ jep.close();\n+ }\n+ }\n+\n+ private static File compileVariant(File root, String method)\n+ throws Exception {\n+ File sourceRoot = new File(root, method + \"/src/cacheprobe\");\n+ File outputRoot = new File(root, method + \"/classes\");\n+ if (!sourceRoot.mkdirs() || !outputRoot.mkdirs()) {\n+ throw new IllegalStateException(\"could not create test directories\");\n+ }\n+ File source = new File(sourceRoot, \"Sample.java\");\n+ FileWriter writer = new FileWriter(source);\n+ try {\n+ writer.write(\"package cacheprobe; public class Sample { \"\n+ + \"public String \" + method + \"() { return \\\"\" + method\n+ + \"\\\"; } }\");\n+ } finally {\n+ writer.close();\n+ }\n+ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();\n+ if (compiler == null || compiler.run(null, null, null, \"-d\",\n+ outputRoot.getAbsolutePath(), source.getAbsolutePath()) != 0) {\n+ throw new AssertionError(\"could not compile cache probe\");\n+ }\n+ return outputRoot;\n+ }\n+\n+ private static File makeTempDirectory() throws Exception {\n+ File file = File.createTempFile(\"jep-cache\", \"dir\");\n+ if (!file.delete() || !file.mkdirs()) {\n+ throw new IllegalStateException(\"could not create temp directory\");\n+ }\n+ return file;\n+ }\n+\n+ private static void deleteRecursively(File file) {\n+ if (file.isDirectory()) {\n+ File[] children = file.listFiles();\n+ if (children != null) {\n+ for (File child : children) {\n+ deleteRecursively(child);\n+ }\n+ }\n+ }\n+ file.delete();\n+ }\n+}\ndiff --git a/tests/__init__.py b/tests/__init__.py\nindex eea0c94..0000000 100644\n--- a/tests/__init__.py\n+++ b/tests/__init__.py\n@@ -11,3 +11,4 @@ from .test_compare import *\n from .test_dir import *\n from .test_numpy import *\n \n+from .test_classloader_method_cache import *\ndiff --git a/tests/jep_pipe.py b/tests/jep_pipe.py\nnew file mode 100644\nindex 0000000..0000000\n--- /dev/null\n+++ b/tests/jep_pipe.py\n@@ -0,0 +1,31 @@\n+from __future__ import print_function\n+\n+import subprocess\n+from subprocess import PIPE\n+\n+\n+def jep_pipe(argv):\n+ process = subprocess.Popen(argv, stdout=PIPE, stderr=PIPE)\n+ stdout, stderr = process.communicate()\n+ if process.returncode != 0:\n+ raise AssertionError(\n+ \"child process failed with exit code {0}\\nstdout:\\n{1}\\nstderr:\\n{2}\".format(\n+ process.returncode,\n+ stdout.decode(\"utf-8\", \"replace\"),\n+ stderr.decode(\"utf-8\", \"replace\")\n+ )\n+ )\n+ return stdout\n+\n+\n+def build_java_process_cmd(java_test_name):\n+ from java.lang import System\n+\n+ classpath = System.getProperty(\"java.class.path\")\n+ library_path = \"-Djava.library.path=\" + System.getProperty(\n+ \"java.library.path\"\n+ )\n+\n+ return [\n+ \"java\", \"-ea\", \"-cp\", classpath, library_path, java_test_name\n+ ]\ndiff --git a/tests/test_classloader_method_cache.py b/tests/test_classloader_method_cache.py\nnew file mode 100644\nindex 0000000..0000000\n--- /dev/null\n+++ b/tests/test_classloader_method_cache.py\n@@ -0,0 +1,15 @@\n+from __future__ import print_function\n+\n+import unittest\n+\n+from tests.jep_pipe import build_java_process_cmd, jep_pipe\n+\n+\n+class TestClassLoaderMethodCache(unittest.TestCase):\n+\n+ def test_classloader_method_cache(self):\n+ stdout = jep_pipe(\n+ build_java_process_cmd(\"jep.test.TestClassLoaderMethodCache\")\n+ )\n+ if b\"CLASSLOADER_CACHE_OK\" not in stdout:\n+ raise AssertionError(\"classloader cache marker missing\")\n", "FAIL_TO_PASS": ["test_classloader_method_cache.TestClassLoaderMethodCache.test_classloader_method_cache"], "PASS_TO_PASS": ["test_array.TestArray.test_slice", "test_array.TestArray.test_read_file", "test_call.TestTypes.test_string", "test_call.TestTypes.test_enum", "test_call.TestTypes.test_long", "test_call.TestTypes.test_double", "test_call.TestTypes.test_float", "test_call.TestTypes.test_intobj", "test_call.TestTypes.test_getobj", "test_call.TestTypes.test_getstring_array", "test_call.TestTypes.test_string_string_array", "test_call.TestTypes.test_int_array", "test_call.TestTypes.test_bool_array", "test_call.TestTypes.test_short_array", "test_call.TestTypes.test_float_array", "test_call.TestTypes.test_object_array", "test_call.TestTypes.test_equals", "test_compare.TestCompare.test_int_compare", "test_compare.TestCompare.test_date_compare", "test_dir.TestDir.test_dir_list", "test_exceptions.TestExceptions.test_number_format", "test_exceptions.TestExceptions.test_io_exception", "test_exceptions.TestExceptions.test_null_pointer_exception", "test_exceptions.TestExceptions.test_import_error", "test_exceptions.TestExceptions.test_index_error", "test_exceptions.TestExceptions.test_io_error", "test_exceptions.TestExceptions.test_type_error", "test_exceptions.TestExceptions.test_value_err", "test_exceptions.TestExceptions.test_arithmetic_error", "test_import.TestImport.test_java_sql", "test_import.TestImport.test_not_found", "test_import.TestImport.test_restricted_classloader", "test_import.TestImport.test_without_restricted_classloader", "test_import.TestImport.test_class_import", "test_jdbc.TestJdbc.test_java_sql", "test_jdbc.TestJdbc.test_dbapi_primitives", "test_jdbc.TestJdbc.test_datetime", "test_jdbc.TestJdbc.test_batch", "test_lists.TestLists.test_sequence", "test_lists.TestLists.test_len", "test_lists.TestLists.test_loop", "test_lists.TestLists.test_contains", "test_lists.TestLists.test_getitem", "test_lists.TestLists.test_getslice", "test_lists.TestLists.test_setitem", "test_lists.TestLists.test_setslice", "test_lists.TestLists.test_add", "test_lists.TestLists.test_addequals", "test_lists.TestLists.test_multiply", "test_lists.TestLists.test_multiplyequals", "test_maps.TestMaps.test_map", "test_numpy.TestNumpy.testSetGet", "test_numpy.TestNumpy.testArgReturn", "test_numpy.TestNumpy.testMultiDimensional", "test_numpy.TestNumpy.testArrayParams", "test_regressions.TestRegressions.test_out", "test_regressions.TestRegressions.test_byte_value", "test_types.TestFields.test_string", "test_types.TestFields.test_boolean_field", "test_types.TestFields.test_short_field", "test_types.TestFields.test_int_field", "test_types.TestFields.test_long_field", "test_types.TestFields.test_double_field", "test_types.TestFields.test_float_field", "test_types.TestFields.test_byte_field", "test_types.TestFields.test_char_field", "test_types.TestFields.test_class_field", "test_types.TestFields.test_static_string", "test_types.TestFields.test_static_boolean_field", "test_types.TestFields.test_static_short_field", "test_types.TestFields.test_static_int_field", "test_types.TestFields.test_static_long_field", "test_types.TestFields.test_static_double_field", "test_types.TestFields.test_static_float_field", "test_types.TestFields.test_static_byte_field", "test_types.TestFields.test_static_char_field", "test_types.TestFields.test_static_class_field", "test_types.TestFields.test_equals"]} +{"instance_id": "clb-javac-163", "repo": "kohlschutter/junixsocket", "base_commit": "90716d6008c5c9cfa8a061f3d23531acaea29777", "problem_statement": "\"java: symbol lookup error: libjunixsocket-native-2.2.0.so: undefined symbol: stat\" on machines with older glibc (< 2.14)\nThis is a continuation of the previously closed issue https://github.com/kohlschutter/junixsocket/issues/69\r\n\r\nI was able to reproduce this same error on my local machine. using version 2.2.0. I am using OpenJDK 1.8, Linux 4.9.217, X86_64.\r\n\r\nI haven't tried to use the newest version 2.3.1 yet. But I was able to narrow down the exact line of code that caused this error to occur in 2.2.0. It happened for me in AFUNIXServerSocket.bind(). Hope this helps.\n", "image": {"image_id": "sha256:c8b7c236569b9eb461c66197356b0b109088ce31fd0f0057f5441a3afb99e497", "pull_reference": "yutu0814/javac-case-163-junixsocket@sha256:c8b7c236569b9eb461c66197356b0b109088ce31fd0f0057f5441a3afb99e497"}, "cohort": "java_author11", "patch": "diff --git a/junixsocket-native/src/main/c/org_newsclub_net_unix_NativeUnixSocket.c b/junixsocket-native/src/main/c/org_newsclub_net_unix_NativeUnixSocket.c\nindex fc32a4e2398d3853810029fefaf15ecf2b748d63..06b6a54795ab41b4490e03605baee1959d8f3bda 100644\n--- a/junixsocket-native/src/main/c/org_newsclub_net_unix_NativeUnixSocket.c\n+++ b/junixsocket-native/src/main/c/org_newsclub_net_unix_NativeUnixSocket.c\n@@ -185,6 +185,16 @@ typedef unsigned long socklen_t; /* 64-bits */\n # define socket_errno errno\n #endif\n \n+#if __GLIBC__\n+# if __CROSSCLANG_NODEPS__\n+// nothing to do\n+# else\n+// This allows us to link against older glibc versions\n+# define memcpy memmove\n+# define stat(...) __xstat(1, __VA_ARGS__)\n+# endif\n+#endif\n+\n typedef enum {\n kExceptionSocketException = 0,\n kExceptionSocketTimeoutException,\n@@ -392,6 +402,47 @@ static void setLongFieldValue(JNIEnv *env, jobject instance, char *fieldName,\n }\n #endif\n \n+/**\n+ * Initializes a sockaddr_un given a byte[] address, returning the socklen,\n+ * or 0 if an error occurred.\n+ */\n+static socklen_t initSu(JNIEnv * env, struct sockaddr_un *su, jbyteArray addr) {\n+ const int maxLen = sizeof(su->sun_path);\n+\n+ socklen_t addrLen = (socklen_t)(*env)->GetArrayLength(env, addr);\n+ if((int)addrLen <= 0 || addrLen >= maxLen) {\n+ org_newsclub_net_unix_NativeUnixSocket_throwException(env,\n+ kExceptionSocketException,\n+ \"Socket address length out of range\");\n+ return 0;\n+ }\n+\n+ const char* socketFile = (char*)(void*)(*env)->GetByteArrayElements(env,\n+ addr, NULL);\n+ if(socketFile == NULL) {\n+ return 0; // OOME\n+ }\n+\n+ su->sun_family = AF_UNIX;\n+ memset(su->sun_path, 0, maxLen);\n+ memcpy(su->sun_path, socketFile, addrLen);\n+\n+ (*env)->ReleaseByteArrayElements(env, addr, (jbyte*)(void*)socketFile, 0);\n+ socketFile = NULL;\n+\n+#ifdef junixsocket_have_sun_len\n+ su->sun_len = (unsigned char)(sizeof(*su) - sizeof(su->sun_path) + addrLen);\n+#endif\n+\n+ socklen_t suLength = (socklen_t)(addrLen + sizeof(su->sun_family)\n+#ifdef junixsocket_have_sun_len\n+ + sizeof(su->sun_len)\n+#endif\n+ );\n+\n+ return suLength;\n+}\n+\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: init\n@@ -657,41 +708,12 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_accept(\n jobject fd, jlong expectedInode, int timeout)\n {\n struct sockaddr_un su;\n- const int maxLen = sizeof(su.sun_path);\n-\n- socklen_t addrLen = (socklen_t)(*env)->GetArrayLength(env, addr);\n- if((int)addrLen <= 0 || addrLen >= maxLen) {\n- org_newsclub_net_unix_NativeUnixSocket_throwException(env,\n- kExceptionSocketException,\n- \"Socket address length out of range\");\n- return;\n- }\n-\n- const char* socketFile = (char*)(void*)(*env)->GetByteArrayElements(env,\n- addr, NULL);\n- if(socketFile == NULL) {\n- return; // OOME\n- }\n+ socklen_t suLength = initSu(env, &su, addr);\n+ if(suLength == 0) return;\n \n int serverHandle = org_newsclub_net_unix_NativeUnixSocket_getFD(env,\n fdServer);\n \n- su.sun_family = AF_UNIX;\n- memset(su.sun_path, 0, maxLen);\n- memcpy(su.sun_path, socketFile, addrLen);\n- (*env)->ReleaseByteArrayElements(env, addr, (jbyte*)(void*)socketFile, 0);\n- socketFile = NULL;\n-\n-#ifdef junixsocket_have_sun_len\n- su.sun_len = (unsigned char)(sizeof(su) - sizeof(su.sun_path) + addrLen);\n-#endif\n-\n- socklen_t suLength = (socklen_t)(addrLen + sizeof(su.sun_family)\n-#ifdef junixsocket_have_sun_len\n- + (unsigned char)sizeof(su.sun_len)\n-#endif\n- );\n-\n if(expectedInode > 0) {\n struct stat fdStat;\n \n@@ -746,39 +768,8 @@ JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind(\n JNIEnv * env, jclass clazz, jbyteArray addr, jobject fd, jint options)\n {\n struct sockaddr_un su;\n- const int maxLen = sizeof(su.sun_path);\n-\n- socklen_t addrLen = (socklen_t)(*env)->GetArrayLength(env, addr);\n- if((int)addrLen <= 0 || addrLen >= maxLen) {\n- org_newsclub_net_unix_NativeUnixSocket_throwException(env,\n- kExceptionSocketException,\n- \"Socket address length out of range\");\n- return -1;\n- }\n-\n- const char* socketFile = (char*)(void*)(*env)->GetByteArrayElements(env,\n- addr, NULL);\n-\n- if(socketFile == NULL) {\n- return -1; // OOME\n- }\n-\n- su.sun_family = AF_UNIX;\n- memset(su.sun_path, 0, maxLen);\n- memcpy(su.sun_path, socketFile, addrLen);\n-\n- (*env)->ReleaseByteArrayElements(env, addr, (jbyte*)(void*)socketFile, 0);\n- socketFile = NULL;\n-\n-#ifdef junixsocket_have_sun_len\n- su.sun_len = (unsigned char)(sizeof(su) - sizeof(su.sun_path) + addrLen);\n-#endif\n-\n- socklen_t suLength = (socklen_t)(addrLen + sizeof(su.sun_family)\n-#ifdef junixsocket_have_sun_len\n- + sizeof(su.sun_len)\n-#endif\n- );\n+ socklen_t suLength = initSu(env, &su, addr);\n+ if(suLength == 0) return -1;\n \n #if defined(_WIN32)\n int serverHandle = socket(PF_UNIX, SOCK_STREAM, 0);\n@@ -1071,21 +1062,8 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_connect(\n jlong expectedInode)\n {\n struct sockaddr_un su;\n- const int maxLen = sizeof(su.sun_path);\n-\n- socklen_t addrLen = (socklen_t)(*env)->GetArrayLength(env, addr);\n- if((int)addrLen <= 0 || addrLen >= maxLen) {\n- org_newsclub_net_unix_NativeUnixSocket_throwException(env,\n- kExceptionSocketException,\n- \"Socket address length out of range\");\n- return;\n- }\n-\n- const char* socketFile = (char*)(void*)(*env)->GetByteArrayElements(env,\n- addr, NULL);\n- if(socketFile == NULL) {\n- return; // OOME\n- }\n+ socklen_t suLength = initSu(env, &su, addr);\n+ if(suLength == 0) return;\n \n SOCKET socketHandle = socket(PF_UNIX, SOCK_STREAM, 0);\n if(socketHandle == INVALID_SOCKET) {\n@@ -1094,23 +1072,6 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_connect(\n return;\n }\n \n- su.sun_family = AF_UNIX;\n- memset(su.sun_path, 0, maxLen);\n- memcpy(su.sun_path, socketFile, addrLen);\n-\n- (*env)->ReleaseByteArrayElements(env, addr, (jbyte*)(void*)socketFile, 0);\n- socketFile = NULL;\n-\n-#ifdef junixsocket_have_sun_len\n- su.sun_len = (unsigned char)(sizeof(su) - sizeof(su.sun_path) + addrLen);\n-#endif\n-\n- socklen_t suLength = (socklen_t)(addrLen + sizeof(su.sun_family)\n-#ifdef junixsocket_have_sun_len\n- + sizeof(su.sun_len)\n-#endif\n- );\n-\n if(expectedInode > 0) {\n struct stat fdStat;\n \ndiff --git a/junixsocket-native/src/main/nar/aol.properties b/junixsocket-native/src/main/nar/aol.properties\nindex 606d7f5806e01812cb479c600bbdc5237d7e0767..b8feea0f672a41c49c3a22580e09ced7f3382c8c 100644\n--- a/junixsocket-native/src/main/nar/aol.properties\n+++ b/junixsocket-native/src/main/nar/aol.properties\n@@ -29,7 +29,7 @@ amd64.Linux.clang.linker.name=clang\n amd64.Linux.clang.linker.options=-Xcrossclang-with-and-without-lc -target ${junixsocket.native.llvm.target}\n amd64.Linux.clang.c.compiler=clang\n amd64.Linux.clang.c.defines=_GNU_SOURCE\n-amd64.Linux.clang.c.options=${junixsocket.native.clang.c.options} -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n+amd64.Linux.clang.c.options=${junixsocket.native.clang.c.options} -Xcrossclang-with-and-without-lc -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n amd64.Linux.clang.c.includes=${junixsocket.native.default.c.includes}\n amd64.Linux.clang.c.excludes=\n amd64.Linux.clang.java.include=\n@@ -51,7 +51,7 @@ arm.Linux.clang.linker.name=clang\n arm.Linux.clang.linker.options=-Xcrossclang-with-and-without-lc -target ${junixsocket.native.llvm.target}\n arm.Linux.clang.c.compiler=clang\n arm.Linux.clang.c.defines=_GNU_SOURCE\n-arm.Linux.clang.c.options=${junixsocket.native.clang.c.options} -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n+arm.Linux.clang.c.options=${junixsocket.native.clang.c.options} -Xcrossclang-with-and-without-lc -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n arm.Linux.clang.c.includes=${junixsocket.native.default.c.includes}\n arm.Linux.clang.c.excludes=\n arm.Linux.clang.java.include=\n@@ -73,7 +73,7 @@ aarch64.Linux.clang.linker.name=clang\n aarch64.Linux.clang.linker.options=-Xcrossclang-with-and-without-lc -target ${junixsocket.native.llvm.target}\n aarch64.Linux.clang.c.compiler=clang\n aarch64.Linux.clang.c.defines=_GNU_SOURCE\n-aarch64.Linux.clang.c.options=${junixsocket.native.clang.c.options} -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n+aarch64.Linux.clang.c.options=${junixsocket.native.clang.c.options} -Xcrossclang-with-and-without-lc -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n aarch64.Linux.clang.c.includes=${junixsocket.native.default.c.includes}\n aarch64.Linux.clang.c.excludes=\n aarch64.Linux.clang.java.include=\n@@ -95,7 +95,7 @@ ppc64le.Linux.clang.linker.name=clang\n ppc64le.Linux.clang.linker.options=-Xcrossclang-with-and-without-lc -target ${junixsocket.native.llvm.target}\n ppc64le.Linux.clang.c.compiler=clang\n ppc64le.Linux.clang.c.defines=_GNU_SOURCE\n-ppc64le.Linux.clang.c.options=${junixsocket.native.clang.c.options} -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n+ppc64le.Linux.clang.c.options=${junixsocket.native.clang.c.options} -Xcrossclang-with-and-without-lc -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n ppc64le.Linux.clang.c.includes=${junixsocket.native.default.c.includes}\n ppc64le.Linux.clang.c.excludes=\n ppc64le.Linux.clang.java.include=\n@@ -117,7 +117,7 @@ s390x.Linux.clang.linker.name=clang\n s390x.Linux.clang.linker.options=-Xcrossclang-with-and-without-lc -target ${junixsocket.native.llvm.target}\n s390x.Linux.clang.c.compiler=clang\n s390x.Linux.clang.c.defines=_GNU_SOURCE\n-s390x.Linux.clang.c.options=${junixsocket.native.clang.c.options} -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n+s390x.Linux.clang.c.options=${junixsocket.native.clang.c.options} -Xcrossclang-with-and-without-lc -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n s390x.Linux.clang.c.includes=${junixsocket.native.default.c.includes}\n s390x.Linux.clang.c.excludes=\n s390x.Linux.clang.java.include=\n@@ -139,7 +139,7 @@ riscv64.Linux.clang.linker.name=clang\n riscv64.Linux.clang.linker.options=-Xcrossclang-with-and-without-lc -target ${junixsocket.native.llvm.target} -Xcrossclang-llvm-name llvm@9\n riscv64.Linux.clang.c.compiler=clang\n riscv64.Linux.clang.c.defines=_GNU_SOURCE\n-riscv64.Linux.clang.c.options=-march=rv64ifd -mabi=lp64d ${junixsocket.native.clang.c.options} -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n+riscv64.Linux.clang.c.options=-march=rv64ifd -mabi=lp64d ${junixsocket.native.clang.c.options} -Xcrossclang-with-and-without-lc -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n riscv64.Linux.clang.c.includes=${junixsocket.native.default.c.includes}\n riscv64.Linux.clang.c.excludes=\n riscv64.Linux.clang.java.include=\n@@ -207,7 +207,7 @@ amd64.FreeBSD.clang.linker.name=clang\n amd64.FreeBSD.clang.linker.options=-Xcrossclang-with-and-without-lc -target ${junixsocket.native.llvm.target}\n amd64.FreeBSD.clang.c.compiler=clang\n amd64.FreeBSD.clang.c.defines=_GNU_SOURCE\n-amd64.FreeBSD.clang.c.options=${junixsocket.native.clang.c.options} -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n+amd64.FreeBSD.clang.c.options=${junixsocket.native.clang.c.options} -Xcrossclang-with-and-without-lc -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target}\n amd64.FreeBSD.clang.c.includes=${junixsocket.native.default.c.includes}\n amd64.FreeBSD.clang.c.excludes=\n amd64.FreeBSD.clang.java.include=\n", "test_patch": "diff --git a/junixsocket-common/src/test/java/org/newsclub/net/unix/Issue81GlibcProbe.java b/junixsocket-common/src/test/java/org/newsclub/net/unix/Issue81GlibcProbe.java\nnew file mode 100644\n--- /dev/null\n+++ b/junixsocket-common/src/test/java/org/newsclub/net/unix/Issue81GlibcProbe.java\n@@ -0,0 +1,57 @@\n+package org.newsclub.net.unix;\n+\n+import java.io.DataInputStream;\n+import java.io.DataOutputStream;\n+import java.io.File;\n+import org.newsclub.net.unix.AFUNIXServerSocket;\n+import org.newsclub.net.unix.AFUNIXSocket;\n+import org.newsclub.net.unix.AFUNIXSocketAddress;\n+\n+/** Calls the real library loader and native bind; no simulated native failures. */\n+public final class Issue81GlibcProbe {\n+ public static void main(String[] args) throws Exception {\n+ System.out.println(\"JAVA_STARTED=\" + System.getProperty(\"java.version\"));\n+ if (args.length == 2 && \"--library\".equals(args[0])) {\n+ System.load(args[1]);\n+ System.setProperty(\"org.newsclub.net.unix.library.override\", args[1]);\n+ } else if (args.length != 0) {\n+ throw new IllegalArgumentException(\"Expected no arguments or --library PATH\");\n+ }\n+ if (!AFUNIXSocket.isSupported()) {\n+ throw new AssertionError(\"AF_UNIX unavailable\");\n+ }\n+ System.out.println(\"LOADER_COMPLETED=\" + AFUNIXSocket.getLoadedLibrary());\n+ for (int iteration = 0; iteration < 3; iteration++) {\n+ File file = File.createTempFile(\"issue81-\", \".sock\");\n+ if (!file.delete()) {\n+ throw new AssertionError(\"Could not prepare socket pathname\");\n+ }\n+ AFUNIXSocketAddress address = new AFUNIXSocketAddress(file);\n+ System.out.println(\"BEFORE_BIND=\" + iteration);\n+ try (AFUNIXServerSocket server = AFUNIXServerSocket.bindOn(address)) {\n+ System.out.println(\"AFTER_BIND=\" + iteration);\n+ server.setSoTimeout(3000);\n+ try (AFUNIXSocket client = AFUNIXSocket.connectTo(address);\n+ AFUNIXSocket accepted = server.accept()) {\n+ client.setSoTimeout(3000);\n+ accepted.setSoTimeout(3000);\n+ int value = 0x1638100 + iteration;\n+ new DataOutputStream(client.getOutputStream()).writeInt(value);\n+ if (new DataInputStream(accepted.getInputStream()).readInt() != value) {\n+ throw new AssertionError(\"Request corrupted\");\n+ }\n+ new DataOutputStream(accepted.getOutputStream()).writeInt(~value);\n+ if (new DataInputStream(client.getInputStream()).readInt() != ~value) {\n+ throw new AssertionError(\"Response corrupted\");\n+ }\n+ }\n+ } finally {\n+ if (file.exists() && !file.delete()) {\n+ throw new AssertionError(\"Socket cleanup failed\");\n+ }\n+ }\n+ System.out.println(\"ROUNDTRIP_OK=\" + iteration);\n+ }\n+ System.out.println(\"ISSUE81_PROBE_OK\");\n+ }\n+}\n", "FAIL_TO_PASS": ["org.newsclub.net.unix.Issue81CompatibilityTest.testAutomaticFallbackOldGlibc"], "PASS_TO_PASS": ["org.newsclub.net.unix.Issue81CompatibilityTest.testModernGlibcRoundTrip", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testPort", "org.newsclub.net.unix.AcceptTimeoutTest.testCatchTimeout", "org.newsclub.net.unix.AcceptTimeoutTest.testTimeoutAfterDelay", "org.newsclub.net.unix.BufferOverflowTest.readOutOfBounds", "org.newsclub.net.unix.BufferOverflowTest.readUpTo", "org.newsclub.net.unix.BufferOverflowTest.writeOverflow", "org.newsclub.net.unix.CancelAcceptTest.issue6test1", "org.newsclub.net.unix.EndOfFileJavaTest.bidirectionalSanity", "org.newsclub.net.unix.EndOfFileJavaTest.clientReadEof", "org.newsclub.net.unix.EndOfFileJavaTest.clientWriteToSocketClosedByClient", "org.newsclub.net.unix.EndOfFileJavaTest.clientWriteToSocketClosedByServer", "org.newsclub.net.unix.EndOfFileJavaTest.serverReadEof", "org.newsclub.net.unix.EndOfFileJavaTest.serverWriteToSocketClosedByClient", "org.newsclub.net.unix.EndOfFileJavaTest.serverWriteToSocketClosedByServer", "org.newsclub.net.unix.EndOfFileTest.bidirectionalSanity", "org.newsclub.net.unix.EndOfFileTest.clientReadEof", "org.newsclub.net.unix.EndOfFileTest.clientWriteToSocketClosedByClient", "org.newsclub.net.unix.EndOfFileTest.clientWriteToSocketClosedByServer", "org.newsclub.net.unix.EndOfFileTest.serverReadEof", "org.newsclub.net.unix.EndOfFileTest.serverWriteToSocketClosedByClient", "org.newsclub.net.unix.EndOfFileTest.serverWriteToSocketClosedByServer", "org.newsclub.net.unix.FileDescriptorsTest.testAncillaryReceiveBufferTooSmall", "org.newsclub.net.unix.FileDescriptorsTest.testBadFileDescriptor", "org.newsclub.net.unix.FileDescriptorsTest.testFileInputStream", "org.newsclub.net.unix.FileDescriptorsTest.testFileInputStreamPartiallyConsumed", "org.newsclub.net.unix.FileDescriptorsTest.testNoAncillaryReceiveBuffer", "org.newsclub.net.unix.FileDescriptorsTest.testSendRecvFileDescriptors", "org.newsclub.net.unix.PeerCredentialsTest.testSameProcess", "org.newsclub.net.unix.ServerSocketCloseTest.testUnblockAcceptsWithSoTimeout", "org.newsclub.net.unix.ServerSocketCloseTest.testUnblockAcceptsWithoutSoTimeout", "org.newsclub.net.unix.SoTimeoutTest.issue14Fail", "org.newsclub.net.unix.SoTimeoutTest.issue14Pass", "org.newsclub.net.unix.TcpNoDelayTest.testDefaultImpl", "org.newsclub.net.unix.TcpNoDelayTest.testStrictImpl"]} +{"instance_id": "clb-javac-170", "repo": "kohlschutter/junixsocket", "base_commit": "71a134bce58a22fb17a7a14f00799196c0c71a60", "problem_statement": "Junix socket 2.7.2 crashes on unix hosts with /tmp mounted as non-exec\n**Describe the bug**\r\nWe have an application that uses junix-socket 2.7.2 and we are seeing that on SE Linux enabled system with /tmp mounted with non-exec permission, we see the junix socket is crashing. I am attacheding the self test results. We don't see that problem if /tmp is mounted with exec permission. I have done the self test for both 2.7.2 and 2.8.0 and both seem to fail.\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n1. Have an SE Linux enabled RHEL host and /tmp mounted as nonexec\r\n2. Run the junix socket app \r\n3. Observe that it crashes\r\n\r\n**Expected behavior**\r\nIt shouldn't crash\r\n\r\n**Output/Screenshots**\r\nSuppressed: java.lang.UnsatisfiedLinkError: /tmp/libtmp3251380450989097213libjunixsocket-native-2.7.2.so: /tmp/libtmp3251380450989097213libjunixsocket-native-2.7.2.so: failed to map segment from shared object\r\n at java.base/java.lang.ClassLoader$NativeLibrary.load0(Native Method)\r\n at java.base/java.lang.ClassLoader$NativeLibrary.load(ClassLoader.java:2450)\r\n at java.base/java.lang.ClassLoader$NativeLibrary.loadLibrary(ClassLoader.java:2506)\r\n at java.base/java.lang.ClassLoader.loadLibrary0(ClassLoader.java:2705)\r\n at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2635)\r\n at java.base/java.lang.Runtime.load0(Runtime.java:768)\r\n at java.base/java.lang.System.load(System.java:1850)\r\n at org.newsclub.net.unix.NativeLibraryLoader$ClasspathLibraryCandidate.load(NativeLibraryLoader.java:195)\r\n\r\n\r\n**Please make sure to test the problem still occurs on the latest version of junixsocket**\r\nPlease add the output of the selftest from the latest version available, for example:\r\n\r\n`java -jar junixsocket-selftest-2.7.0-jar-with-dependencies.jar`\r\n\r\nThe selftest is available from the [Release section](https://github.com/kohlschutter/junixsocket/releases) on GitHub.\r\n\r\nAll minor version updates (e.g., 2.4.x -> 2.5.x) are supposed to be backwards compatible.\r\nIf you find that this isn't the case, please mention it in your report. Thank you!\r\n\r\n**Notes**\r\nAdd any other context about the problem here. Please link/attach any source code that is useful to diagnose the issue.\r\n[selftest_result_2.8.0_failed.txt](https://github.com/kohlschutter/junixsocket/files/12762652/selftest_result_2.8.0_failed.txt)\r\n[self_test_result_2.7.2_failed.txt](https://github.com/kohlschutter/junixsocket/files/12762655/self_test_result_2.7.2_failed.txt)\r\n\n", "image": {"image_id": "sha256:1a70b55b3d05b7f18257b238ba0ab246f055b03023eb9483d1cafc58703fbde3", "pull_reference": "yutu0814/javac-case-170-junixsocket@sha256:1a70b55b3d05b7f18257b238ba0ab246f055b03023eb9483d1cafc58703fbde3"}, "cohort": "java_author11", "patch": "diff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeLibraryLoader.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeLibraryLoader.java\nindex 1e2b46f..faca7d1 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeLibraryLoader.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeLibraryLoader.java\n@@ -28,7 +28,6 @@ import java.net.URL;\n import java.util.ArrayList;\n import java.util.Collections;\n import java.util.List;\n-import java.util.Locale;\n import java.util.Objects;\n import java.util.Properties;\n import java.util.concurrent.atomic.AtomicBoolean;\n@@ -194,11 +193,6 @@ final class NativeLibraryLoader implements Closeable {\n try {\n System.load(libFile.getAbsolutePath());\n } catch (UnsatisfiedLinkError e) {\n- String message = e.getMessage().toLowerCase(Locale.getDefault());\n- if (!message.contains(\"perm\")) {\n- throw e;\n- }\n-\n // Operation not permitted; permission denied; EPERM...\n // -> tmp directory may be mounted with \"noexec\", try loading from user.home, user.dir\n \n", "test_patch": "diff --git a/benchmark-tests/org/newsclub/net/unix/NoexecProbe.java b/benchmark-tests/org/newsclub/net/unix/NoexecProbe.java\nnew file mode 100644\n--- /dev/null\n+++ b/benchmark-tests/org/newsclub/net/unix/NoexecProbe.java\n@@ -0,0 +1,82 @@\n+package org.newsclub.net.unix;\n+\n+import java.io.DataInputStream;\n+import java.io.DataOutputStream;\n+import java.io.File;\n+import java.nio.charset.StandardCharsets;\n+import java.nio.file.Files;\n+import java.nio.file.Path;\n+import java.nio.file.Paths;\n+import java.util.LinkedHashSet;\n+import java.util.Set;\n+\n+/** Uses the unchanged automatic loader and real AF_UNIX sockets. */\n+public final class NoexecProbe {\n+ public static void main(String[] args) throws Exception {\n+ System.out.println(\"JAVA=\" + System.getProperty(\"java.version\"));\n+ System.out.println(\"LOADER_ORIGIN=\" + NativeLibraryLoader.class.getProtectionDomain()\n+ .getCodeSource().getLocation());\n+ for (String directory : new String[] {System.getProperty(\"java.io.tmpdir\"), System.getProperty(\"user.home\"), System.getProperty(\"user.dir\")}) {\n+ Path test = Files.createTempFile(Paths.get(directory), \"writable-\", \".txt\");\n+ try {\n+ Files.write(test, new byte[] {1, 2, 3});\n+ if (Files.readAllBytes(test).length != 3) {\n+ throw new AssertionError(\"File I/O control failed\");\n+ }\n+ } finally {\n+ Files.delete(test);\n+ }\n+ System.out.println(\"WRITABLE=\" + directory);\n+ }\n+ for (String line : Files.readAllLines(Paths.get(\"/proc/self/mountinfo\"), StandardCharsets.UTF_8)) {\n+ String[] columns = line.split(\" \");\n+ if (columns.length > 5 && (columns[4].equals(\"/case-noexec\") || columns[4].equals(\"/case-exec\"))) {\n+ System.out.println(\"MOUNT=\" + columns[4] + \" \" + columns[5]);\n+ }\n+ }\n+ System.out.println(\"BEFORE_SOCKET\");\n+ for (int iteration = 0; iteration < 3; iteration++) {\n+ File file = File.createTempFile(\"case170-\", \".sock\", new File(System.getProperty(\"user.dir\")));\n+ if (!file.delete()) {\n+ throw new AssertionError(\"Could not prepare socket pathname\");\n+ }\n+ AFUNIXSocketAddress address = AFUNIXSocketAddress.of(file);\n+ try (AFUNIXServerSocket server = AFUNIXServerSocket.bindOn(address)) {\n+ server.setSoTimeout(3000);\n+ try (AFUNIXSocket client = AFUNIXSocket.connectTo(address);\n+ AFUNIXSocket accepted = server.accept()) {\n+ client.setSoTimeout(3000);\n+ accepted.setSoTimeout(3000);\n+ int value = 0x17014000 + iteration;\n+ new DataOutputStream(client.getOutputStream()).writeInt(value);\n+ if (new DataInputStream(accepted.getInputStream()).readInt() != value) {\n+ throw new AssertionError(\"Request payload mismatch\");\n+ }\n+ new DataOutputStream(accepted.getOutputStream()).writeInt(~value);\n+ if (new DataInputStream(client.getInputStream()).readInt() != ~value) {\n+ throw new AssertionError(\"Response payload mismatch\");\n+ }\n+ }\n+ } finally {\n+ if (file.exists() && !file.delete()) {\n+ throw new AssertionError(\"Socket cleanup failed\");\n+ }\n+ }\n+ System.out.println(\"ROUNDTRIP_OK=\" + iteration);\n+ }\n+ Set mapped = new LinkedHashSet();\n+ for (String line : Files.readAllLines(Paths.get(\"/proc/self/maps\"), StandardCharsets.UTF_8)) {\n+ if (line.contains(\"junixsocket-native\") && line.contains(\".so\")) {\n+ String[] columns = line.split(\"\\\\s+\", 6);\n+ mapped.add(columns[5]);\n+ }\n+ }\n+ for (String path : mapped) {\n+ System.out.println(\"NATIVE_MAPPING=\" + path);\n+ }\n+ if (mapped.isEmpty()) {\n+ throw new AssertionError(\"No real native library mapping found\");\n+ }\n+ System.out.println(\"NOEXEC_PROBE_OK\");\n+ }\n+}\n", "FAIL_TO_PASS": ["benchmark.noexec.noexec_home_fallback", "benchmark.noexec.noexec_cwd_fallback"], "PASS_TO_PASS": ["benchmark.noexec.exec_loading", "benchmark.noexec.all_noexec_rejected", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testAbstractNamespace()", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testCraftDeserialization()", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testFileScheme()", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testHttpUnix()", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testParseURIandBack()", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testSchemesAvailable()", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testSerialize()", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testSocatString()", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testURITemplate()", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testURITemplateWithPortNumber()", "org.newsclub.net.unix.AFUNIXSocketAddressTest.testUnixScheme()", "org.newsclub.net.unix.domain.ReadWriteTest.testReceiveDataByteForByteSendByteForByte()", "org.newsclub.net.unix.domain.ReadWriteTest.testReceiveDataByteForByteSendWithByteArray()", "org.newsclub.net.unix.domain.ReadWriteTest.testReceiveWithByteArraySendByteForByte()", "org.newsclub.net.unix.domain.ReadWriteTest.testReceiveWithByteArraySendWithByteArray()", "org.newsclub.net.unix.domain.SocketAddressTest.testAbstractNamespace()", "org.newsclub.net.unix.domain.SocketAddressTest.testByteConstructor()", "org.newsclub.net.unix.domain.SocketAddressTest.testEmptyAddress()", "org.newsclub.net.unix.domain.SocketAddressTest.testInetAddress()", "org.newsclub.net.unix.domain.SocketAddressTest.testLargePort()", "org.newsclub.net.unix.domain.SocketAddressTest.testLegacyConstructor()", "org.newsclub.net.unix.domain.SocketAddressTest.testPath()", "org.newsclub.net.unix.domain.SocketAddressTest.testPort()", "org.newsclub.net.unix.domain.SocketFactoryTest.testFactoryArg()", "org.newsclub.net.unix.domain.SocketFactoryTest.testSystemProperty()", "org.newsclub.net.unix.domain.SocketFactoryTest.testURISchemeCeateSocketThenConnect()", "org.newsclub.net.unix.domain.SocketFactoryTest.testURISchemeCeateSocketWithHostnameValidCases()", "org.newsclub.net.unix.domain.SocketFactoryTest.testURISchemeCeateSocketWithIllegalArguments()", "org.newsclub.net.unix.domain.SocketFactoryTest.testURISchemeCeateSocketWithInvalidHostname()", "org.newsclub.net.unix.domain.SocketTest.testBindBadArguments()", "org.newsclub.net.unix.domain.SocketTest.testCloseable()", "org.newsclub.net.unix.domain.SocketTest.testConnectBadArguments()", "org.newsclub.net.unix.domain.SocketTest.testLoadedLibrary()", "org.newsclub.net.unix.domain.SocketTest.testMain()", "org.newsclub.net.unix.domain.SocketTest.testReceivedFileDescriptorsUnconnected()", "org.newsclub.net.unix.domain.SocketTest.testSupported()", "org.newsclub.net.unix.domain.SocketTest.testSupports()", "org.newsclub.net.unix.domain.SocketTest.testUnconnectedSocket()", "org.newsclub.net.unix.domain.SocketTest.testVersion()"]} +{"instance_id": "clb-javac-069", "repo": "LWJGL/lwjgl3", "base_commit": "427e278dc2402aca025cacd58a80eb4eaa8c4832", "problem_statement": "ALUtil.getStringList is returning incorrect values with OpenJDK 10.0.1\n### Environment\r\n\r\n* LWJGL version: 3.2.0 build 12\r\n* Platform: `Windows`\r\n* Module: `openal`\r\n\r\n### Description\r\n\r\nALUtil.getStringList is returning incorrect values on OpenJDK 10.0.1 64 bit.\r\n\r\n\t\tSystem.out.println(ALUtil.getStringList(0, ALC11.ALC_ALL_DEVICES_SPECIFIER));\r\n\t\tSystem.out.println(ALC11.alcGetString(0, ALC11.ALC_ALL_DEVICES_SPECIFIER));\r\n\r\nprints \r\n\r\n![untitled](https://user-images.githubusercontent.com/8334578/44628819-9be9d380-a915-11e8-9555-97cb8daf8d3f.png)\r\n\r\nIt works with Java 1.8.0_74 64 bit:\r\n\r\n[OpenAL Soft on Speakers (Realtek High Definition Audio)]\r\nOpenAL Soft on Speakers (Realtek High Definition Audio)\r\n\r\nI also tried with ALC_CAPTURE_DEVICE_SPECIFIER with similar results:\r\n\r\n1.8:\r\n[OpenAL Soft on Microphone (Realtek High Definition Audio), OpenAL Soft on Microphone (DroidCam Virtual Audio)]\r\nOpenAL Soft on Microphone (Realtek High Definition Audio)\r\n\r\n10.0.1:\r\n\r\n![untitled](https://user-images.githubusercontent.com/8334578/44628876-5548a900-a916-11e8-8b83-f7222faf1f82.png)\r\n\r\nThe bad characters are different every time.\r\n\r\nEdit:\r\n\r\nIt works correctly when I move getStringList to my own class and add two buffer.position() calls:\r\n\r\n\r\n public static List getStringList(long deviceHandle, int token) {\r\n long __result = nalcGetString(deviceHandle, token);\r\n if (__result == 0) {\r\n return null;\r\n }\r\n\r\n ByteBuffer buffer = MemoryUtil.memByteBuffer(__result, Integer.MAX_VALUE);\r\n\r\n List strings = new ArrayList<>();\r\n\r\n int offset = 0;\r\n while (true) {\r\n if (buffer.get() == 0) {\r\n int limit = buffer.position() - 1;\r\n if (limit == offset) { // Previous char was also a \\0 == end of list.\r\n break;\r\n }\r\n buffer.position(0);\r\n strings.add(MemoryUtil.memUTF8(buffer, limit - offset, offset));\r\n buffer.position(limit + 1);\r\n offset = buffer.position();\r\n }\r\n }\r\n\r\n return strings;\r\n }\r\n\r\nIt looks like the java9 MemoryTextDecoding here (https://github.com/LWJGL/lwjgl3/blob/14a47551f2ec55361c31654c89c0c5c006cb3997/modules/lwjgl/core/src/main/java9/org/lwjgl/system/MemoryTextDecoding.java) uses the buffer's position while the java 8 version does not.\r\n\n", "image": {"image_id": "sha256:28841dd5e2c53ab5b4e5d54a6426005f3011e90ec2fd1fb70db3a5e897eecbda", "pull_reference": "yutu0814/javac-case-069-lwjgl3@sha256:28841dd5e2c53ab5b4e5d54a6426005f3011e90ec2fd1fb70db3a5e897eecbda", "historical_image_id": "sha256:8f2c37403299227261579735576bc5a395b8bffe826f44a9ba15f1a8fa3fa41f"}, "cohort": "java_upstream11", "patch": "diff --git a/modules/lwjgl/core/src/main/java/org/lwjgl/system/MemoryTextDecoding.java b/modules/lwjgl/core/src/main/java/org/lwjgl/system/MemoryTextDecoding.java\nindex 24c556e5f..b318cc164 100644\n--- a/modules/lwjgl/core/src/main/java/org/lwjgl/system/MemoryTextDecoding.java\n+++ b/modules/lwjgl/core/src/main/java/org/lwjgl/system/MemoryTextDecoding.java\n@@ -123,7 +123,7 @@ final class MemoryTextDecoding {\n return \"\";\n }\n \n- return memCharBuffer(memAddress(buffer) + offset, length).toString();\n+ return memCharBuffer(memAddress0(buffer) + offset, length).toString();\n }\n \n }\n\\ No newline at end of file\ndiff --git a/modules/lwjgl/core/src/main/java9/org/lwjgl/system/MemoryTextDecoding.java b/modules/lwjgl/core/src/main/java9/org/lwjgl/system/MemoryTextDecoding.java\nindex 3b2ed3d40..eb9baea3a 100644\n--- a/modules/lwjgl/core/src/main/java9/org/lwjgl/system/MemoryTextDecoding.java\n+++ b/modules/lwjgl/core/src/main/java9/org/lwjgl/system/MemoryTextDecoding.java\n@@ -28,7 +28,7 @@ final class MemoryTextDecoding {\n }\n \n byte[] bytes = new byte[length];\n- memByteBuffer(memAddress(buffer) + offset, length).get(bytes);\n+ memByteBuffer(memAddress0(buffer) + offset, length).get(bytes);\n return new String(bytes, StandardCharsets.ISO_8859_1);\n }\n \n@@ -41,7 +41,7 @@ final class MemoryTextDecoding {\n }\n \n byte[] bytes = new byte[length];\n- memByteBuffer(memAddress(buffer) + offset, length).get(bytes);\n+ memByteBuffer(memAddress0(buffer) + offset, length).get(bytes);\n return new String(bytes, StandardCharsets.UTF_8);\n }\n \n@@ -53,7 +53,7 @@ final class MemoryTextDecoding {\n return \"\";\n }\n \n- return memCharBuffer(memAddress(buffer) + offset, length).toString();\n+ return memCharBuffer(memAddress0(buffer) + offset, length).toString();\n }\n \n }\n\\ No newline at end of file\n", "test_patch": "diff --git a/modules/lwjgl/core/src/test/java/org/lwjgl/system/MemoryUtilTest.java b/modules/lwjgl/core/src/test/java/org/lwjgl/system/MemoryUtilTest.java\nindex b187f5489..36f8a1673 100644\n--- a/modules/lwjgl/core/src/test/java/org/lwjgl/system/MemoryUtilTest.java\n+++ b/modules/lwjgl/core/src/test/java/org/lwjgl/system/MemoryUtilTest.java\n@@ -11,6 +11,7 @@ import org.testng.annotations.*;\n import java.nio.*;\n import java.nio.charset.*;\n import java.util.*;\n+import java.util.function.*;\n \n import static org.lwjgl.system.Checks.*;\n import static org.lwjgl.system.MemoryUtil.*;\n@@ -234,6 +235,54 @@ public class MemoryUtilTest {\n }\n }\n \n+ public void testTextDecoding() {\n+ testTextDecoding(MemoryUtil::memASCII, MemoryUtil::memASCII, MemoryUtil::memASCII, 1);\n+ testTextDecoding(MemoryUtil::memUTF8, MemoryUtil::memUTF8, MemoryUtil::memUTF8, 1);\n+ testTextDecoding(MemoryUtil::memUTF16, MemoryUtil::memUTF16, MemoryUtil::memUTF16, 2);\n+ }\n+\n+ @FunctionalInterface\n+ private interface TextEncoder {\n+ ByteBuffer apply(String text, boolean nullTerminated);\n+ }\n+\n+ @FunctionalInterface\n+ private interface TextDecoder {\n+ String apply(ByteBuffer buffer, int length, int offset);\n+ }\n+\n+ private static void testTextDecoding(TextEncoder encoder, Function decoder, TextDecoder decoderUnsafe, int bpc) {\n+ ByteBuffer encoded = encoder.apply(\"one two three\", false);\n+\n+ assertEquals(encoded.position(), 0);\n+ assertEquals(encoded.remaining(), 13 * bpc);\n+\n+ encoded.limit(13 * bpc);\n+ encoded.position(0 * bpc);\n+ assertEquals(decoder.apply(encoded), \"one two three\");\n+\n+ encoded.limit(3 * bpc);\n+ encoded.position(0 * bpc);\n+ assertEquals(decoder.apply(encoded), \"one\");\n+\n+ encoded.limit(7 * bpc);\n+ encoded.position(4 * bpc);\n+ assertEquals(decoder.apply(encoded), \"two\");\n+\n+ encoded.limit(13 * bpc);\n+ encoded.position(8 * bpc);\n+ assertEquals(decoder.apply(encoded), \"three\");\n+\n+ encoded.clear();\n+\n+ assertEquals(decoderUnsafe.apply(encoded, 13, 0 * bpc), \"one two three\");\n+ assertEquals(decoderUnsafe.apply(encoded, 3, 0 * bpc), \"one\");\n+ assertEquals(decoderUnsafe.apply(encoded, 3, 4 * bpc), \"two\");\n+ assertEquals(decoderUnsafe.apply(encoded, 5, 8 * bpc), \"three\");\n+\n+ memFree(encoded);\n+ }\n+\n public void testUTF8() {\n // null-termination\n ByteBuffer bytes = memUTF8(\"\");\n", "FAIL_TO_PASS": ["org.lwjgl.system.MemoryUtilTest.testTextDecoding"], "PASS_TO_PASS": ["org.lwjgl.system.MemoryUtilTest.testUTF8"]} +{"instance_id": "clb-javac-092", "repo": "ninia/jep", "base_commit": "d14567567ac1281e978790b9170c981113de282f", "problem_statement": "Unable to execute compiled script with JEP and Python 3.5.3\nI have implemented a compile step to convert .py to .pyc files prior to execution. Each script is cached and if it is present it is used instead of the interpreted .py.\r\n\r\nEverything works great when JEP is asked to execute the .pyc when on Python 2.7.13. However when I change environment and use Python 3.5.3 I get the following error...\r\n\r\n**Bad code object in .pyc file**\r\n\r\n_Note_ I am aware of pyc magic numbers - the cached pyc files are cleaned and compiled with 3.5.3. Looking at pyembed.c I am getting past the magic number validation at line 1328 and seeing the error at the validation step at line 1334.\r\n\r\nHere's the bit I can't understand. If I execute the compiled .pyc file using python3 directly it runs just fine.\r\n\r\nI have attached a simple example that highlights the problem, the zip contains the following...\r\n\r\njepHello.py - native script\r\njepHello-2.7.13.pyc - compiled with 2.7.13 - runs from JEP on Python 2.7.13 and native python2\r\njepHello-3.5.3.pyc - compiled with 3.5.3 - fails with JEP on Python 3.5.3 but runs with native python3\r\n\r\n[jepHello.zip](https://github.com/mrj0/jep/files/980875/jepHello.zip)\r\n\r\nPlease let me know if there's something I'm missing or if this is a bug and needs more investigation I'd be very happy to help. JEP is an awesome piece of work!\r\n\r\nIncidentally I am using JEP as the caching compiler too using the following ...\r\n\r\njep.eval(\"import py_compile\");\r\nString py=\"py_compile.compile(file='\"+scriptFile.getAbsolutePath()+\"', cfile='\"+compiledFile.getAbsolutePath()+\"' )\";\r\njep.eval(py);\r\njep.eval(null); // flush\r\n\r\nThis works flawlessly and the JEP generated .pyc runs fine on any version of native python.\r\n\r\nThanks for any help you can offer... \r\n\r\nPeter\n", "image": {"image_id": "sha256:da9c9293093a89f2cfd0e2d584077080c640f0c002cef0589c64e28ac6b550d4", "pull_reference": "yutu0814/javac-case-092-jep@sha256:da9c9293093a89f2cfd0e2d584077080c640f0c002cef0589c64e28ac6b550d4"}, "cohort": "java_upstream11", "patch": "diff --git a/src/jep/pyembed.c b/src/jep/pyembed.c\nindex a9f7299..e3a503f 100644\n--- a/src/jep/pyembed.c\n+++ b/src/jep/pyembed.c\n@@ -1330,6 +1330,11 @@ static void pyembed_run_pyc(JepThread *jepThread,\n return;\n }\n (void) PyMarshal_ReadLongFromFile(fp);\n+#if PY_MAJOR_VERSION >= 3\n+ // Python 3.3 added an extra long containing the size of the source.\n+ // https://github.com/python/cpython/commit/5136ac0ca21a05691978df8d0650f902c8ca3463\n+ (void) PyMarshal_ReadLongFromFile(fp);\n+#endif\n v = (PyObject *) (intptr_t) PyMarshal_ReadLastObjectFromFile(fp);\n if (v == NULL || !PyCode_Check(v)) {\n Py_XDECREF(v);\n", "test_patch": "diff --git a/src/jep/test/TestCompiledScript.java b/src/jep/test/TestCompiledScript.java\nnew file mode 100644\nindex 0000000..6f297f8\n--- /dev/null\n+++ b/src/jep/test/TestCompiledScript.java\n@@ -0,0 +1,34 @@\n+package jep.test;\n+\n+import java.lang.IllegalStateException;\n+import java.lang.Boolean;\n+\n+import jep.Jep;\n+import jep.JepConfig;\n+import jep.JepException;\n+\n+/**\n+ * Tests that a compiled script can be loaded by Jep.runscript()\n+ * \n+ * Created: May 2017\n+ * \n+ * @author Ben Steffensmeier\n+ */\n+public class TestCompiledScript {\n+\n+ public static void main(String[] args) throws JepException{\n+ JepConfig config = new JepConfig();\n+ config.addIncludePaths(\".\");\n+ Jep jep = new Jep(config);\n+ jep.eval(\"import py_compile\");\n+ jep.eval(\"py_compile.compile(file='build/testScript.py', cfile='build/testScript.pyc')\");\n+ jep.eval(null);\n+ jep.runScript(\"build/testScript.pyc\");\n+ Object result = jep.getValue(\"isGood()\");\n+ jep.close();\n+ if(!Boolean.TRUE.equals(result)){\n+ throw new IllegalStateException(\"isGood() returned \" + result);\n+ }\n+ }\n+\n+}\ndiff --git a/tests/test_run_script.py b/tests/test_run_script.py\nnew file mode 100644\nindex 0000000..d406d60\n--- /dev/null\n+++ b/tests/test_run_script.py\n@@ -0,0 +1,26 @@\n+import unittest\n+import os\n+import os.path\n+\n+from tests.jep_pipe import jep_pipe\n+from tests.jep_pipe import build_java_process_cmd\n+\n+\n+class TestRunScript(unittest.TestCase):\n+\n+ def setUp(self):\n+ with open('build/testScript.py', 'w') as testScript:\n+ testScript.write(\"def isGood():\\n\")\n+ testScript.write(\" return True\\n\")\n+ \n+\n+ def test_compiledScript(self):\n+ jep_pipe(build_java_process_cmd('jep.test.TestCompiledScript'))\n+\n+\n+ def tearDown(self):\n+ if os.path.exists('build/testScript.py'):\n+ os.remove('build/testScript.py')\n+ if os.path.exists('build/testScript.pyc'):\n+ os.remove('build/testScript.pyc')\n+\n", "FAIL_TO_PASS": ["test_run_script.TestRunScript.test_compiledScript"], "PASS_TO_PASS": ["test_array.TestArray.test_initialization", "test_array.TestArray.test_int_setitem_wrong_type_throws_exception", "test_array.TestArray.test_iter", "test_array.TestArray.test_read_file", "test_array.TestArray.test_set_string_array", "test_array.TestArray.test_setitem", "test_array.TestArray.test_setitem_out_of_bounds_throws_exception", "test_array.TestArray.test_slice", "test_array.TestArray.test_slice_out_of_bounds_handled_cleanly", "test_array.TestArray.test_slice_with_step_not_1_throws_exception", "test_array.TestArray.test_string_index_conversion", "test_call.TestTypes.test_20args", "test_call.TestTypes.test_bool_array", "test_call.TestTypes.test_deepList", "test_call.TestTypes.test_enum", "test_call.TestTypes.test_equals", "test_call.TestTypes.test_float_array", "test_call.TestTypes.test_getstring_array", "test_call.TestTypes.test_int_array", "test_call.TestTypes.test_object_array", "test_call.TestTypes.test_overload", "test_call.TestTypes.test_short_array", "test_call.TestTypes.test_string_string_array", "test_compare.TestCompare.test_date_compare", "test_compare.TestCompare.test_equals", "test_compare.TestCompare.test_int_compare", "test_dir.TestDir.test_dir_arraylist", "test_dir.TestDir.test_dir_package", "test_dir.TestDir.test_dir_subpackage", "test_exceptions.TestExceptions.test_arithmetic_error", "test_exceptions.TestExceptions.test_import_error", "test_exceptions.TestExceptions.test_index_error", "test_exceptions.TestExceptions.test_io_error", "test_exceptions.TestExceptions.test_io_exception", "test_exceptions.TestExceptions.test_null_pointer_exception", "test_exceptions.TestExceptions.test_number_format", "test_exceptions.TestExceptions.test_type_error", "test_exceptions.TestExceptions.test_value_err", "test_import.TestImport.test_class_import", "test_import.TestImport.test_conflicting_package", "test_import.TestImport.test_java_sql", "test_import.TestImport.test_not_found", "test_import.TestImport.test_restricted_classloader", "test_import.TestImport.test_without_restricted_classloader", "test_iterators.TestIterators.test_iteration", "test_lists.TestLists.test_add", "test_lists.TestLists.test_addequals", "test_lists.TestLists.test_contains", "test_lists.TestLists.test_del", "test_lists.TestLists.test_getitem", "test_lists.TestLists.test_getslice", "test_lists.TestLists.test_getstringbyindex", "test_lists.TestLists.test_getstringbyiterator", "test_lists.TestLists.test_len", "test_lists.TestLists.test_loop", "test_lists.TestLists.test_multiply", "test_lists.TestLists.test_multiplyequals", "test_lists.TestLists.test_sequence", "test_lists.TestLists.test_setitem", "test_lists.TestLists.test_setslice", "test_maps.TestMaps.test_del", "test_maps.TestMaps.test_getitem", "test_maps.TestMaps.test_iter", "test_maps.TestMaps.test_len", "test_numbers.TestNumbers.test_absolute", "test_numbers.TestNumbers.test_add", "test_numbers.TestNumbers.test_compare", "test_numbers.TestNumbers.test_divide", "test_numbers.TestNumbers.test_divmod", "test_numbers.TestNumbers.test_index", "test_numbers.TestNumbers.test_multiply", "test_numbers.TestNumbers.test_negative", "test_numbers.TestNumbers.test_nonzero", "test_numbers.TestNumbers.test_positive", "test_numbers.TestNumbers.test_pow", "test_numbers.TestNumbers.test_remainder", "test_numbers.TestNumbers.test_subtract", "test_object.TestObject.test_del_throws_exception", "test_object.TestObject.test_hash", "test_object.TestObject.test_str", "test_regressions.TestRegressions.test_byte_value", "test_regressions.TestRegressions.test_out", "test_types.TestTypes.test_boolean", "test_types.TestTypes.test_byte", "test_types.TestTypes.test_byte_coercion", "test_types.TestTypes.test_byte_overflow", "test_types.TestTypes.test_char", "test_types.TestTypes.test_char_coercion", "test_types.TestTypes.test_class", "test_types.TestTypes.test_class_coercion", "test_types.TestTypes.test_double", "test_types.TestTypes.test_double_coercion", "test_types.TestTypes.test_double_nan", "test_types.TestTypes.test_float", "test_types.TestTypes.test_float_coercion", "test_types.TestTypes.test_float_nan", "test_types.TestTypes.test_int", "test_types.TestTypes.test_int_coersion", "test_types.TestTypes.test_int_overflow", "test_types.TestTypes.test_long", "test_types.TestTypes.test_long_coersion", "test_types.TestTypes.test_long_overflow", "test_types.TestTypes.test_object_boolean_coercion", "test_types.TestTypes.test_object_byte_boolean_coercion", "test_types.TestTypes.test_object_double_int_coercion", "test_types.TestTypes.test_object_float_int_coercion", "test_types.TestTypes.test_object_int_boolean_coersion", "test_types.TestTypes.test_object_long_boolean_coersion", "test_types.TestTypes.test_object_short_boolean_coercion", "test_types.TestTypes.test_primitive_boolean_coercion", "test_types.TestTypes.test_primitive_byte_boolean_coercion", "test_types.TestTypes.test_primitive_double_int_coercion", "test_types.TestTypes.test_primitive_float_int_coercion", "test_types.TestTypes.test_primitive_int_boolean_coersion", "test_types.TestTypes.test_primitive_long_boolean_coersion", "test_types.TestTypes.test_primitive_short_boolean_coercion", "test_types.TestTypes.test_short", "test_types.TestTypes.test_short_coercion", "test_types.TestTypes.test_short_overflow", "test_types.TestTypes.test_string", "test_types.TestTypes.test_string_coercion"]} +{"instance_id": "clb-javac-100", "repo": "ninia/jep", "base_commit": "bbf96b5cbb83fe9e4edef71d410d29460084d5fc", "problem_statement": "JEP should map common Java exceptions to the corresponding Python built-in exceptions and preserve correct import-hook behavior.", "image": {"image_id": "sha256:be480bb4f1310e82d3b624cc62a6901dc084b6db19bd16ae44a50d19400e22bb", "pull_reference": "yutu0814/javac-case-100-jep@sha256:be480bb4f1310e82d3b624cc62a6901dc084b6db19bd16ae44a50d19400e22bb"}, "cohort": "java_upstream11", "patch": "diff --git a/jep/hook.py b/jep/hook.py\nindex c9744ca..74fa143 100644\n--- a/jep/hook.py\n+++ b/jep/hook.py\n@@ -1,5 +1,5 @@\n from _jep import forName\n-import sys\n+import sys, string\n from types import ModuleType\n \n \n@@ -19,13 +19,9 @@ class module(ModuleType):\n try:\n return super(module, self).__getattribute__(name)\n except AttributeError as ae:\n- try:\n- clazz = forName('{0}.{1}'.format(self.__name__, name))\n- setattr(self, name, clazz)\n- return clazz\n- except Exception:\n- # should raise AttributeError, not JepException\n- raise ae\n+ clazz = forName('{0}.{1}'.format(self.__name__, name))\n+ setattr(self, name, clazz)\n+ return clazz\n \n \n class JepImporter(object):\n@@ -44,23 +40,34 @@ class JepImporter(object):\n if fullname in sys.modules:\n return sys.modules[fullname]\n \n- mod = module(fullname)\n- mod.__dict__.update({\n- '__loader__': self,\n- '__path__': [],\n- '__file__': '',\n- })\n- sys.modules[fullname] = mod\n-\n- if self.classlist.supportsPackageImport():\n- # list of classes in package\n- classlist = self.classlist.get(fullname)\n- if classlist:\n- for name in classlist:\n- try:\n- setattr(mod, name.split('.')[-1], forName(name))\n- except Exception:\n- pass\n+ split = fullname.split('.')\n+ if split[-1][0].islower():\n+ # it's a package/module\n+ mod = module(fullname)\n+ mod.__dict__.update({\n+ '__loader__': self,\n+ '__path__': [],\n+ '__file__': '',\n+ })\n+ sys.modules[fullname] = mod\n+ \n+ if self.classlist.supportsPackageImport():\n+ # get the list of classes in package and add them as attributes\n+ # to the module\n+ classlist = self.classlist.get(fullname)\n+ if classlist:\n+ for name in classlist:\n+ try:\n+ setattr(mod, name.split('.')[-1], forName(name))\n+ except Exception:\n+ pass\n+ else:\n+ # It's a Java class, in general we will only reach here if\n+ # self.classlist.supportsPackageImport() is False (ie the class\n+ # has not already been imported and set on the module).\n+ parentModName = string.join(split[0:-1], '.')\n+ parentMod = sys.modules[parentModName]\n+ return parentMod.__getattr__(split[-1])\n return mod\n \n \ndiff --git a/src/jep/pyjclass.c b/src/jep/pyjclass.c\nindex 1c3b23a..fe3c1f9 100644\n--- a/src/jep/pyjclass.c\n+++ b/src/jep/pyjclass.c\n@@ -301,7 +301,7 @@ static PyObject* pyjclass_add_inner_classes(JNIEnv *env,\n return NULL;\n charName = jstring2char(env, shortName);\n \n- if(PyObject_SetAttrString((PyObject*) topClz, charName, attrClz) != -0) {\n+ if(PyObject_SetAttrString((PyObject*) topClz, charName, attrClz) == -1) {\n printf(\"Error adding inner class %s\\n\", charName);\n }\n release_utf_char(env, shortName, charName);\ndiff --git a/src/jep/util.c b/src/jep/util.c\nindex c189b6b..9b1a195 100644\n--- a/src/jep/util.c\n+++ b/src/jep/util.c\n@@ -71,6 +71,8 @@ static PyObject* convert_jprimitivearray_pyndarray(JNIEnv*, jobject, int, npy_in\n static jarray convert_pyndarray_jprimitivearray(JNIEnv*, PyObject*, jclass);\n #endif\n \n+static PyObject* match_exception_type(JNIEnv*, jthrowable);\n+\n \n // -------------------------------------------------- primitive class types\n // these are shared for all threads, you shouldn't change them.\n@@ -403,10 +405,12 @@ int process_py_exception(JNIEnv *env, int printTrace) {\n */\n if(pyLine != Py_None) {\n char *charPyFileNoExt, *lastDot;\n+ char *charPyFileNoDir, *lastBackslash;\n int namelen;\n jobject element;\n- jstring pyFile, pyFileNoExt, pyFunc;\n+ jstring pyFileNoDir, pyFileNoExt, pyFunc;\n \n+ // remove the .py to look more like a Java StackTraceElement\n namelen = (int) strlen(charPyFile);\n charPyFileNoExt = malloc(sizeof(char) * (namelen + 1));\n strcpy(charPyFileNoExt, charPyFile);\n@@ -415,8 +419,18 @@ int process_py_exception(JNIEnv *env, int printTrace) {\n *lastDot = '\\0';\n }\n \n- pyFile = (*env)->NewStringUTF(env,\n- (const char *) charPyFile);\n+ // remove the dir path to look more like a Java StackTraceElement\n+ charPyFileNoDir = malloc(sizeof(char) * (namelen + 1));\n+ // TODO does this work right on Windows?\n+ lastBackslash = strrchr(charPyFile, '/');\n+ if(lastBackslash != NULL) {\n+ strcpy(charPyFileNoDir, lastBackslash + 1);\n+ } else {\n+ strcpy(charPyFileNoDir, charPyFile);\n+ }\n+\n+ pyFileNoDir = (*env)->NewStringUTF(env,\n+ (const char *) charPyFileNoDir);\n pyFileNoExt = (*env)->NewStringUTF(env,\n (const char *) charPyFileNoExt);\n pyFunc = (*env)->NewStringUTF(env,\n@@ -428,14 +442,15 @@ int process_py_exception(JNIEnv *env, int printTrace) {\n * this makes it look best.\n */\n element = (*env)->NewObject(env, stackTraceElemClazz,\n- stackTraceElemInit, pyFileNoExt, pyFunc, pyFile,\n+ stackTraceElemInit, pyFileNoExt, pyFunc, pyFileNoDir,\n pyLineNum);\n if((*env)->ExceptionCheck(env) || !element) {\n PyErr_Format(PyExc_RuntimeError,\n \"failed to create java.lang.StackTraceElement for python %s:%i.\",\n charPyFile, pyLineNum);\n- release_utf_char(env, pyFile, charPyFile);\n+ release_utf_char(env, pyFileNoDir, charPyFileNoDir);\n release_utf_char(env, pyFileNoExt, charPyFileNoExt);\n+ free(charPyFileNoDir);\n free(charPyFileNoExt);\n release_utf_char(env, pyFunc, charPyFunc);\n Py_DECREF(pystack);\n@@ -444,8 +459,9 @@ int process_py_exception(JNIEnv *env, int printTrace) {\n (*env)->SetObjectArrayElement(env, stackArray, (jsize) i,\n element);\n count++;\n+ free(charPyFileNoDir);\n free(charPyFileNoExt);\n- (*env)->DeleteLocalRef(env, pyFile);\n+ (*env)->DeleteLocalRef(env, pyFileNoDir);\n (*env)->DeleteLocalRef(env, pyFileNoExt);\n (*env)->DeleteLocalRef(env, pyFunc);\n (*env)->DeleteLocalRef(env, element);\n@@ -613,12 +629,107 @@ int process_java_exception(JNIEnv *env) {\n return 1;\n }\n \n+ pyException = match_exception_type(env, exception);\n PyErr_SetObject(pyException, jpyExc);\n (*env)->DeleteLocalRef(env, clazz);\n (*env)->DeleteLocalRef(env, exception);\n return 1;\n }\n \n+/*\n+ * Matches a jthrowable to an equivalent built-in python exception type. This\n+ * is to enable more precise except/catch blocks in python for Java exceptions.\n+ * This method intentionally does not call process_java_exception as it is only\n+ * called when processing java exceptions, and we don't want to infinitely recurse.\n+ *\n+ */\n+static PyObject* match_exception_type(JNIEnv *env, jthrowable exception) {\n+ jclass classNotFound, indexBounds, io, classCast;\n+ jclass illegalArg, arithmetic, memory, assertion;\n+\n+ // map ClassNotFoundException to ImportError\n+ classNotFound = (*env)->FindClass(env, \"java/lang/ClassNotFoundException\");\n+ if((*env)->ExceptionOccurred(env) || !classNotFound) {\n+ goto EXIT_ERROR;\n+ }\n+ if((*env)->IsInstanceOf(env, exception, classNotFound)) {\n+ return PyExc_ImportError;\n+ }\n+\n+ // map IndexOutOfBoundsException exception to IndexError\n+ indexBounds = (*env)->FindClass(env, \"java/lang/IndexOutOfBoundsException\");\n+ if((*env)->ExceptionOccurred(env) || !indexBounds) {\n+ goto EXIT_ERROR;\n+ }\n+ if((*env)->IsInstanceOf(env, exception, indexBounds)) {\n+ return PyExc_IndexError;\n+ }\n+\n+ // map IOException to IOError\n+ io = (*env)->FindClass(env, \"java/io/IOException\");\n+ if((*env)->ExceptionOccurred(env) || !io) {\n+ goto EXIT_ERROR;\n+ }\n+ if((*env)->IsInstanceOf(env, exception, io)) {\n+ return PyExc_IOError;\n+ }\n+\n+ // map ClassCastException to TypeError\n+ classCast = (*env)->FindClass(env, \"java/lang/ClassCastException\");\n+ if((*env)->ExceptionOccurred(env) || !classCast) {\n+ goto EXIT_ERROR;\n+ }\n+ if((*env)->IsInstanceOf(env, exception, classCast)) {\n+ return PyExc_TypeError;\n+ }\n+\n+ // map IllegalArgumentException to ValueError\n+ illegalArg = (*env)->FindClass(env, \"java/lang/IllegalArgumentException\");\n+ if((*env)->ExceptionOccurred(env) || !illegalArg) {\n+ goto EXIT_ERROR;\n+ }\n+ if((*env)->IsInstanceOf(env, exception, illegalArg)) {\n+ return PyExc_ValueError;\n+ }\n+\n+ // map ArithmeticException to ArithmeticError\n+ arithmetic = (*env)->FindClass(env, \"java/lang/ArithmeticException\");\n+ if((*env)->ExceptionOccurred(env) || !arithmetic) {\n+ goto EXIT_ERROR;\n+ }\n+ if((*env)->IsInstanceOf(env, exception, arithmetic)) {\n+ return PyExc_ArithmeticError;\n+ }\n+\n+ // map OutOfMemoryError to MemoryError\n+ memory = (*env)->FindClass(env, \"java/lang/OutOfMemoryError\");\n+ if((*env)->ExceptionOccurred(env) || !memory) {\n+ goto EXIT_ERROR;\n+ }\n+ if((*env)->IsInstanceOf(env, exception, memory)) {\n+ // honestly if you hit this you're probably screwed\n+ return PyExc_MemoryError;\n+ }\n+\n+ // map AssertionError to AssertionError\n+ assertion = (*env)->FindClass(env, \"java/lang/AssertionError\");\n+ if((*env)->ExceptionOccurred(env) || !assertion) {\n+ goto EXIT_ERROR;\n+ }\n+ if((*env)->IsInstanceOf(env, exception, assertion)) {\n+ return PyExc_AssertionError;\n+ }\n+\n+ // default\n+ return PyExc_RuntimeError;\n+\n+EXIT_ERROR:\n+ printf(\"Error mapping exception types\\n\");\n+ (*env)->ExceptionDescribe(env);\n+ (*env)->ExceptionClear(env);\n+ return PyExc_RuntimeError;\n+}\n+\n \n // call toString() on jobject and return result.\n // NULL on error\n@@ -1302,7 +1413,7 @@ int pyarg_matches_jtype(JNIEnv *env,\n break;\n \n case JBOOLEAN_ID:\n- if(PyBool_Check(param))\n+ if(PyInt_Check(param))\n return 1;\n break;\n }\n", "test_patch": "diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py\nindex bbe13e8..af49482 100644\n--- a/tests/test_exceptions.py\n+++ b/tests/test_exceptions.py\n@@ -24,3 +24,56 @@ class TestExceptions(unittest.TestCase):\n except Exception as ex:\n # because it's not a checked exception, mapped exceptions doesn't apply here (all Runtime) \n self.assertIn('java.lang.NullPointerException', str(ex.message))\n+\n+\n+# the tests below verify that specific java exceptions map to python errors,\n+# enabling more precise except blocks when python encounters a java error\n+\n+ def test_import_error(self):\n+ try:\n+ from java.lang import ArrayList\n+ except ImportError as ex:\n+ pass\n+\n+ def test_index_error(self):\n+ x = jep.jarray(3, Integer)\n+ try:\n+ i = x[5]\n+ except IndexError as ex:\n+ pass\n+\n+ def test_io_error(self):\n+ try:\n+ FileInputStream('asdf')\n+ except IOError as ex:\n+ pass\n+\n+ def test_type_error(self):\n+ try:\n+ from java.util import Collections, ArrayList\n+ x = ArrayList()\n+ c = Collections.checkedList(x, Integer)\n+ c.add(Integer(5))\n+ c.add(String(\"5\"))\n+ except TypeError as ex:\n+ pass\n+\n+ def test_value_err(self):\n+ try:\n+ from java.lang import System\n+ System.getProperty('', '')\n+ except ValueError as ex:\n+ pass\n+\n+ def test_arithmetic_error(self):\n+ try:\n+ from java.math import BigDecimal\n+ d = BigDecimal(3.14159)\n+ zero = BigDecimal(0.0)\n+ x = d.divide(zero)\n+ except ArithmeticError as ex:\n+ pass\n+ \n+ # TODO come up with a way to test MemoryError and AssertionError given\n+ # I coded support for that.\n+\ndiff --git a/tests/test_import.py b/tests/test_import.py\nindex 24a8ac8..d00569e 100644\n--- a/tests/test_import.py\n+++ b/tests/test_import.py\n@@ -18,7 +18,7 @@ class TestImport(unittest.TestCase):\n importer = JepImporter()\n mod = importer.load_module('java.lang')\n mod.Integer\n- self.assertRaises(AttributeError, mod.__getattr__, 'asdf')\n+ self.assertRaises(ImportError, mod.__getattr__, 'asdf')\n \n def test_restricted_classloader(self):\n # should use the supplied classloader for hooks\n", "FAIL_TO_PASS": ["test_exceptions.TestExceptions.test_io_error", "test_exceptions.TestExceptions.test_type_error", "test_exceptions.TestExceptions.test_value_err", "test_exceptions.TestExceptions.test_arithmetic_error", "test_import.TestImport.test_not_found"], "PASS_TO_PASS": ["test_array.TestArray.test_slice", "test_array.TestArray.test_read_file", "test_call.TestTypes.test_string", "test_call.TestTypes.test_enum", "test_call.TestTypes.test_long", "test_call.TestTypes.test_double", "test_call.TestTypes.test_float", "test_call.TestTypes.test_intobj", "test_call.TestTypes.test_getobj", "test_call.TestTypes.test_getstring_array", "test_call.TestTypes.test_string_string_array", "test_call.TestTypes.test_int_array", "test_call.TestTypes.test_bool_array", "test_call.TestTypes.test_short_array", "test_call.TestTypes.test_float_array", "test_call.TestTypes.test_object_array", "test_call.TestTypes.test_equals", "test_exceptions.TestExceptions.test_number_format", "test_exceptions.TestExceptions.test_io_exception", "test_exceptions.TestExceptions.test_null_pointer_exception", "test_import.TestImport.test_java_sql", "test_import.TestImport.test_restricted_classloader", "test_import.TestImport.test_without_restricted_classloader", "test_import.TestImport.test_class_import", "test_jdbc.TestJdbc.test_java_sql", "test_jdbc.TestJdbc.test_dbapi_primitives", "test_jdbc.TestJdbc.test_datetime", "test_jdbc.TestJdbc.test_batch", "test_lists.TestLists.test_sequence", "test_lists.TestLists.test_len", "test_lists.TestLists.test_loop", "test_lists.TestLists.test_contains", "test_lists.TestLists.test_getitem", "test_lists.TestLists.test_getslice", "test_lists.TestLists.test_setitem", "test_lists.TestLists.test_setslice", "test_lists.TestLists.test_add", "test_lists.TestLists.test_addequals", "test_lists.TestLists.test_multiply", "test_lists.TestLists.test_multiplyequals", "test_numpy.TestNumpy.testSetGet", "test_numpy.TestNumpy.testArgReturn", "test_numpy.TestNumpy.testMultiDimensional", "test_numpy.TestNumpy.testArrayParams", "test_regressions.TestRegressions.test_out", "test_regressions.TestRegressions.test_byte_value", "test_types.TestFields.test_string", "test_types.TestFields.test_boolean_field", "test_types.TestFields.test_short_field", "test_types.TestFields.test_int_field", "test_types.TestFields.test_long_field", "test_types.TestFields.test_double_field", "test_types.TestFields.test_float_field", "test_types.TestFields.test_byte_field", "test_types.TestFields.test_char_field", "test_types.TestFields.test_class_field", "test_types.TestFields.test_static_string", "test_types.TestFields.test_static_boolean_field", "test_types.TestFields.test_static_short_field", "test_types.TestFields.test_static_int_field", "test_types.TestFields.test_static_long_field", "test_types.TestFields.test_static_double_field", "test_types.TestFields.test_static_float_field", "test_types.TestFields.test_static_byte_field", "test_types.TestFields.test_static_char_field", "test_types.TestFields.test_static_class_field", "test_types.TestFields.test_equals", "test_exceptions.TestExceptions.test_import_error", "test_exceptions.TestExceptions.test_index_error"]} +{"instance_id": "clb-javac-112", "repo": "uclouvain/openjpeg", "base_commit": "4f5ec07c315872bdee0885be085ebf57cede2db9", "problem_statement": "opj_compress fails to compress lossless on gcc/x86 (-m32)\nI am having an issue with OPJ 1.5 and the following file:\n\nhttp://gdcm.sourceforge.net/thingies/lossless_issue.pgm\n\nIt looks as if I cannot do a round-trip lossless compression / decompression, within a 32bits schroot. Everything is fine within a 64bits schroot system (debian jessie if that matter).\n\n", "image": {"image_id": "sha256:33a22445240b5d6abba03d5c41a277d721fc8940f51aa3e7b7138daeb2f87305", "pull_reference": "yutu0814/javac-case-112-openjpeg@sha256:33a22445240b5d6abba03d5c41a277d721fc8940f51aa3e7b7138daeb2f87305"}, "cohort": "java_upstream11", "patch": "diff --git a/src/lib/openjp2/tcd.c b/src/lib/openjp2/tcd.c\nindex 8f1c9410..2fccff1c 100644\n--- a/src/lib/openjp2/tcd.c\n+++ b/src/lib/openjp2/tcd.c\n@@ -268,7 +268,7 @@ void opj_tcd_makelayer( opj_tcd_t *tcd,\n n = passno + 1;\n continue;\n }\n- if (dd / dr >= thresh)\n+ if (thresh - (dd / dr) < DBL_EPSILON) /* do not rely on float equality, check with DBL_EPSILON margin */\n n = passno + 1;\n }\n \n", "test_patch": "diff --git a/tests/compare_images.c b/tests/compare_images.c\nindex cb1b1301..b28d4957 100644\n--- a/tests/compare_images.c\n+++ b/tests/compare_images.c\n@@ -85,7 +85,7 @@ static void compare_images_help_display(void)\n fprintf(stdout,\"\\n\");\n fprintf(stdout,\" -b \\t REQUIRED \\t filename to the reference/baseline PGX/TIF/PNM image \\n\");\n fprintf(stdout,\" -t \\t REQUIRED \\t filename to the test PGX/TIF/PNM image\\n\");\n- fprintf(stdout,\" -n \\t REQUIRED \\t number of component of the image (used to generate correct filename)\\n\");\n+ fprintf(stdout,\" -n \\t REQUIRED \\t number of component of the image (used to generate correct filename, not used when both input files are TIF)\\n\");\n fprintf(stdout,\" -m \\t OPTIONAL \\t list of MSE tolerances, separated by : (size must correspond to the number of component) of \\n\");\n fprintf(stdout,\" -p \\t OPTIONAL \\t list of PEAK tolerances, separated by : (size must correspond to the number of component) \\n\");\n fprintf(stdout,\" -s \\t OPTIONAL \\t 1 or 2 filename separator to take into account PGX/PNM image with different components, \"\n@@ -279,8 +279,6 @@ static opj_image_t* readImageFromFileTIF(const char* filename, int nbFilenamePGX\n return NULL;\n }\n \n- /* \\postconditions */\n- assert( image_read->numcomps == 1 || image_read->numcomps == 3 );\n return image_read;\n }\n \ndiff --git a/tests/nonregression/CMakeLists.txt b/tests/nonregression/CMakeLists.txt\nindex 2527f8cb..5ce37c81 100644\n--- a/tests/nonregression/CMakeLists.txt\n+++ b/tests/nonregression/CMakeLists.txt\n@@ -353,6 +353,26 @@ foreach(OPJ_TEST_CMD_LINE ${OPJ_TEST_CMD_LINE_LIST})\n )\t\t\n endif()\n endif(JPYLYZER_EXECUTABLE)\n+ \n+ # If lossless compression (simple test is 4 arguments), decompress & compare\n+ list(LENGTH CMD_ARG_LIST_2 ARG_COUNT)\n+ if (ARG_COUNT EQUAL 4)\n+ # can we compare with the input image ?\n+ if (${INPUT_FILENAME_NAME} MATCHES \"\\\\.tif$\")\n+ add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-lossless-decode\n+ COMMAND opj_decompress -i ${OUTPUT_FILENAME} -o ${OUTPUT_FILENAME}.lossless.tif\n+ )\n+ set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-lossless-decode PROPERTIES \n+ DEPENDS NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-encode\n+ )\n+ add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-lossless-compare\n+ COMMAND compare_images -b ${INPUT_FILENAME} -t ${OUTPUT_FILENAME}.lossless.tif -n 1 -d\n+ )\n+ set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-lossless-compare PROPERTIES \n+ DEPENDS NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-lossless-decode\n+ )\t\n+ endif()\n+ endif()\n endif()\n \n # DECODER TEST SUITE\ndiff --git a/tests/nonregression/test_suite.ctest.in b/tests/nonregression/test_suite.ctest.in\nindex 6f9bba83..7e3a35a8 100644\n--- a/tests/nonregression/test_suite.ctest.in\n+++ b/tests/nonregression/test_suite.ctest.in\n@@ -134,6 +134,9 @@ opj_compress -i @INPUT_NR_PATH@/pngsuite/ftp0n2c08.png -o @TEMP_PATH@/ftp0n2c08.\n opj_compress -i @INPUT_NR_PATH@/pngsuite/ftp0n3p08.png -o @TEMP_PATH@/ftp0n3p08.png.jp2\n opj_compress -i @INPUT_NR_PATH@/pngsuite/ftp1n3p08.png -o @TEMP_PATH@/ftp1n3p08.png.jp2\n \n+# issue 571 Lossless is not lossless on linux x86\n+opj_compress -i @INPUT_NR_PATH@/issue571.tif -o @TEMP_PATH@/issue571.tif.j2k\n+\n # DECODER TEST SUITE\n opj_decompress -i @INPUT_NR_PATH@/Bretagne2.j2k -o @TEMP_PATH@/Bretagne2.j2k.pgx\n opj_decompress -i @INPUT_NR_PATH@/_00042.j2k -o @TEMP_PATH@/_00042.j2k.pgx\n", "FAIL_TO_PASS": ["openjpeg.issue571.lossless_roundtrip"], "PASS_TO_PASS": ["openjpeg.issue571.encode_issue571", "openjpeg.issue571.decode_issue571"]} +{"instance_id": "clb-javac-150", "repo": "kohlschutter/junixsocket", "base_commit": "7578a2470871e12dd72716925f60d857ad7eb409", "problem_statement": "Length of name in abstract namespace is not respected anymore\nWhen upgrading an existing Linux project from junixsocket 2.3.2 to 2.5.1, the below (previously working) code pattern stopped working. The scenario involves a Java process listening on a Unix domain socket in an abstract namespace and a C client process trying to connect to it.\r\n\r\nJava server process:\r\n```java\r\nString socketName = \"foobar\";\r\nAFUNIXServerSocket serverSocket = AFUNIXServerSocket.newInstance();\r\nserverSocket.bind(AFUNIXSocketAddress.inAbstractNamespace(socketName));\r\nAFUNIXSocket socket = serverSocket.accept();\r\n```\r\n\r\nC client process:\r\n```cpp\r\nconst char *socket_name = \"foobar\";\r\nsockaddr_un socket_addr;\r\nbzero(&socket_addr, sizeof(socket_addr));\r\nsocket_addr.sun_family = AF_UNIX;\r\nstrncpy(socket_addr.sun_path + 1, socket_name, strlen(socket_name));\r\nint server_socket = socket(AF_UNIX, SOCK_STREAM, 0);\r\nconnect(server_socket, (struct sockaddr *) &socket_addr,\r\n offsetof(sockaddr_un, sun_path) + strlen(socket_name) + 1);\r\n```\r\n\r\nUsing strace revealed the new version of junixsocket does not respect the length of the given socket name and always considers the entire content of `sun_path` as a socket name (i.e. all 108 bytes, instead of just 7):\r\n```\r\n[pid 10013] bind(138, {sa_family=AF_LOCAL, sun_path=@\"foobar\"}, 110) = 0\r\n\r\n[pid 10238] connect(17, {sa_family=AF_LOCAL, sun_path=@\"foobar\"}, 9) = -1 ECONNREFUSED (Connection refused)\r\n```\r\nThe workaround is to use a socket name that has the maximum possible length on a given platform (i.e. 107 bytes on Linux, leaving room just for the initial null byte).\n", "image": {"image_id": "sha256:1e6da170e3dc03c5245f2c4ce3a47c2b4e200615df73876ed17a2ffa015d5a35", "pull_reference": "yutu0814/javac-case-150-junixsocket@sha256:1e6da170e3dc03c5245f2c4ce3a47c2b4e200615df73876ed17a2ffa015d5a35"}, "cohort": "java_upstream11", "patch": "diff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFInetAddress.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFInetAddress.java\nindex 9eb15d68..c8078cfb 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFInetAddress.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFInetAddress.java\n@@ -134,7 +134,7 @@ class AFInetAddress {\n \n byte[] bytes = createUnresolvedHostname(socketAddress, af).getBytes(StandardCharsets.UTF_8);\n if (bytes.length > 255) {\n- throw new IllegalStateException(\"Address too long\");\n+ throw new IllegalStateException(\"junixsocket address is too long to wrap as InetAddress\");\n }\n byte[] serializedData = new byte[SERIALIZED_INET_ADDRESS_START.length + 1 + bytes.length + 1];\n System.arraycopy(SERIALIZED_INET_ADDRESS_START, 0, serializedData, 0,\ndiff --git a/junixsocket-native/crossclang/bin/clang b/junixsocket-native/crossclang/bin/clang\nindex e8c9628a..97aa0cfe 100755\n--- a/junixsocket-native/crossclang/bin/clang\n+++ b/junixsocket-native/crossclang/bin/clang\n@@ -127,6 +127,8 @@ while [ $# -gt 0 ]; do\n -Wshorten-64-to-32 ) skipGccArg=1 ;;\n -Wobjc-literal-conversion ) skipGccArg=1 ;;\n -Wnon-literal-null-conversion ) skipGccArg=1 ;;\n+ -Wno-c++11-extensions ) skipGccArg=1 ;;\n+ -Wno-declaration-after-statement ) skipGccArg=1 ;;\n -Wbool-conversion ) skipGccArg=1 ;;\n -Wconstant-conversion ) skipGccArg=1 ;;\n -Wquoted-include-in-framework-header ) skipGccArg=1 ;;\ndiff --git a/junixsocket-native/junixsocket-native.xcodeproj/project.pbxproj b/junixsocket-native/junixsocket-native.xcodeproj/project.pbxproj\nindex 9636100f..d30d994c 100644\n--- a/junixsocket-native/junixsocket-native.xcodeproj/project.pbxproj\n+++ b/junixsocket-native/junixsocket-native.xcodeproj/project.pbxproj\n@@ -4378,6 +4378,7 @@\n \t\t\t\t\t\"-Wint-conversion\",\n \t\t\t\t\t\"-Wno-unused-command-line-argument\",\n \t\t\t\t\t\"-Werror-implicit-function-declaration\",\n+\t\t\t\t\t\"-Wno-declaration-after-statement\",\n \t\t\t\t);\n \t\t\t};\n \t\t\tname = Debug;\n@@ -4456,6 +4457,7 @@\n \t\t\t\t\t\"-Wint-conversion\",\n \t\t\t\t\t\"-Wno-unused-command-line-argument\",\n \t\t\t\t\t\"-Werror-implicit-function-declaration\",\n+\t\t\t\t\t\"-Wno-declaration-after-statement\",\n \t\t\t\t);\n \t\t\t};\n \t\t\tname = Release;\ndiff --git a/junixsocket-native/src/main/c/address.c b/junixsocket-native/src/main/c/address.c\nindex 6a530bad..e8dfd19f 100644\n--- a/junixsocket-native/src/main/c/address.c\n+++ b/junixsocket-native/src/main/c/address.c\n@@ -128,7 +128,7 @@ static jbyteArray sockAddrUnToBytes(JNIEnv *env, struct sockaddr_un *addr, sockl\n return NULL;\n }\n #if defined(junixsocket_have_sun_len)\n- len = MIN(len, sizeof(struct sockaddr_un)-2);\n+ len = MIN(len, sizeof(struct sockaddr_un) - 2);\n if(len < 256 && addr->sun_len < len) {\n len = addr->sun_len;\n }\n@@ -159,6 +159,12 @@ static jbyteArray sockAddrUnToBytes(JNIEnv *env, struct sockaddr_un *addr, sockl\n return NULL;\n }\n \n+#if defined(__linux__)\n+ if(firstZero && addr->sun_path[len-1] == 0) {\n+ len -= 1;\n+ }\n+#endif\n+\n jbyteArray array = (*env)->NewByteArray(env, len);\n (*env)->SetByteArrayRegion(env, array, 0, len, (jbyte*)addr->sun_path);\n \n@@ -353,8 +359,9 @@ JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAdd\n */\n JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bytesToSockAddr\n (JNIEnv *env, jclass clazz CK_UNUSED, jint domain, jobject directByteBuf, jbyteArray addressBytes) {\n- domain = domainToNative(domain);\n size_t sockAddrLen;\n+\n+ domain = domainToNative(domain);\n switch(domain) {\n case AF_UNIX:\n sockAddrLen = sizeof(struct sockaddr_un);\n@@ -395,9 +402,16 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bytesToSockAd\n {\n struct sockaddr_un *addrUn = (struct sockaddr_un *) addr;\n #if defined(junixsocket_have_sun_len)\n- addrUn->sun_len = ((socklen_t)len >= SUN_NAME_MAX_LEN) ? SUN_NAME_MAX_LEN : len + 1; // including zero byte\n+ addrUn->sun_len = ((socklen_t)len >= SUN_NAME_MAX_LEN) ? SUN_NAME_MAX_LEN :\n+ (socklen_t)len + 1; // including zero byte\n #endif\n (*env)->GetByteArrayRegion(env, addressBytes, 0, len, (signed char*)addrUn->sun_path);\n+\n+#if defined(__linux__)\n+ if(addrUn->sun_path[0] == 0) {\n+ sockAddrLen = MIN((size_t)(len + sizeof(sa_family_t)), sockAddrLen);\n+ }\n+#endif\n }\n break;\n #if junixsocket_have_tipc\n", "test_patch": "diff --git a/junixsocket-common/src/test/java/org/newsclub/net/unix/AFUNIXSocketAddressTest.java b/junixsocket-common/src/test/java/org/newsclub/net/unix/AFUNIXSocketAddressTest.java\nindex d17b2013..828125a7 100644\n--- a/junixsocket-common/src/test/java/org/newsclub/net/unix/AFUNIXSocketAddressTest.java\n+++ b/junixsocket-common/src/test/java/org/newsclub/net/unix/AFUNIXSocketAddressTest.java\n@@ -19,6 +19,7 @@ package org.newsclub.net.unix;\n \n import static org.junit.jupiter.api.Assertions.assertEquals;\n import static org.junit.jupiter.api.Assertions.assertFalse;\n+import static org.junit.jupiter.api.Assertions.assertNotNull;\n import static org.junit.jupiter.api.Assertions.assertTrue;\n \n import java.io.File;\n@@ -126,4 +127,10 @@ public class AFUNIXSocketAddressTest {\n assertTrue(socatString.contains(\":\"));\n }\n }\n+\n+ @Test\n+ public void testAbstractNamespace() throws Exception {\n+ assertNotNull(AFUNIXSocketAddress.inAbstractNamespace(\"test\"));\n+ assertNotNull(AFUNIXSocketAddress.inAbstractNamespace(\"test\", 1234));\n+ }\n }\ndiff --git a/junixsocket-common/src/test/java/org/newsclub/net/unix/SelftestProvider.java b/junixsocket-common/src/test/java/org/newsclub/net/unix/SelftestProvider.java\nindex 1d9cad11..0c841222 100644\n--- a/junixsocket-common/src/test/java/org/newsclub/net/unix/SelftestProvider.java\n+++ b/junixsocket-common/src/test/java/org/newsclub/net/unix/SelftestProvider.java\n@@ -42,6 +42,8 @@ public class SelftestProvider {\n \n registerTest(\"junixsocket-common\", org.newsclub.net.unix.AFUNIXSocketAddressTest.class);\n \n+ registerTest(org.newsclub.net.unix.domain.AbstractNamespaceTest.class);\n+\n registerTest(org.newsclub.net.unix.domain.AcceptTimeoutTest.class);\n \n // AncillaryMesageTest: currently only in junixsocket-tipc\ndiff --git a/junixsocket-common/src/test/java/org/newsclub/net/unix/domain/AbstractNamespaceTest.java b/junixsocket-common/src/test/java/org/newsclub/net/unix/domain/AbstractNamespaceTest.java\nnew file mode 100644\nindex 00000000..d754a62d\n--- /dev/null\n+++ b/junixsocket-common/src/test/java/org/newsclub/net/unix/domain/AbstractNamespaceTest.java\n@@ -0,0 +1,85 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2022 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.domain;\n+\n+import static org.junit.jupiter.api.Assertions.assertEquals;\n+\n+import java.io.IOException;\n+import java.util.UUID;\n+import java.util.concurrent.CompletableFuture;\n+\n+import org.junit.jupiter.api.Test;\n+import org.newsclub.net.unix.AFSocketCapability;\n+import org.newsclub.net.unix.AFSocketCapabilityRequirement;\n+import org.newsclub.net.unix.AFUNIXServerSocket;\n+import org.newsclub.net.unix.AFUNIXSocket;\n+import org.newsclub.net.unix.AFUNIXSocketAddress;\n+import org.newsclub.net.unix.SocketTestBase;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+@AFSocketCapabilityRequirement({\n+ AFSocketCapability.CAPABILITY_UNIX_DOMAIN, AFSocketCapability.CAPABILITY_ABSTRACT_NAMESPACE})\n+@SuppressFBWarnings({\n+ \"THROWS_METHOD_THROWS_CLAUSE_THROWABLE\", \"THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION\",\n+ \"NM_SAME_SIMPLE_NAME_AS_SUPERCLASS\"})\n+public class AbstractNamespaceTest extends SocketTestBase {\n+\n+ public AbstractNamespaceTest() {\n+ super(AFUNIXAddressSpecifics.INSTANCE);\n+ }\n+\n+ private void testBind(AFUNIXSocketAddress addr) throws Exception {\n+ testBind(addr, addr);\n+ }\n+\n+ private void testBind(AFUNIXSocketAddress addr, AFUNIXSocketAddress expected) throws Exception {\n+ try (AFUNIXServerSocket serverSocket = (AFUNIXServerSocket) newServerSocket()) {\n+ serverSocket.bind(addr);\n+\n+ CompletableFuture cf = CompletableFuture.supplyAsync(() -> {\n+ AFUNIXSocket socket;\n+ try {\n+ socket = AFUNIXSocket.connectTo(addr);\n+ } catch (IOException e) {\n+ throw new IllegalStateException(e);\n+ }\n+ return socket.getRemoteSocketAddress();\n+ });\n+ AFUNIXSocket accept = serverSocket.accept();\n+ assertEquals(accept.getLocalSocketAddress(), cf.get());\n+ assertEquals(expected, cf.get());\n+ }\n+ }\n+\n+ @Test\n+ public void testBind() throws Exception {\n+ testBind(AFUNIXSocketAddress.inAbstractNamespace(\"juxtest-\" + UUID.randomUUID()));\n+ }\n+\n+ @Test\n+ public void testBindTrailingZeroes() throws Exception {\n+ // trailing zeroes should be treated like other bytes\n+ testBind(AFUNIXSocketAddress.of(new byte[] {0, 10, 0}));\n+ testBind(AFUNIXSocketAddress.of(new byte[] {0, 10, 0, 0}));\n+ testBind(AFUNIXSocketAddress.of(new byte[] {0, 'J', 0, 'U'}));\n+\n+ // any sequence of 0's -> null\n+ testBind(AFUNIXSocketAddress.of(new byte[] {0, 0, 0}), null);\n+ }\n+}\n", "FAIL_TO_PASS": ["org.newsclub.net.unix.domain.AbstractNamespaceTest.testBind", "org.newsclub.net.unix.domain.AbstractNamespaceTest.testBindTrailingZeroes"], "PASS_TO_PASS": ["org.newsclub.net.unix.AFUNIXSocketAddressTest.testAbstractNamespace"]} +{"instance_id": "clb-javac-152", "repo": "kohlschutter/junixsocket", "base_commit": "4f7667c4655712fc7371c0dbab0de5bf785e5d3d", "problem_statement": "0 treated as invalid socket\nHi! I was trying to use `AFUNIXServerSocket.newInstance(FileDescriptor.in)`, with Apache's fcgid module invoking the process with FD 0 as a bound `AF_UNIX` socket, but it throws `SocketException` with \"Not a valid socket\". This seems to be down to `socket.c` regarding FD 0 as invalid.\r\nI don't think there's any reason why 0 can't be a socket, is there (other than it usually being occupied by stdin)? And FastCGI actually depends on it.\r\nCheers!\n", "image": {"image_id": "sha256:5962f393b2102bb2455cfd24dfcd510cfa97a1ec605644d59164651f63c4a390", "pull_reference": "yutu0814/clb.eval.x86_64.kohlschutter_1776_junixsocket-97@sha256:5962f393b2102bb2455cfd24dfcd510cfa97a1ec605644d59164651f63c4a390"}, "cohort": "java_upstream11", "patch": "diff --git a/.gitignore b/.gitignore\nindex 0bef71384..2a8cdb1cd 100644\n--- a/.gitignore\n+++ b/.gitignore\n@@ -15,3 +15,5 @@ pom.xml.releaseBackup\n interpolated-pom.xml\n .eclipse-pmd\n .*.swp\n+.checkstyle\n+hs_err_pid*.log\ndiff --git a/README.md b/README.md\nindex 157bd2c9e..afcab95be 100644\n--- a/README.md\n+++ b/README.md\n@@ -1,13 +1,16 @@\n # junixsocket\n \n-junixsocket is a Java/JNI library that allows the use of [Unix Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket) (AF_UNIX sockets) from Java.\n+junixsocket is a Java/JNI library that allows the use of\n+[Unix Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket) (AF_UNIX sockets), and\n+other address/protocol families (such as [TIPC](http://tipc.io/)), from Java.\n \n ## Why it's cool\n \n * *junixsocket* is the most complete implementation of Unix Domain Sockets for the Java ecosystem.\n-* Comes with pre-built native libraries for several operating systems and platforms, including\n- macOS, Linux, Windows, Solaris, FreeBSD, NetBSD, OpenBSD, DragonFlyBSD.\n-* Supports all Java versions since Java 7\\*.\n+* Supports other socket types, such as TIPC (on Linux), as well!\n+* Comes with pre-built native libraries for most operating systems and platforms, including\n+ macOS, Linux, Windows, Solaris, FreeBSD, NetBSD, OpenBSD, DragonFlyBSD, AIX, IBM i.\n+* Supports all Java versions since Java 8.\n * Supports both the Java Socket API and NIO (`java.net.Socket`, `java.net.SocketChannel`, etc.)\n * Supports streams and datagrams.\n * Supports Remote Method Invocation (RMI) over AF_UNIX.\n@@ -23,7 +26,7 @@ junixsocket is a Java/JNI library that allows the use of [Unix Domain Sockets](h\n * Provides a selftest package with 100+ tests to ensure compatibility with any target platform.\n * Apache 2.0 licensed.\n \n-`*` (Tested up to Java 17; Java 7 support is limited to core functionality, no RMI).\n+`*` (Tested up to Java 19; support for Java 7 was dropped in version 2.5.0).\n \n ## Quick links\n \n@@ -39,8 +42,10 @@ junixsocket is a Java/JNI library that allows the use of [Unix Domain Sockets](h\n * API Javadocs\n - [The core (common) API](https://kohlschutter.github.io/junixsocket/junixsocket-common/apidocs/org.newsclub.net.unix/org/newsclub/net/unix/package-summary.html)\n - [The RMI-over-Unix-Socket API](https://kohlschutter.github.io/junixsocket/junixsocket-rmi/apidocs/org.newsclub.net.unix.rmi/org/newsclub/net/unix/rmi/package-summary.html)\n+ - [The TIPC API](https://kohlschutter.github.io/junixsocket/junixsocket-tipc/apidocs/org.newsclub.net.unix.tipc/org/newsclub/net/unix/tipc/package-summary.html)\n \n * [Unix Domain Socket Reference](https://kohlschutter.github.io/junixsocket/unixsockets.html)\n+ * [TIPC Reference](http://tipc.io)\n \n ## Licensing\n \n@@ -67,7 +72,7 @@ To include the core junixsocket functionality in your project, add the following\n \n com.kohlschutter.junixsocket\n junixsocket-core\n- 2.4.1\n+ 2.5.0\n pom\n \n ```\ndiff --git a/junixsocket-codecoverage/pom.xml b/junixsocket-codecoverage/pom.xml\nindex a032a5831..9b290857c 100644\n--- a/junixsocket-codecoverage/pom.xml\n+++ b/junixsocket-codecoverage/pom.xml\n@@ -8,7 +8,7 @@\n \n com.kohlschutter.junixsocket\n junixsocket-parent\n- 2.4.1-SNAPSHOT\n+ 2.5.0-SNAPSHOT\n ../pom.xml\n \n junixsocket-codecoverage\n@@ -63,6 +63,12 @@\n ${project.version}\n compile\n \n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-tipc\n+ ${project.version}\n+ compile\n+ \n \n com.kohlschutter.junixsocket\n junixsocket-rmi\ndiff --git a/junixsocket-common/pom.xml b/junixsocket-common/pom.xml\nindex f59300bae..4da2a16ad 100644\n--- a/junixsocket-common/pom.xml\n+++ b/junixsocket-common/pom.xml\n@@ -1,50 +1,73 @@\n \n-\n- 4.0.0\n- junixsocket-common\n- jar\n- \n- com.kohlschutter.junixsocket\n- junixsocket-parent\n- 2.4.1-SNAPSHOT\n- ../pom.xml\n- \n- junixsocket-common\n- \n- ${project.parent.basedir}\n- \n+\n+ 4.0.0\n+ junixsocket-common\n+ jar\n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-parent\n+ 2.5.0-SNAPSHOT\n+ ../pom.xml\n+ \n+ junixsocket-common\n+ \n+ ${project.parent.basedir}\n+ \n \n- The public, core API\n+ The public, core API\n \n- \n- \n- \n- maven-compiler-plugin\n- \n- \n- \n- -h\n- ${kohlschutter.project.base.directory}/junixsocket-native/src/main/c\n- \n- \n- \n- \n- \n- \n- \n- com.kohlschutter.junixsocket\n- junixsocket-native-common\n- ${project.version}\n- test\n- \n- \n- com.kohlschutter.junixsocket\n- junixsocket-native-custom\n- ${project.version}\n- test\n- default\n- \n- \n-\n+ \n+ \n+ \n+ maven-compiler-plugin\n+ \n+ \n+ \n+ -h\n+ ${kohlschutter.project.base.directory}/junixsocket-native/src/main/c\n+ \n+\n+ \n+ false\n+ \n+ \n+ \n+ org.apache.maven.plugins\n+ maven-jar-plugin\n+ \n+ \n+ \n+ test-jar\n+ \n+ \n+ \n+ \n+ \n+ org.apache.maven.plugins\n+ maven-source-plugin\n+ \n+ \n+ \n+ test-jar\n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-native-common\n+ ${project.version}\n+ test\n+ \n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-native-custom\n+ ${project.version}\n+ test\n+ default\n+ \n+ \n+\n\\ No newline at end of file\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFAddressFamily.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFAddressFamily.java\nnew file mode 100644\nindex 000000000..609dec595\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFAddressFamily.java\n@@ -0,0 +1,312 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.IOException;\n+import java.net.SocketException;\n+import java.net.URI;\n+import java.nio.channels.UnsupportedAddressTypeException;\n+import java.util.Collections;\n+import java.util.HashMap;\n+import java.util.HashSet;\n+import java.util.Map;\n+import java.util.Objects;\n+import java.util.Set;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.Nullable;\n+import org.newsclub.net.unix.AFSocketAddress.AFSocketAddressConstructor;\n+\n+/**\n+ * Describes an address family supported by junixsocket.\n+ * \n+ * @param The corresponding {@link AFSocketAddress} subclass.\n+ * @author Christian Kohlschütter\n+ */\n+public final class AFAddressFamily {\n+ private static final Map> AF_MAP = Collections.synchronizedMap(\n+ new HashMap<>());\n+ private static final Map> URI_SCHEMES = Collections.synchronizedMap(\n+ new HashMap<>());\n+ private static final AtomicBoolean DEFERRED_INIT_DONE = new AtomicBoolean(false);\n+\n+ private final int domain;\n+ private AFSocketAddressConstructor addressConstructor;\n+ private @Nullable Class addressClass;\n+ private final String juxString;\n+ private final String juxInetAddressSuffix;\n+ private final String addressClassname;\n+\n+ private String selectorProviderClassname;\n+\n+ private AFSocket.Constructor socketConstructor;\n+ private AFServerSocket.Constructor serverSocketConstructor;\n+ private AFSocketAddressConfig addressConfig;\n+\n+ static {\n+ NativeUnixSocket.isLoaded(); // trigger init\n+ }\n+\n+ private AFAddressFamily(String juxString, int domain, String addressClassname) {\n+ this.juxString = juxString;\n+ this.domain = domain; // FIXME validate\n+ this.addressClassname = addressClassname;\n+ this.juxInetAddressSuffix = \".\" + juxString + AFInetAddress.INETADDR_SUFFIX;\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ static synchronized @NonNull AFAddressFamily registerAddressFamily(\n+ String juxString, int domain, String addressClassname) {\n+ AFAddressFamily af = AF_MAP.get(juxString);\n+ if (af != null) {\n+ if (af.getDomain() != domain) {\n+ throw new IllegalStateException(\"Wrong domain for address family \" + juxString + \": \" + af\n+ .getDomain() + \" vs. \" + domain);\n+ }\n+ return (AFAddressFamily) af;\n+ }\n+\n+ af = new AFAddressFamily<>(juxString, domain, addressClassname);\n+ AF_MAP.put(juxString, af);\n+\n+ return (AFAddressFamily) af;\n+ }\n+\n+ static synchronized void triggerInit() {\n+ for (AFAddressFamily af : new HashSet<>(AF_MAP.values())) {\n+ if (af.addressClassname != null) {\n+ try {\n+ Class clz = Class.forName(af.addressClassname);\n+ clz.getMethod(\"addressFamily\").invoke(null);\n+ } catch (Exception e) {\n+ // ignore\n+ }\n+ }\n+ }\n+ }\n+\n+ static synchronized AFAddressFamily getAddressFamily(String juxString) {\n+ return AF_MAP.get(juxString);\n+ }\n+\n+ static AFAddressFamily getAddressFamily(URI uri) {\n+ checkDeferredInit();\n+ Objects.requireNonNull(uri, \"uri\");\n+ String scheme = uri.getScheme();\n+ return URI_SCHEMES.get(scheme);\n+ }\n+\n+ static void checkDeferredInit() {\n+ if (DEFERRED_INIT_DONE.compareAndSet(false, true)) {\n+ NativeUnixSocket.isLoaded();\n+ AFAddressFamily.triggerInit();\n+ }\n+ }\n+\n+ int getDomain() {\n+ return domain;\n+ }\n+\n+ String getJuxString() {\n+ return juxString;\n+ }\n+\n+ AFSocketAddressConstructor getAddressConstructor() {\n+ if (addressConstructor == null) {\n+ throw new UnsupportedAddressTypeException();\n+ }\n+ return addressConstructor;\n+ }\n+\n+ private void checkProvider() {\n+ if (socketConstructor == null && selectorProviderClassname != null) {\n+ try {\n+ Class.forName(selectorProviderClassname);\n+ } catch (ClassNotFoundException e) {\n+ // ignore\n+ }\n+ }\n+ }\n+\n+ AFSocket.Constructor getSocketConstructor() {\n+ checkProvider();\n+ if (socketConstructor == null) {\n+ throw new UnsupportedAddressTypeException();\n+ }\n+ return socketConstructor;\n+ }\n+\n+ AFServerSocket.Constructor getServerSocketConstructor() {\n+ checkProvider();\n+ if (serverSocketConstructor == null) {\n+ throw new UnsupportedAddressTypeException();\n+ }\n+ return serverSocketConstructor;\n+ }\n+\n+ Class getSocketAddressClass() {\n+ if (addressClass == null) {\n+ throw new UnsupportedAddressTypeException();\n+ }\n+ return addressClass;\n+ }\n+\n+ String getJuxInetAddressSuffix() {\n+ return juxInetAddressSuffix;\n+ }\n+\n+ /**\n+ * Registers an address family.\n+ * \n+ * @param The supported address type.\n+ * @param juxString The sockaddr_* identifier as registered in native code.\n+ * @param addressClass The supported address subclass.\n+ * @param config The address-specific config object.\n+ * @return The corresponding {@link AFAddressFamily} instance.\n+ */\n+ @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n+ public static synchronized AFAddressFamily registerAddressFamily(\n+ String juxString, //\n+ Class addressClass, AFSocketAddressConfig config) {\n+ AFAddressFamily af = getAddressFamily(juxString);\n+ if (af == null) {\n+ throw new IllegalStateException(\"Address family not supported by native code: \" + juxString);\n+ }\n+ if (af.addressClassname != null && !addressClass.getName().equals(af.addressClassname)) {\n+ throw new IllegalStateException(\"Unexpected classname for address family \" + juxString + \": \"\n+ + addressClass.getName());\n+ }\n+ if (af.addressConstructor != null || af.addressClass != null) {\n+ throw new IllegalStateException(\"Already registered: \" + juxString);\n+ }\n+ af.addressConfig = (AFSocketAddressConfig) config;\n+ af.addressConstructor = (AFSocketAddressConstructor) config.addressConstructor();\n+ af.addressClass = (Class) addressClass;\n+ af.selectorProviderClassname = config.selectorProviderClassname();\n+\n+ for (String scheme : config.uriSchemes()) {\n+ if (scheme.isEmpty()) {\n+ throw new IllegalStateException(\"Invalid URI scheme; cannot register \" + scheme + \" for \"\n+ + juxString);\n+\n+ }\n+ if (URI_SCHEMES.containsKey(scheme)) {\n+ throw new IllegalStateException(\"URI scheme already registered; cannot register \" + scheme\n+ + \" for \" + juxString);\n+ }\n+ URI_SCHEMES.put(scheme, af);\n+ }\n+\n+ return (AFAddressFamily) af;\n+ }\n+\n+ /**\n+ * Registers an implementation.\n+ * \n+ * @param The supported address type.\n+ * @param juxString The sockaddr_* identifier as registered in native code.\n+ * @param addressFamily The supported address family as registered via\n+ * {@link #registerAddressFamily(String, Class, AFSocketAddressConfig)}.\n+ * @param config The address family-specific configuration object.\n+ * @return The corresponding {@link AFAddressFamily} instance.\n+ */\n+ @SuppressWarnings({\"unchecked\", \"rawtypes\", \"PMD.ExcessiveParameterList\"})\n+ public static synchronized AFAddressFamily registerAddressFamilyImpl(\n+ String juxString, //\n+ AFAddressFamily addressFamily, //\n+ AFAddressFamilyConfig config) {\n+ Objects.requireNonNull(addressFamily);\n+ Objects.requireNonNull(config);\n+\n+ AFAddressFamily af = getAddressFamily(juxString);\n+ if (af == null) {\n+ throw new IllegalStateException(\"Unknown address family: \" + juxString);\n+ }\n+ if (addressFamily != af) { // NOPMD.CompareObjectsWithEquals\n+ throw new IllegalStateException(\"Address family inconsistency: \" + juxString);\n+ }\n+ if (af.socketConstructor != null) {\n+ throw new IllegalStateException(\"Already registered: \" + juxString);\n+ }\n+ af.socketConstructor = (AFSocket.Constructor) config.socketConstructor();\n+ af.serverSocketConstructor = (AFServerSocket.Constructor) config.serverSocketConstructor();\n+\n+ FileDescriptorCast.registerCastingProviders(config);\n+\n+ return (AFAddressFamily) af;\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ AFSocketImplExtensions initImplExtensions(AncillaryDataSupport ancillaryDataSupport) {\n+ switch (getDomain()) {\n+ case NativeUnixSocket.DOMAIN_TIPC:\n+ return (AFSocketImplExtensions) new AFTIPCSocketImplExtensions(ancillaryDataSupport);\n+ default:\n+ throw new UnsupportedOperationException();\n+ }\n+ }\n+\n+ /**\n+ * Creates a new, unconnected, unbound socket compatible with this socket address.\n+ * \n+ * @return The socket instance.\n+ * @throws IOException on error.\n+ */\n+ public AFSocket newSocket() throws IOException {\n+ try {\n+ return getSocketConstructor().newInstance(null, null);\n+ } catch (UnsupportedOperationException e) {\n+ throw (SocketException) new SocketException().initCause(e);\n+ }\n+ }\n+\n+ /**\n+ * Creates a new, unconnected, unbound server socket compatible with this socket address.\n+ * \n+ * @return The server socket instance.\n+ * @throws IOException on error.\n+ */\n+ public AFServerSocket newServerSocket() throws IOException {\n+ try {\n+ return getServerSocketConstructor().newInstance(null);\n+ } catch (UnsupportedOperationException e) {\n+ throw (SocketException) new SocketException().initCause(e);\n+ }\n+ }\n+\n+ AFSocketAddress parseURI(URI u, int overridePort) throws SocketException {\n+ if (addressConfig == null) {\n+ throw new SocketException(\"Cannot instantiate addresses of type \" + addressClass);\n+ }\n+ return addressConfig.parseURI(u, overridePort);\n+ }\n+\n+ /**\n+ * Returns the set of supported URI schemes that can be parsed to some {@link AFSocketAddress}.\n+ * \n+ * The set is dependent on which {@link AFSocketAddress} implementations are registered with\n+ * junixsocket.\n+ * \n+ * @return The set of supported URI schemes.\n+ */\n+ public static synchronized Set uriSchemes() {\n+ checkDeferredInit();\n+ return Collections.unmodifiableSet(URI_SCHEMES.keySet());\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFAddressFamilyConfig.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFAddressFamilyConfig.java\nnew file mode 100644\nindex 000000000..d1fd35de1\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFAddressFamilyConfig.java\n@@ -0,0 +1,104 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.net.DatagramSocket;\n+import java.net.ServerSocket;\n+import java.net.Socket;\n+import java.nio.channels.DatagramChannel;\n+import java.nio.channels.ServerSocketChannel;\n+import java.nio.channels.SocketChannel;\n+\n+/**\n+ * The implementation-specifics for a given address family implementation.\n+ * \n+ * @param The supported address type.\n+ * @author Christian Kohlschütter\n+ * @see AFSocketAddressConfig\n+ */\n+public abstract class AFAddressFamilyConfig {\n+\n+ /**\n+ * Constructor.\n+ */\n+ protected AFAddressFamilyConfig() {\n+ }\n+\n+ /**\n+ * Returns the implementation's {@link Socket} class.\n+ * \n+ * @return The implementation's {@link Socket} class.\n+ */\n+ protected abstract Class> socketClass();\n+\n+ /**\n+ * Returns the implementation's {@link Socket} constructor.\n+ * \n+ * @return The implementation's {@link Socket} constructor.\n+ */\n+ protected abstract AFSocket.Constructor socketConstructor();\n+\n+ /**\n+ * Returns the implementation's {@link ServerSocket} class.\n+ * \n+ * @return The implementation's {@link ServerSocket} class.\n+ */\n+ protected abstract Class> serverSocketClass();\n+\n+ /**\n+ * Returns the implementation's {@link ServerSocket} constructor.\n+ * \n+ * @return The implementation's {@link ServerSocket} constructor.\n+ */\n+ protected abstract AFServerSocket.Constructor serverSocketConstructor();\n+\n+ /**\n+ * Returns the implementation's {@link SocketChannel} class.\n+ * \n+ * @return The implementation's {@link SocketChannel} class..\n+ */\n+ protected abstract Class> socketChannelClass();\n+\n+ /**\n+ * Returns the implementation's {@link ServerSocketChannel} class.\n+ * \n+ * @return The implementation's {@link ServerSocketChannel} class.\n+ */\n+ protected abstract Class> serverSocketChannelClass();\n+\n+ /**\n+ * Returns the implementation's {@link DatagramSocket} class.\n+ * \n+ * @return The implementation's {@link DatagramSocket} class.\n+ */\n+ protected abstract Class> datagramSocketClass();\n+\n+ /**\n+ * Returns the implementation's {@link DatagramSocket} constructor.\n+ * \n+ * @return The implementation's {@link DatagramSocket} constructor.\n+ */\n+ protected abstract AFDatagramSocket.Constructor datagramSocketConstructor();\n+\n+ /**\n+ * Returns the implementation's {@link DatagramChannel} class.\n+ * \n+ * @return The implementation's {@link DatagramChannel} class.\n+ */\n+ protected abstract Class> datagramChannelClass();\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXCore.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFCore.java\nsimilarity index 70%\nrename from junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXCore.java\nrename to junixsocket-common/src/main/java/org/newsclub/net/unix/AFCore.java\nindex ad821c21e..fdc2b93e6 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXCore.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFCore.java\n@@ -29,28 +29,31 @@ import java.util.concurrent.atomic.AtomicBoolean;\n * \n * @author Christian Kohlschütter\n */\n-class AFUNIXCore extends CleanableState {\n- @SuppressWarnings(\"PMD.UseDiamondOperator\") // not in Java 7\n- private static final ThreadLocal DATAGRAMPACKET_BUFFER_TL =\n- new ThreadLocal();\n+class AFCore extends CleanableState {\n+ private static final ThreadLocal DATAGRAMPACKET_BUFFER_TL = new ThreadLocal<>();\n \n private static final int DATAGRAMPACKET_BUFFER_MIN_CAPACITY = 8192;\n private static final int DATAGRAMPACKET_BUFFER_MAX_CAPACITY = 1 * 1024 * 1024;\n \n private final AtomicBoolean closed = new AtomicBoolean(false);\n \n- protected final FileDescriptor fd;\n- protected final AncillaryDataSupport ancillaryDataSupport;\n+ final FileDescriptor fd;\n+ final AncillaryDataSupport ancillaryDataSupport;\n \n- protected AFUNIXCore(Object observed, FileDescriptor fd,\n- AncillaryDataSupport ancillaryDataSupport) {\n+ private final boolean datagramMode;\n+\n+ private boolean blocking = true;\n+\n+ AFCore(Object observed, FileDescriptor fd, AncillaryDataSupport ancillaryDataSupport,\n+ boolean datagramMode) {\n super(observed);\n+ this.datagramMode = datagramMode;\n this.fd = (fd == null) ? new FileDescriptor() : fd;\n this.ancillaryDataSupport = ancillaryDataSupport;\n }\n \n- protected AFUNIXCore(Object observed, FileDescriptor fd) {\n- this(observed, fd, null);\n+ AFCore(Object observed, FileDescriptor fd) {\n+ this(observed, fd, null, false);\n }\n \n @Override\n@@ -67,25 +70,25 @@ class AFUNIXCore extends CleanableState {\n }\n }\n \n- protected boolean isClosed() {\n+ boolean isClosed() {\n return closed.get();\n }\n \n- protected void doClose() throws IOException {\n+ void doClose() throws IOException {\n NativeUnixSocket.close(fd);\n closed.set(true);\n }\n \n- protected FileDescriptor validFdOrException() throws SocketException {\n+ FileDescriptor validFdOrException() throws SocketException {\n FileDescriptor fdesc = validFd();\n if (fdesc == null) {\n closed.set(true);\n- throw new SocketException(\"Not open\");\n+ throw new SocketClosedException(\"Not open\");\n }\n return fdesc;\n }\n \n- protected synchronized FileDescriptor validFd() {\n+ synchronized FileDescriptor validFd() {\n if (isClosed()) {\n return null;\n }\n@@ -117,10 +120,17 @@ class AFUNIXCore extends CleanableState {\n remaining = Math.min(remaining, buf.remaining());\n }\n \n+ if (!blocking) {\n+ options |= NativeUnixSocket.OPT_NON_BLOCKING;\n+ }\n+\n int pos = dst.position();\n \n int count = NativeUnixSocket.receive(fdesc, buf, pos, remaining, socketAddressBuffer, options,\n ancillaryDataSupport, 0);\n+ if (count == -1) {\n+ return count;\n+ }\n if (buf != dst) { // NOPMD\n buf.limit(count);\n dst.put(buf);\n@@ -139,40 +149,58 @@ class AFUNIXCore extends CleanableState {\n \n int write(ByteBuffer src, SocketAddress target, int options) throws IOException {\n int remaining = src.remaining();\n+\n if (remaining == 0) {\n return 0;\n }\n \n FileDescriptor fdesc = validFdOrException();\n- ByteBuffer addressTo;\n+ final ByteBuffer addressTo;\n+ final int addressToLen;\n if (target == null) {\n addressTo = null;\n+ addressToLen = 0;\n } else {\n- addressTo = AFUNIXSocketAddress.SOCKETADDRESS_BUFFER_TL.get();\n- AFUNIXSocketAddress.unwrapAddressDirectBufferInternal(addressTo, target);\n+ addressTo = AFSocketAddress.SOCKETADDRESS_BUFFER_TL.get();\n+ addressToLen = AFSocketAddress.unwrapAddressDirectBufferInternal(addressTo, target);\n }\n \n // accept \"send buffer overflow\" as packet loss\n- // and don't retry (which would slow things down quite a bit)\n- options |= NativeUnixSocket.OPT_NON_BLOCKING;\n+ // and don't retry (which may slow things down quite a bit)\n+ if (!blocking) {\n+ options |= NativeUnixSocket.OPT_NON_BLOCKING;\n+ }\n+\n+ int pos = src.position();\n \n+ boolean isDirect = src.isDirect();\n ByteBuffer buf;\n- if (src.isDirect()) {\n+ if (isDirect) {\n buf = src;\n } else {\n buf = getThreadLocalDirectByteBuffer(remaining);\n remaining = Math.min(remaining, buf.remaining());\n- buf.put(src);\n+\n+ // Java 16: buf.put(buf.position(), src, src.position(), Math.min(buf.limit(), src.limit()));\n+ int limit = src.limit();\n+ if (limit > buf.limit()) {\n+ src.limit(buf.limit());\n+ buf.put(src);\n+ src.limit(limit);\n+ } else {\n+ buf.put(src);\n+ }\n+\n buf.position(0);\n }\n- int pos = buf.position();\n-\n- int written = NativeUnixSocket.send(fdesc, buf, pos, remaining, addressTo, options,\n- ancillaryDataSupport);\n- if (written > 0) {\n- src.position(pos + written);\n+ if (datagramMode) {\n+ options |= NativeUnixSocket.OPT_DGRAM_MODE;\n }\n \n+ int written = NativeUnixSocket.send(fdesc, buf, pos, remaining, addressTo, addressToLen,\n+ options, ancillaryDataSupport);\n+ src.position(pos + written);\n+\n return written;\n }\n \n@@ -193,5 +221,10 @@ class AFUNIXCore extends CleanableState {\n \n void implConfigureBlocking(boolean block) throws IOException {\n NativeUnixSocket.configureBlocking(validFdOrException(), block);\n+ this.blocking = block;\n+ }\n+\n+ boolean isBlocking() {\n+ return blocking;\n }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFDatagramChannel.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFDatagramChannel.java\nnew file mode 100644\nindex 000000000..6f41f7c73\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFDatagramChannel.java\n@@ -0,0 +1,268 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.net.DatagramSocket;\n+import java.net.InetAddress;\n+import java.net.NetworkInterface;\n+import java.net.Socket;\n+import java.net.SocketAddress;\n+import java.net.SocketOption;\n+import java.nio.ByteBuffer;\n+import java.nio.channels.DatagramChannel;\n+import java.nio.channels.MembershipKey;\n+import java.nio.channels.spi.SelectorProvider;\n+import java.util.Set;\n+\n+import org.eclipse.jdt.annotation.Nullable;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * A {@link DatagramChannel} implementation that works with junixsocket.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFDatagramChannel extends DatagramChannel\n+ implements AFSomeSocket, AFSocketExtensions {\n+ private final AFDatagramSocket afSocket;\n+\n+ /**\n+ * Creates a new {@link AFDatagramChannel} instance.\n+ * \n+ * @param selectorProvider The corresponding {@link SelectorProvider}.\n+ * @param socket The corresponding {@link Socket}.\n+ */\n+ protected AFDatagramChannel(AFSelectorProvider selectorProvider, AFDatagramSocket socket) {\n+ super(selectorProvider);\n+ this.afSocket = socket;\n+ }\n+\n+ /**\n+ * Returns the corresponding {@link Socket}.\n+ * \n+ * @return The socket.\n+ */\n+ protected final AFDatagramSocket getAFSocket() {\n+ return afSocket;\n+ }\n+\n+ // CPD-OFF\n+\n+ @Override\n+ public final MembershipKey join(InetAddress group, NetworkInterface interf) throws IOException {\n+ throw new UnsupportedOperationException();\n+ }\n+\n+ @Override\n+ public final MembershipKey join(InetAddress group, NetworkInterface interf, InetAddress source)\n+ throws IOException {\n+ throw new UnsupportedOperationException();\n+ }\n+\n+ @Override\n+ public final AFDatagramChannel bind(SocketAddress local) throws IOException {\n+ afSocket.bind(local);\n+ return this;\n+ }\n+\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n+ @Override\n+ public final AFDatagramSocket socket() {\n+ return afSocket;\n+ }\n+\n+ /**\n+ * Returns the binding state of the socket.\n+ * \n+ * @return true if the socket successfully bound to an address\n+ */\n+ public final boolean isBound() {\n+ return afSocket.isBound();\n+ }\n+\n+ @Override\n+ public final boolean isConnected() {\n+ return afSocket.isConnected();\n+ }\n+\n+ @Override\n+ public final AFDatagramChannel connect(SocketAddress remote) throws IOException {\n+ afSocket.connect(remote);\n+ return this;\n+ }\n+\n+ @Override\n+ public final AFDatagramChannel disconnect() throws IOException {\n+ afSocket.disconnect();\n+ return this;\n+ }\n+\n+ @Override\n+ public final @Nullable A getRemoteAddress() throws IOException {\n+ return getRemoteSocketAddress();\n+ }\n+\n+ @Override\n+ public final @Nullable A getRemoteSocketAddress() {\n+ return afSocket.getRemoteSocketAddress();\n+ }\n+\n+ @Override\n+ public final @Nullable A getLocalAddress() throws IOException {\n+ return getLocalSocketAddress();\n+ }\n+\n+ @Override\n+ public final @Nullable A getLocalSocketAddress() {\n+ return afSocket.getLocalSocketAddress();\n+ }\n+\n+ @Override\n+ public final A receive(ByteBuffer dst) throws IOException {\n+ return afSocket.getAFImpl().receive(dst);\n+ }\n+\n+ @Override\n+ public final int send(ByteBuffer src, SocketAddress target) throws IOException {\n+ return afSocket.getAFImpl().send(src, target);\n+ }\n+\n+ @Override\n+ public final int read(ByteBuffer dst) throws IOException {\n+ return afSocket.getAFImpl().read(dst, null);\n+ }\n+\n+ @Override\n+ public final long read(ByteBuffer[] dsts, int offset, int length) throws IOException {\n+ if (length == 0) {\n+ return 0;\n+ }\n+ // FIXME support more than one buffer for scatter-gather access\n+ return read(dsts[offset]);\n+ }\n+\n+ @Override\n+ public final int write(ByteBuffer src) throws IOException {\n+ return afSocket.getAFImpl().write(src);\n+ }\n+\n+ @Override\n+ public final long write(ByteBuffer[] srcs, int offset, int length) throws IOException {\n+ if (length == 0) {\n+ return 0;\n+ }\n+ // FIXME support more than one buffer for scatter-gather access\n+ return write(srcs[offset]);\n+ }\n+\n+ @Override\n+ protected final void implCloseSelectableChannel() throws IOException {\n+ getAFSocket().close();\n+ }\n+\n+ @Override\n+ protected final void implConfigureBlocking(boolean block) throws IOException {\n+ getAFCore().implConfigureBlocking(block);\n+ }\n+\n+ @Override\n+ public final int getAncillaryReceiveBufferSize() {\n+ return afSocket.getAncillaryReceiveBufferSize();\n+ }\n+\n+ @Override\n+ public final void setAncillaryReceiveBufferSize(int size) {\n+ afSocket.setAncillaryReceiveBufferSize(size);\n+ }\n+\n+ @Override\n+ public final void ensureAncillaryReceiveBufferSize(int minSize) {\n+ afSocket.ensureAncillaryReceiveBufferSize(minSize);\n+ }\n+\n+ @Override\n+ public final AFDatagramChannel setOption(SocketOption name, T value)\n+ throws IOException {\n+ if (name instanceof AFSocketOption) {\n+ getAFCore().setOption((AFSocketOption) name, value);\n+ return this;\n+ }\n+ Integer optionId = SocketOptionsMapper.resolve(name);\n+ if (optionId == null) {\n+ throw new UnsupportedOperationException(\"unsupported option\");\n+ } else {\n+ afSocket.getAFImpl().setOption(optionId.intValue(), value);\n+ }\n+ return this;\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ @Override\n+ public final T getOption(SocketOption name) throws IOException {\n+ if (name instanceof AFSocketOption) {\n+ return getAFCore().getOption((AFSocketOption) name);\n+ }\n+ Integer optionId = SocketOptionsMapper.resolve(name);\n+ if (optionId == null) {\n+ throw new UnsupportedOperationException(\"unsupported option\");\n+ } else {\n+ return (T) afSocket.getAFImpl().getOption(optionId.intValue());\n+ }\n+ }\n+\n+ @Override\n+ public final Set> supportedOptions() {\n+ return SocketOptionsMapper.SUPPORTED_SOCKET_OPTIONS;\n+ }\n+\n+ final AFSocketCore getAFCore() {\n+ return afSocket.getAFImpl().getCore();\n+ }\n+\n+ @Override\n+ public final FileDescriptor getFileDescriptor() throws IOException {\n+ return afSocket.getFileDescriptor();\n+ }\n+\n+ /**\n+ * Checks if this {@link DatagramSocket}'s bound filename should be removed upon {@link #close()}.\n+ * \n+ * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n+ * namespace).\n+ * \n+ * @return {@code true} if an attempt is made to delete the socket file upon {@link #close()}.\n+ */\n+ public final boolean isDeleteOnClose() {\n+ return afSocket.isDeleteOnClose();\n+ }\n+\n+ /**\n+ * Enables/disables deleting this {@link DatagramSocket}'s bound filename upon {@link #close()}.\n+ * \n+ * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n+ * namespace).\n+ * \n+ * @param b Enabled if {@code true}.\n+ */\n+ public final void setDeleteOnClose(boolean b) {\n+ afSocket.setDeleteOnClose(b);\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFDatagramSocket.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFDatagramSocket.java\nnew file mode 100644\nindex 000000000..47a274d67\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFDatagramSocket.java\n@@ -0,0 +1,431 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.net.DatagramPacket;\n+import java.net.DatagramSocket;\n+import java.net.InetAddress;\n+import java.net.InetSocketAddress;\n+import java.net.SocketAddress;\n+import java.net.SocketException;\n+import java.net.SocketImpl;\n+import java.nio.channels.AlreadyBoundException;\n+import java.nio.channels.DatagramChannel;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+\n+import org.eclipse.jdt.annotation.Nullable;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * A {@link DatagramSocket} implementation that works with junixsocket.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFDatagramSocket extends DatagramSocket implements\n+ AFSomeSocket, AFSocketExtensions {\n+ private static final InetSocketAddress WILDCARD_ADDRESS = new InetSocketAddress(0);\n+\n+ private final AFDatagramSocketImpl impl;\n+ private final AncillaryDataSupport ancillaryDataSupport;\n+ private final AtomicBoolean created = new AtomicBoolean(false);\n+ private final AtomicBoolean deleteOnClose = new AtomicBoolean(true);\n+ private final AFDatagramChannel channel = newChannel();\n+\n+ /**\n+ * Creates a new {@link AFDatagramSocket} instance.\n+ * \n+ * @param impl The corresponding {@link SocketImpl} class.\n+ * @throws IOException on error.\n+ */\n+ protected AFDatagramSocket(final AFDatagramSocketImpl impl) throws IOException {\n+ super(impl);\n+ this.impl = impl;\n+ this.ancillaryDataSupport = impl.ancillaryDataSupport;\n+ }\n+\n+ /**\n+ * Creates a new {@link DatagramChannel} that is associated with this socket.\n+ * \n+ * @return The channel.\n+ */\n+ protected abstract AFDatagramChannel newChannel();\n+\n+ /**\n+ * Returns the {@link AncillaryDataSupport} instance.\n+ * \n+ * @return The instance.\n+ */\n+ protected final AncillaryDataSupport getAncillaryDataSupport() {\n+ return ancillaryDataSupport;\n+ }\n+\n+ /**\n+ * A reference to the constructor of an {@link AFDatagramSocket} subclass.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ */\n+ @FunctionalInterface\n+ public interface Constructor {\n+ /**\n+ * Constructs a new {@link DatagramSocket} instance.\n+ * \n+ * @param fd The file descriptor.\n+ * @return The new instance.\n+ * @throws IOException on error.\n+ */\n+ AFDatagramSocket newSocket(FileDescriptor fd) throws IOException;\n+ }\n+\n+ /**\n+ * Returns the {@link AFSocketAddress} type supported by this socket.\n+ * \n+ * @return The supported {@link AFSocketAddress}.\n+ */\n+ protected final Class socketAddressClass() {\n+ return impl.getAddressFamily().getSocketAddressClass();\n+ }\n+\n+ /**\n+ * Returns a new {@link AFDatagramSocket} instance.\n+ *\n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @param constructor The supplying constructor.\n+ * @return The new instance.\n+ * @throws IOException on error.\n+ */\n+ protected static final AFDatagramSocket newInstance(\n+ Constructor constructor) throws IOException {\n+ return constructor.newSocket(null);\n+ }\n+\n+ /**\n+ * Creates a new {@link AFDatagramSocket}.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @param constructor The supplying constructor.\n+ * @param fdObj The file descriptor.\n+ * @param localPort The local port.\n+ * @param remotePort The remote port.\n+ * @return The new instance.\n+ * @throws IOException on error.\n+ */\n+ protected static final AFDatagramSocket newInstance(\n+ Constructor constructor, FileDescriptor fdObj, int localPort, int remotePort)\n+ throws IOException {\n+ if (fdObj == null) {\n+ return newInstance(constructor);\n+ }\n+ if (!fdObj.valid()) {\n+ throw new SocketException(\"Invalid file descriptor\");\n+ }\n+\n+ int status = NativeUnixSocket.socketStatus(fdObj);\n+ if (status == NativeUnixSocket.SOCKETSTATUS_INVALID) {\n+ throw new SocketException(\"Not a valid socket\");\n+ }\n+\n+ AFDatagramSocket socket = constructor.newSocket(fdObj);\n+ socket.getAFImpl().updatePorts(localPort, remotePort);\n+\n+ switch (status) {\n+ case NativeUnixSocket.SOCKETSTATUS_CONNECTED:\n+ socket.internalDummyConnect();\n+ break;\n+ case NativeUnixSocket.SOCKETSTATUS_BOUND:\n+ socket.internalDummyBind();\n+ break;\n+ case NativeUnixSocket.SOCKETSTATUS_UNKNOWN:\n+ break;\n+ default:\n+ throw new IllegalStateException(\"Invalid socketStatus response: \" + status);\n+ }\n+\n+ return socket;\n+ }\n+\n+ @Override\n+ public final void connect(InetAddress address, int port) {\n+ throw new IllegalArgumentException(\"Cannot connect to InetAddress\");\n+ }\n+\n+ /**\n+ * Reads the next received packet without actually removing it from the queue.\n+ * \n+ * In other words, once a packet is received, calling this method multiple times in a row will not\n+ * have further effects on the packet contents.\n+ * \n+ * This call still blocks until at least one packet has been received and added to the queue.\n+ * \n+ * @param p The packet.\n+ * @throws IOException on error.\n+ */\n+ public final void peek(DatagramPacket p) throws IOException {\n+ synchronized (p) {\n+ if (isClosed()) {\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+ getAFImpl().peekData(p);\n+ }\n+ }\n+\n+ @Override\n+ public final void send(DatagramPacket p) throws IOException {\n+ synchronized (p) {\n+ if (isClosed()) {\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+ if (!isBound()) {\n+ internalDummyBind();\n+ }\n+ getAFImpl().send(p);\n+ }\n+ }\n+\n+ final void internalDummyConnect() throws SocketException {\n+ super.connect(AFSocketAddress.INTERNAL_DUMMY_DONT_CONNECT);\n+ }\n+\n+ final void internalDummyBind() throws SocketException {\n+ bind(AFSocketAddress.INTERNAL_DUMMY_BIND);\n+ }\n+\n+ @Override\n+ public final synchronized void connect(SocketAddress addr) throws SocketException {\n+ if (!isBound()) {\n+ internalDummyBind();\n+ }\n+ internalDummyConnect();\n+ try {\n+ getAFImpl().connect(AFSocketAddress.preprocessSocketAddress(socketAddressClass(), addr,\n+ null));\n+ } catch (SocketException e) {\n+ throw e;\n+ } catch (IOException e) {\n+ throw (SocketException) new SocketException(e.getMessage()).initCause(e);\n+ }\n+ }\n+\n+ @Override\n+ public final synchronized @Nullable A getRemoteSocketAddress() {\n+ return getAFImpl().getRemoteSocketAddress();\n+ }\n+\n+ @Override\n+ public final boolean isConnected() {\n+ return super.isConnected() || impl.isConnected();\n+ }\n+\n+ @Override\n+ public final boolean isBound() {\n+ return super.isBound() || impl.isBound();\n+ }\n+\n+ @Override\n+ public final void close() {\n+ // IMPORTANT This method must not be synchronized on \"this\",\n+ // otherwise we can't unblock a pending read\n+ if (isClosed()) {\n+ return;\n+ }\n+ getAFImpl().close();\n+ boolean wasBound = isBound();\n+ if (wasBound && deleteOnClose.get()) {\n+ InetAddress addr = getLocalAddress();\n+ if (AFInetAddress.isSupportedAddress(addr, addressFamily())) {\n+ try {\n+ AFSocketAddress socketAddress = AFSocketAddress.unwrap(addr, 0, addressFamily());\n+ if (socketAddress != null && socketAddress.hasFilename()) {\n+ if (!socketAddress.getFile().delete()) {\n+ // ignore\n+ }\n+ }\n+ } catch (IOException e) {\n+ // ignore\n+ }\n+ }\n+ }\n+ super.close();\n+ }\n+\n+ @Override\n+ @SuppressWarnings(\"PMD.CognitiveComplexity\")\n+ public final synchronized void bind(SocketAddress addr) throws SocketException {\n+ boolean isBound = isBound();\n+ if (isBound) {\n+ if (addr == AFSocketAddress.INTERNAL_DUMMY_BIND) { // NOPMD\n+ return;\n+ }\n+ // getAFImpl().bind(null); // try unbind (may not succeed)\n+ }\n+ if (isClosed()) {\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+ if (!isBound) {\n+ try {\n+ super.bind(AFSocketAddress.INTERNAL_DUMMY_BIND);\n+ } catch (AlreadyBoundException e) {\n+ // ignore\n+ } catch (SocketException e) {\n+ String message = e.getMessage();\n+ if (message != null && message.contains(\"already bound\")) {\n+ // ignore (Java 14 or older)\n+ } else {\n+ throw e;\n+ }\n+ }\n+ }\n+\n+ boolean isWildcardBind = WILDCARD_ADDRESS.equals(addr);\n+\n+ AFSocketAddress epoint = (addr == null || isWildcardBind) ? null : AFSocketAddress\n+ .preprocessSocketAddress(socketAddressClass(), addr, null);\n+ if (epoint instanceof SentinelSocketAddress) {\n+ return;\n+ }\n+\n+ try {\n+ getAFImpl().bind(epoint);\n+ } catch (SocketException e) {\n+ if (isWildcardBind) {\n+ // permit errors on wildcard bind\n+ } else {\n+ getAFImpl().close();\n+ throw e;\n+ }\n+ }\n+ }\n+\n+ @Override\n+ public final @Nullable A getLocalSocketAddress() {\n+ if (isClosed()) {\n+ return null;\n+ }\n+ if (!isBound()) {\n+ return null;\n+ }\n+ try {\n+ return AFSocketAddress.unwrap(getLocalAddress(), getLocalPort(), addressFamily());\n+ } catch (SocketException e) {\n+ return null;\n+ }\n+ }\n+\n+ /**\n+ * Checks if this {@link AFDatagramSocket}'s bound filename should be removed upon\n+ * {@link #close()}.\n+ * \n+ * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n+ * namespace).\n+ * \n+ * @return {@code true} if an attempt is made to delete the socket file upon {@link #close()}.\n+ */\n+ public final boolean isDeleteOnClose() {\n+ return deleteOnClose.get();\n+ }\n+\n+ /**\n+ * Enables/disables deleting this {@link AFDatagramSocket}'s bound filename upon {@link #close()}.\n+ * \n+ * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n+ * namespace).\n+ * \n+ * @param b Enabled if {@code true}.\n+ */\n+ public final void setDeleteOnClose(boolean b) {\n+ deleteOnClose.set(b);\n+ }\n+\n+ final AFDatagramSocketImpl getAFImpl() {\n+ if (created.compareAndSet(false, true)) {\n+ try {\n+ getSoTimeout(); // trigger create via java.net.Socket\n+ } catch (SocketException e) {\n+ // ignore\n+ }\n+ }\n+ return impl;\n+ }\n+\n+ final AFDatagramSocketImpl getAFImpl(boolean create) {\n+ if (create) {\n+ return getAFImpl();\n+ } else {\n+ return impl;\n+ }\n+ }\n+\n+ @Override\n+ public final int getAncillaryReceiveBufferSize() {\n+ return ancillaryDataSupport.getAncillaryReceiveBufferSize();\n+ }\n+\n+ @Override\n+ public final void setAncillaryReceiveBufferSize(int size) {\n+ ancillaryDataSupport.setAncillaryReceiveBufferSize(size);\n+ }\n+\n+ @Override\n+ public final void ensureAncillaryReceiveBufferSize(int minSize) {\n+ ancillaryDataSupport.ensureAncillaryReceiveBufferSize(minSize);\n+ }\n+\n+ @Override\n+ public final boolean isClosed() {\n+ return super.isClosed() || getAFImpl().isClosed();\n+ }\n+\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n+ @Override\n+ public AFDatagramChannel getChannel() {\n+ return channel;\n+ }\n+\n+ @Override\n+ public final FileDescriptor getFileDescriptor() throws IOException {\n+ return getAFImpl().getFileDescriptor();\n+ }\n+\n+ @Override\n+ public final void receive(DatagramPacket p) throws IOException {\n+ getAFImpl().receive(p);\n+ }\n+\n+ /**\n+ * Returns the address family supported by this implementation.\n+ * \n+ * @return The family.\n+ */\n+ protected final AFAddressFamily addressFamily() {\n+ return getAFImpl().getAddressFamily();\n+ }\n+\n+ /**\n+ * Returns the internal helper instance for address-specific extensions.\n+ * \n+ * @return The helper instance.\n+ * @throws UnsupportedOperationException if such extensions are not supported for this address\n+ * type.\n+ */\n+ protected AFSocketImplExtensions getImplExtensions() {\n+ return getAFImpl(false).getImplExtensions();\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFDatagramSocketImpl.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFDatagramSocketImpl.java\nnew file mode 100644\nindex 000000000..5294fc7e4\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFDatagramSocketImpl.java\n@@ -0,0 +1,397 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.net.DatagramPacket;\n+import java.net.DatagramSocketImpl;\n+import java.net.InetAddress;\n+import java.net.NetworkInterface;\n+import java.net.SocketAddress;\n+import java.net.SocketException;\n+import java.net.SocketTimeoutException;\n+import java.nio.ByteBuffer;\n+import java.nio.channels.ClosedChannelException;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+import java.util.concurrent.atomic.AtomicInteger;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.Nullable;\n+\n+/**\n+ * A {@link DatagramSocketImpl} implemented by junixsocket.\n+ * \n+ * @param The associated address type.\n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFDatagramSocketImpl extends\n+ DatagramSocketImplShim {\n+ private final AFSocketType socketType;\n+ private final AFSocketCore core;\n+ final AncillaryDataSupport ancillaryDataSupport = new AncillaryDataSupport();\n+ private final AtomicBoolean connected = new AtomicBoolean(false);\n+ private final AtomicBoolean bound = new AtomicBoolean(false);\n+\n+ private final AtomicInteger socketTimeout = new AtomicInteger(0);\n+ private int remotePort = 0;\n+ private final AFAddressFamily<@NonNull A> addressFamily;\n+ private AFSocketImplExtensions implExtensions = null;\n+\n+ /**\n+ * Constructs a new {@link AFDatagramSocketImpl} using the given {@link FileDescriptor} (or null\n+ * to create a new one).\n+ * \n+ * @param addressFamily The address family.\n+ * @param fd The file descriptor, or {@code null}.\n+ * @param socketType The socket type.\n+ * @throws IOException on error.\n+ */\n+ protected AFDatagramSocketImpl(AFAddressFamily<@NonNull A> addressFamily, FileDescriptor fd,\n+ AFSocketType socketType) throws IOException {\n+ super();\n+ this.addressFamily = addressFamily;\n+ // FIXME verify fd\n+ this.socketType = socketType;\n+ this.core = new AFSocketCore(this, fd, ancillaryDataSupport, getAddressFamily(), true);\n+ this.fd = core.fd;\n+ }\n+\n+ @Override\n+ protected final void create() throws SocketException {\n+ if (isClosed()) {\n+ throw new SocketException(\"Already closed\");\n+ } else if (fd.valid()) {\n+ return;\n+ }\n+ try {\n+ NativeUnixSocket.createSocket(fd, getAddressFamily().getDomain(), socketType.getId());\n+ } catch (SocketException e) {\n+ throw e;\n+ } catch (IOException e) {\n+ throw (SocketException) new SocketException(e.getMessage()).initCause(e);\n+ }\n+ }\n+\n+ @Override\n+ protected final void close() {\n+ core.runCleaner();\n+ }\n+\n+ @Override\n+ protected final void connect(InetAddress address, int port) throws SocketException {\n+ // not used; see connect(AFSocketAddress)\n+ }\n+\n+ final void connect(AFSocketAddress socketAddress) throws IOException {\n+ if (socketAddress == AFSocketAddress.INTERNAL_DUMMY_CONNECT) { // NOPMD\n+ return;\n+ }\n+ ByteBuffer ab = socketAddress.getNativeAddressDirectBuffer();\n+ NativeUnixSocket.connect(ab, ab.limit(), fd, -1);\n+ this.remotePort = socketAddress.getPort();\n+ }\n+\n+ @Override\n+ protected final void disconnect() {\n+ try {\n+ NativeUnixSocket.disconnect(fd);\n+ connected.set(false);\n+ this.remotePort = 0;\n+ } catch (IOException e) {\n+ e.printStackTrace();\n+ }\n+ }\n+\n+ final AFSocketCore getCore() {\n+ return core;\n+ }\n+\n+ @Override\n+ protected final FileDescriptor getFileDescriptor() {\n+ return core.fd;\n+ }\n+\n+ final boolean isClosed() {\n+ return core.isClosed();\n+ }\n+\n+ @Override\n+ protected final void bind(int lport, InetAddress laddr) throws SocketException {\n+ // not used; see bind(AFSocketAddress)\n+ }\n+\n+ final void bind(AFSocketAddress socketAddress) throws SocketException {\n+ if (socketAddress == AFSocketAddress.INTERNAL_DUMMY_BIND) { // NOPMD\n+ return;\n+ }\n+ try {\n+ ByteBuffer ab;\n+ if (socketAddress == null) {\n+ ab = AFSocketAddress.getNativeAddressDirectBuffer(0);\n+ } else {\n+ ab = socketAddress.getNativeAddressDirectBuffer();\n+ }\n+ NativeUnixSocket.bind(ab, ab.limit(), fd, NativeUnixSocket.OPT_DGRAM_MODE);\n+ if (socketAddress == null) {\n+ this.localPort = 0;\n+ this.bound.set(false);\n+ } else {\n+ this.localPort = socketAddress.getPort();\n+ }\n+ } catch (SocketException e) {\n+ throw e;\n+ } catch (IOException e) {\n+ throw (SocketException) new SocketException(e.getMessage()).initCause(e);\n+ }\n+ }\n+\n+ @Override\n+ protected final void receive(DatagramPacket p) throws IOException {\n+ recv(p, 0);\n+ }\n+\n+ private void recv(DatagramPacket p, int options) throws IOException {\n+ int len = p.getLength();\n+ FileDescriptor fdesc = core.validFdOrException();\n+\n+ ByteBuffer datagramPacketBuffer = core.getThreadLocalDirectByteBuffer(len);\n+ len = Math.min(len, datagramPacketBuffer.capacity());\n+\n+ options |= core.isBlocking() ? 0 : NativeUnixSocket.OPT_NON_BLOCKING;\n+\n+ ByteBuffer socketAddressBuffer = AFSocketAddress.SOCKETADDRESS_BUFFER_TL.get();\n+ int count = NativeUnixSocket.receive(fdesc, datagramPacketBuffer, 0, len, socketAddressBuffer,\n+ options, ancillaryDataSupport, socketTimeout.get());\n+ if (count > len) {\n+ throw new IllegalStateException(\"count > len: \" + count + \" > \" + len);\n+ } else if (count == -1) {\n+ throw new SocketTimeoutException();\n+ } else if (count < 0) {\n+ throw new IllegalStateException(\"count: \" + count + \" < 0\");\n+ }\n+ datagramPacketBuffer.limit(count);\n+ datagramPacketBuffer.rewind();\n+ datagramPacketBuffer.get(p.getData(), p.getOffset(), count);\n+\n+ p.setLength(count);\n+\n+ A addr = AFSocketAddress.ofInternal(socketAddressBuffer, getAddressFamily());\n+ p.setAddress(addr == null ? null : addr.getInetAddress());\n+ p.setPort(remotePort);\n+ }\n+\n+ @Override\n+ protected final void send(DatagramPacket p) throws IOException {\n+ InetAddress addr = p.getAddress();\n+ ByteBuffer sendToBuf = null;\n+ int sendToBufLen = 0;\n+ if (addr != null) {\n+ byte[] addrBytes = AFInetAddress.unwrapAddress(addr, getAddressFamily());\n+ if (addrBytes != null) {\n+ sendToBuf = AFSocketAddress.SOCKETADDRESS_BUFFER_TL.get();\n+ sendToBufLen = NativeUnixSocket.bytesToSockAddr(getAddressFamily().getDomain(), sendToBuf,\n+ addrBytes);\n+ if (sendToBufLen == -1) {\n+ throw new SocketException(\"Unsupported domain\");\n+ }\n+ }\n+ }\n+ FileDescriptor fdesc = core.validFdOrException();\n+\n+ int len = p.getLength();\n+ ByteBuffer datagramPacketBuffer = core.getThreadLocalDirectByteBuffer(len);\n+ datagramPacketBuffer.clear();\n+ datagramPacketBuffer.put(p.getData(), p.getOffset(), p.getLength());\n+ NativeUnixSocket.send(fdesc, datagramPacketBuffer, 0, len, sendToBuf, sendToBufLen,\n+ /* NativeUnixSocket.OPT_NON_BLOCKING | */\n+ NativeUnixSocket.OPT_DGRAM_MODE, ancillaryDataSupport);\n+ }\n+\n+ @Override\n+ protected final int peek(InetAddress i) throws IOException {\n+ throw new SocketException(\"Unsupported operation\");\n+ }\n+\n+ @Override\n+ protected final int peekData(DatagramPacket p) throws IOException {\n+ recv(p, NativeUnixSocket.OPT_PEEK);\n+ return 0;\n+ }\n+\n+ @Override\n+ protected final byte getTTL() throws IOException {\n+ return (byte) (getTimeToLive() & 0xFF);\n+ }\n+\n+ @Override\n+ protected final void setTTL(byte ttl) throws IOException {\n+ // ignored\n+ }\n+\n+ @Override\n+ protected final int getTimeToLive() throws IOException {\n+ return 0;\n+ }\n+\n+ @Override\n+ protected final void setTimeToLive(int ttl) throws IOException {\n+ // ignored\n+ }\n+\n+ @Override\n+ protected final void join(InetAddress inetaddr) throws IOException {\n+ throw new SocketException(\"Unsupported\");\n+ }\n+\n+ @Override\n+ protected final void leave(InetAddress inetaddr) throws IOException {\n+ throw new SocketException(\"Unsupported\");\n+ }\n+\n+ @Override\n+ protected final void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)\n+ throws IOException {\n+ throw new SocketException(\"Unsupported\");\n+ }\n+\n+ @Override\n+ protected final void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf)\n+ throws IOException {\n+ throw new SocketException(\"Unsupported\");\n+ }\n+\n+ @Override\n+ public Object getOption(int optID) throws SocketException {\n+ if (isClosed()) {\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+\n+ FileDescriptor fdesc = core.validFdOrException();\n+ return AFSocketImpl.getOptionDefault(fdesc, optID, socketTimeout, getAddressFamily());\n+ }\n+\n+ @Override\n+ public void setOption(int optID, Object value) throws SocketException {\n+ if (isClosed()) {\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+\n+ FileDescriptor fdesc = core.validFdOrException();\n+ AFSocketImpl.setOptionDefault(fdesc, optID, value, socketTimeout);\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ final A receive(ByteBuffer dst) throws IOException {\n+ try {\n+ return (A) core.receive(dst);\n+ } catch (SocketClosedException e) {\n+ throw (ClosedChannelException) new ClosedChannelException().initCause(e);\n+ }\n+ }\n+\n+ final int send(ByteBuffer src, SocketAddress target) throws IOException {\n+ try {\n+ return core.write(src, target, 0);\n+ } catch (SocketClosedException e) {\n+ throw (ClosedChannelException) new ClosedChannelException().initCause(e);\n+ }\n+ }\n+\n+ final int read(ByteBuffer dst, ByteBuffer socketAddressBuffer) throws IOException {\n+ try {\n+ return core.read(dst, socketAddressBuffer, 0);\n+ } catch (SocketClosedException e) {\n+ throw (ClosedChannelException) new ClosedChannelException().initCause(e);\n+ }\n+ }\n+\n+ final int write(ByteBuffer src) throws IOException {\n+ try {\n+ return core.write(src);\n+ } catch (SocketClosedException e) {\n+ throw (ClosedChannelException) new ClosedChannelException().initCause(e);\n+ }\n+ }\n+\n+ final boolean isConnected() {\n+ if (connected.get()) {\n+ return true;\n+ }\n+ if (isClosed()) {\n+ return false;\n+ }\n+ if (core.isConnected(false)) {\n+ connected.set(true);\n+ return true;\n+ }\n+ return false;\n+ }\n+\n+ final boolean isBound() {\n+ if (bound.get()) {\n+ return true;\n+ }\n+ if (isClosed()) {\n+ return false;\n+ }\n+ if (core.isConnected(true)) {\n+ bound.set(true);\n+ return true;\n+ }\n+ return false;\n+ }\n+\n+ final void updatePorts(int local, int remote) {\n+ this.localPort = local;\n+ this.remotePort = remote;\n+ }\n+\n+ final @Nullable A getLocalSocketAddress() {\n+ return AFSocketAddress.getSocketAddress(getFileDescriptor(), false, localPort,\n+ getAddressFamily());\n+ }\n+\n+ final @Nullable A getRemoteSocketAddress() {\n+ return AFSocketAddress.getSocketAddress(getFileDescriptor(), true, remotePort,\n+ getAddressFamily());\n+ }\n+\n+ /**\n+ * Returns the address family supported by this implementation.\n+ * \n+ * @return The family.\n+ */\n+ protected final AFAddressFamily<@NonNull A> getAddressFamily() {\n+ return addressFamily;\n+ }\n+\n+ /**\n+ * Returns the internal helper instance for address-specific extensions.\n+ * \n+ * @return The helper instance.\n+ * @throws UnsupportedOperationException if such extensions are not supported for this address\n+ * type.\n+ */\n+ protected final synchronized AFSocketImplExtensions getImplExtensions() {\n+ if (implExtensions == null) {\n+ implExtensions = addressFamily.initImplExtensions(ancillaryDataSupport);\n+ }\n+ return implExtensions;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXInetAddress.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFInetAddress.java\nsimilarity index 66%\nrename from junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXInetAddress.java\nrename to junixsocket-common/src/main/java/org/newsclub/net/unix/AFInetAddress.java\nindex d8a66bbcd..78dd4b772 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXInetAddress.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFInetAddress.java\n@@ -20,31 +20,35 @@ package org.newsclub.net.unix;\n import java.io.ByteArrayInputStream;\n import java.io.IOException;\n import java.io.ObjectInputStream;\n+import java.io.UnsupportedEncodingException;\n import java.net.DatagramPacket;\n import java.net.Inet4Address;\n import java.net.InetAddress;\n import java.net.InetSocketAddress;\n import java.net.SocketAddress;\n import java.net.SocketException;\n+import java.net.URLDecoder;\n+import java.net.URLEncoder;\n import java.net.UnknownHostException;\n import java.nio.charset.StandardCharsets;\n+import java.util.Objects;\n \n /**\n- * A workaround to create an {@link InetAddress} for an {@link AFUNIXSocketAddress}.\n+ * A workaround to create an {@link InetAddress} for an {@link AFSocketAddress}.\n * \n * {@link DatagramPacket} internally requires InetAddress compatibility. Even if it pretends to\n * accept {@link SocketAddress}es, it refuses anything other than {@link InetSocketAddress}\n * and then even stores host and port separately.\n * \n * This implementation deserializes a specially crafted {@link InetAddress} with a hostname that\n- * encodes the raw bytes of an {@link AFUNIXSocketAddress}. We do this because the deserialization\n- * code path does not attempt DNS resolution (which would fail one way or another).\n+ * encodes the raw bytes of an {@link AFSocketAddress}. We do this because the deserialization code\n+ * path does not attempt DNS resolution (which would fail one way or another).\n * \n * The hostnames we use end with \".junixsocket\", to distinguish them from regular hostnames.\n * \n * @author Christian Kohlschütter\n */\n-class AFUNIXInetAddress {\n+class AFInetAddress {\n private static final byte[] SERIALIZED_INET_ADDRESS_START = {\n (byte) 0xac, (byte) 0xed, // STREAM_MAGIC\n 0x00, 0x05, // STREAM_VERSION\n@@ -83,26 +87,33 @@ class AFUNIXInetAddress {\n };\n \n private static final char PREFIX = '[';\n- private static final String V1_SUFFIX = \".un.junixsocket\";\n+ static final String INETADDR_SUFFIX = \".junixsocket\";\n \n /**\n- * Encodes an AF_UNIX socketAddress into a string that is (somewhat) guaranteed to not be resolved\n- * by java.net code.\n+ * Encodes a junixsocket socketAddress into a string that is (somewhat) guaranteed to not be\n+ * resolved by java.net code.\n * \n * Implementation detail: The \"[\" prefix (with the corresponding \"]\" suffix missing from the\n * input) should cause an early {@link UnknownHostException} be thrown, which is caught within\n * {@link InetSocketAddress#InetSocketAddress(String, int)}, causing the hostname be marked as\n * \"unresolved\" (without an address set).\n * \n- * @param socketAddress The AF_UNIX socket address.\n+ * @param socketAddress The socket address.\n * @return A string, to be used when calling\n * {@link InetSocketAddress#InetSocketAddress(String, int)}, etc.\n */\n- static final String createUnresolvedHostname(byte[] socketAddress) {\n- StringBuilder sb = new StringBuilder(1 + socketAddress.length + V1_SUFFIX.length());\n+ static final String createUnresolvedHostname(byte[] socketAddress, AFAddressFamily af) {\n+ StringBuilder sb = new StringBuilder(1 + socketAddress.length + INETADDR_SUFFIX.length() + 8);\n sb.append(PREFIX);\n- sb.append(new String(socketAddress, StandardCharsets.ISO_8859_1));\n- sb.append(V1_SUFFIX);\n+ try {\n+ sb.append(URLEncoder.encode(new String(socketAddress, StandardCharsets.ISO_8859_1),\n+ StandardCharsets.ISO_8859_1.toString()));\n+ } catch (UnsupportedEncodingException e) {\n+ throw new IllegalStateException(e);\n+ }\n+ sb.append('.');\n+ sb.append(af.getJuxString());\n+ sb.append(INETADDR_SUFFIX);\n return sb.toString();\n }\n \n@@ -112,17 +123,16 @@ class AFUNIXInetAddress {\n * \"hostname\" field containing a hostname as returned by\n * {@link #createUnresolvedHostname(byte[])}.\n * \n- * @param socketAddress The AF_UNIX socket address.\n+ * @param socketAddress The socket address.\n * @return The {@link InetAddress}.\n */\n- static final InetAddress wrapAddress(byte[] socketAddress) {\n- // called from native code\n-\n+ static final InetAddress wrapAddress(byte[] socketAddress, AFAddressFamily af) {\n+ Objects.requireNonNull(af);\n if (socketAddress == null || socketAddress.length == 0) {\n return null;\n }\n \n- byte[] bytes = createUnresolvedHostname(socketAddress).getBytes(StandardCharsets.UTF_8);\n+ byte[] bytes = createUnresolvedHostname(socketAddress, af).getBytes(StandardCharsets.UTF_8);\n if (bytes.length > 255) {\n throw new IllegalStateException(\"Address too long\");\n }\n@@ -141,20 +151,53 @@ class AFUNIXInetAddress {\n }\n }\n \n- static final byte[] unwrapAddress(InetAddress addr) throws SocketException {\n- // called from native code\n+ static final byte[] unwrapAddress(InetAddress addr, AFAddressFamily af)\n+ throws SocketException {\n+ // FIXME\n \n- if (!isSupportedAddress(addr)) {\n+ if (!isSupportedAddress(addr, af)) {\n throw new SocketException(\"Unsupported address\");\n }\n+\n String hostname = addr.getHostName();\n- byte[] bytes = hostname.substring(1, hostname.length() - V1_SUFFIX.length()).getBytes(\n- StandardCharsets.ISO_8859_1);\n- return bytes;\n+ return unwrapAddress(hostname, af);\n+ }\n+\n+ static final byte[] unwrapAddress(String hostname, AFAddressFamily af) throws SocketException {\n+ if (!hostname.endsWith(INETADDR_SUFFIX)) {\n+ throw new SocketException(\"Unsupported address\");\n+ }\n+\n+ final int end = hostname.length() - INETADDR_SUFFIX.length();\n+ char c;\n+ int domDot = -1;\n+ for (int i = end - 1; i >= 0; i--) {\n+ c = hostname.charAt(i);\n+ if (c == '.') {\n+ domDot = i;\n+ break;\n+ }\n+ }\n+\n+ String juxString = hostname.substring(domDot + 1, end);\n+ if (AFAddressFamily.getAddressFamily(juxString) != af) { // NOPMD\n+ throw new SocketException(\"Incompatible address\");\n+ }\n+\n+ String encodedHostname = hostname.substring(1, domDot);\n+ try {\n+ return URLDecoder.decode(encodedHostname, StandardCharsets.ISO_8859_1.toString()).getBytes(\n+ StandardCharsets.ISO_8859_1);\n+ } catch (UnsupportedEncodingException e) {\n+ throw new IllegalStateException(e);\n+ }\n }\n \n- static boolean isSupportedAddress(InetAddress addr) {\n- return (addr instanceof Inet4Address) && addr.isLoopbackAddress() && addr.getHostName()\n- .endsWith(V1_SUFFIX);\n+ static boolean isSupportedAddress(InetAddress addr, AFAddressFamily af) {\n+ if (addr instanceof Inet4Address && addr.isLoopbackAddress()) {\n+ String hostname = addr.getHostName();\n+ return hostname.endsWith(af.getJuxInetAddressSuffix());\n+ }\n+ return false;\n }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFInputStream.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFInputStream.java\nnew file mode 100644\nindex 000000000..98cb2ef05\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFInputStream.java\n@@ -0,0 +1,33 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.InputStream;\n+\n+/**\n+ * An {@link InputStream} for {@link AFSocket}, etc.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFInputStream extends InputStream implements FileDescriptorAccess {\n+ AFInputStream() {\n+ super();\n+ }\n+\n+ // IMPORTANT! also see src/main/java8/org/newsclub/net/unix/AFInputStream shim\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFOutputStream.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFOutputStream.java\nnew file mode 100644\nindex 000000000..5c3a02cb3\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFOutputStream.java\n@@ -0,0 +1,52 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.io.OutputStream;\n+\n+/**\n+ * An {@link OutputStream} for {@link AFSocket}, etc.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFOutputStream extends OutputStream implements FileDescriptorAccess {\n+ AFOutputStream() {\n+ super();\n+ }\n+\n+ // IMPORTANT! also see src/main/java8/org/newsclub/net/unix/AFOutputStream shim\n+\n+ /**\n+ * Reads all bytes from the given input stream and writes the bytes to this output stream in the\n+ * order that they are read. On return, this input stream will be at end of stream. This method\n+ * does not close either stream.\n+ * \n+ * This method effectively is the reverse notation of\n+ * {@link InputStream#transferTo(OutputStream)}, which may or may not be optimized for\n+ * {@link AFSocket}s.\n+ * \n+ * @param in The {@link InputStream} to transfer from.\n+ * @return The number of bytes transferred.\n+ * @throws IOException on error.\n+ */\n+ public long transferFrom(InputStream in) throws IOException {\n+ return in.transferTo(this);\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXPipe.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFPipe.java\nsimilarity index 86%\nrename from junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXPipe.java\nrename to junixsocket-common/src/main/java/org/newsclub/net/unix/AFPipe.java\nindex 9b4b4891f..7ab1fdbb8 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXPipe.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFPipe.java\n@@ -27,22 +27,24 @@ import java.nio.channels.spi.SelectorProvider;\n import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n /**\n- * A {@link Pipe}, natively implemented. Mostly to support {@link AFUNIXSelector}.\n+ * A {@link Pipe}, natively implemented.\n * \n * @author Christian Kohlschütter\n */\n-public final class AFUNIXPipe extends Pipe implements Closeable {\n- private final AFUNIXCore sourceCore;\n- private final AFUNIXCore sinkCore;\n+public final class AFPipe extends Pipe implements Closeable {\n+ private final AFCore sourceCore;\n+ private final AFCore sinkCore;\n private final SourceChannel sourceChannel;\n private final SinkChannel sinkChannel;\n private final int options;\n \n- AFUNIXPipe(AFUNIXSelectorProvider provider, boolean selectable) throws IOException {\n+ AFPipe(AFSelectorProvider provider, boolean selectable) throws IOException {\n super();\n \n- this.sourceCore = new AFUNIXCore(this, (FileDescriptor) null);\n- this.sinkCore = new AFUNIXCore(this, (FileDescriptor) null);\n+ NativeUnixSocket.ensureSupported();\n+\n+ this.sourceCore = new AFCore(this, (FileDescriptor) null);\n+ this.sinkCore = new AFCore(this, (FileDescriptor) null);\n \n boolean isSocket = NativeUnixSocket.initPipe(sourceCore.fd, sinkCore.fd, selectable);\n this.options = isSocket ? 0 : NativeUnixSocket.OPT_NON_SOCKET;\n@@ -51,16 +53,6 @@ public final class AFUNIXPipe extends Pipe implements Closeable {\n this.sinkChannel = new SinkChannel(provider);\n }\n \n- /**\n- * Opens an {@link AFUNIXPipe}.\n- *\n- * @return The new pipe\n- * @throws IOException on error.\n- */\n- public static AFUNIXPipe open() throws IOException {\n- return AFUNIXSelectorProvider.provider().openPipe();\n- }\n-\n @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n @Override\n public SourceChannel source() {\n@@ -177,4 +169,23 @@ public final class AFUNIXPipe extends Pipe implements Closeable {\n return sinkCore.fd;\n }\n }\n+\n+ /**\n+ * Returns the options bitmask that is to be passed to native receive/send calls.\n+ * \n+ * @return The options.\n+ */\n+ int getOptions() {\n+ return options;\n+ }\n+\n+ /**\n+ * Opens an {@link AFPipe}.\n+ *\n+ * @return The new pipe\n+ * @throws IOException on error.\n+ */\n+ public static AFPipe open() throws IOException {\n+ return AFUNIXSelectorProvider.provider().openPipe();\n+ }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSelectionKey.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSelectionKey.java\nsimilarity index 67%\nrename from junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSelectionKey.java\nrename to junixsocket-common/src/main/java/org/newsclub/net/unix/AFSelectionKey.java\nindex a239a7337..d472a829a 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSelectionKey.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSelectionKey.java\n@@ -23,26 +23,27 @@ import java.nio.channels.Selector;\n import java.nio.channels.spi.AbstractSelectableChannel;\n import java.util.concurrent.atomic.AtomicBoolean;\n \n-final class AFUNIXSelectionKey extends SelectionKey {\n- private final AFUNIXSelector sel;\n- private final AFUNIXSocketCore core;\n+final class AFSelectionKey extends SelectionKey {\n+ private static final int OP_INVALID = 1 << 7; // custom\n+ private final AFSelector sel;\n+ private final AFSocketCore core;\n private int ops;\n private final SelectableChannel chann;\n private final AtomicBoolean cancelled = new AtomicBoolean();\n private int opsReady;\n \n- AFUNIXSelectionKey(AFUNIXSelector selector, AbstractSelectableChannel ch, int ops, Object att) {\n+ AFSelectionKey(AFSelector selector, AbstractSelectableChannel ch, int ops, Object att) {\n super();\n this.chann = ch;\n this.sel = selector;\n this.ops = ops; // FIXME check\n \n- if (ch instanceof AFUNIXDatagramChannel) {\n- this.core = ((AFUNIXDatagramChannel) ch).getAFCore();\n- } else if (ch instanceof AFUNIXSocketChannel) {\n- this.core = ((AFUNIXSocketChannel) ch).getAFCore();\n- } else if (ch instanceof AFUNIXServerSocketChannel) {\n- this.core = ((AFUNIXServerSocketChannel) ch).getAFCore();\n+ if (ch instanceof AFDatagramChannel) {\n+ this.core = ((AFDatagramChannel) ch).getAFCore();\n+ } else if (ch instanceof AFSocketChannel) {\n+ this.core = ((AFSocketChannel) ch).getAFCore();\n+ } else if (ch instanceof AFServerSocketChannel) {\n+ this.core = ((AFServerSocketChannel) ch).getAFCore();\n } else {\n throw new UnsupportedOperationException();\n }\n@@ -62,7 +63,11 @@ final class AFUNIXSelectionKey extends SelectionKey {\n \n @Override\n public boolean isValid() {\n- return !cancelled.get() && chann.isOpen() && sel.isOpen();\n+ return !hasOpInvalid() && !cancelled.get() && chann.isOpen() && sel.isOpen();\n+ }\n+\n+ boolean hasOpInvalid() {\n+ return (opsReady & OP_INVALID) != 0;\n }\n \n @Override\n@@ -96,14 +101,20 @@ final class AFUNIXSelectionKey extends SelectionKey {\n \n @Override\n public int readyOps() {\n- return opsReady;\n+ return opsReady & ~OP_INVALID;\n }\n \n- AFUNIXSocketCore getAFCore() {\n+ AFSocketCore getAFCore() {\n return core;\n }\n \n void setOpsReady(int opsReady) {\n this.opsReady = opsReady;\n }\n+\n+ @Override\n+ public String toString() {\n+ return super.toString() + \"[\" + readyOps() + \";valid=\" + isValid() + \";channel=\" + channel()\n+ + \"]\";\n+ }\n }\n\\ No newline at end of file\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSelector.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSelector.java\nnew file mode 100644\nindex 000000000..d1ce0a873\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSelector.java\n@@ -0,0 +1,334 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.net.SocketTimeoutException;\n+import java.nio.ByteBuffer;\n+import java.nio.channels.ClosedSelectorException;\n+import java.nio.channels.SelectableChannel;\n+import java.nio.channels.SelectionKey;\n+import java.nio.channels.Selector;\n+import java.nio.channels.spi.AbstractSelectableChannel;\n+import java.nio.channels.spi.AbstractSelector;\n+import java.util.Collection;\n+import java.util.Collections;\n+import java.util.HashSet;\n+import java.util.Iterator;\n+import java.util.Set;\n+\n+final class AFSelector extends AbstractSelector {\n+ private static AFPipe sharedSelectorPipe = null;\n+ private static PollFd sharedSelectorPipePollFd;\n+\n+ private static final ByteBuffer PIPE_MSG_WAKE_UP = ByteBuffer.allocate(1);\n+ private static final ByteBuffer PIPE_MSG_RECEIVE_BUFFER = ByteBuffer.allocateDirect(256);\n+\n+ private final Set keysRegistered = new HashSet<>();\n+\n+ @SuppressWarnings(\"unchecked\")\n+ private final Set keysView =\n+ (Set) (Set) Collections.unmodifiableSet(keysRegistered);\n+\n+ private PollFd pollFd = null;\n+\n+ private final SelectionKeySet keysSelected = new SelectionKeySet();\n+\n+ protected AFSelector(AFSelectorProvider provider) {\n+ super(provider);\n+ }\n+\n+ private static synchronized AFPipe getSharedSelectorPipe() throws IOException {\n+ if (sharedSelectorPipe == null) {\n+ sharedSelectorPipe = AFUNIXSelectorProvider.getInstance().openSelectablePipe();\n+ sharedSelectorPipePollFd = new PollFd(sharedSelectorPipe.sourceFD());\n+ }\n+ return sharedSelectorPipe;\n+ }\n+\n+ protected AFPipe selectorPipe() throws IOException {\n+ return getSharedSelectorPipe();\n+ }\n+\n+ @Override\n+ protected SelectionKey register(AbstractSelectableChannel ch, int ops, Object att) {\n+ AFSelectionKey key = new AFSelectionKey(this, ch, ops, att);\n+ synchronized (this) {\n+ pollFd = null;\n+ keysRegistered.add(key);\n+ }\n+ return key;\n+ }\n+\n+ @Override\n+ public Set keys() {\n+ return keysView;\n+ }\n+\n+ @Override\n+ public Set selectedKeys() {\n+ return keysSelected;\n+ }\n+\n+ @Override\n+ public int selectNow() throws IOException {\n+ return select0(0);\n+ }\n+\n+ @Override\n+ public int select(long timeout) throws IOException {\n+ if (timeout > Integer.MAX_VALUE) {\n+ timeout = Integer.MAX_VALUE;\n+ } else if (timeout < 0) {\n+ throw new IllegalArgumentException(\"Timeout must not be negative\");\n+ }\n+\n+ return select0((int) timeout);\n+ }\n+\n+ @Override\n+ public int select() throws IOException {\n+ try {\n+ return select0(-1);\n+ } catch (SocketTimeoutException e) {\n+ return 0;\n+ }\n+ }\n+\n+ @SuppressWarnings(\"PMD.CognitiveComplexity\")\n+ private int select0(int timeout) throws IOException {\n+ PollFd pfd;\n+ synchronized (this) {\n+ if (!isOpen()) {\n+ throw new ClosedSelectorException();\n+ }\n+ pfd = pollFd = initPollFd(pollFd);\n+ keysSelected.clear();\n+ }\n+ int num;\n+ try {\n+ begin();\n+ num = NativeUnixSocket.poll(pfd, timeout);\n+ } finally {\n+ end();\n+ }\n+ synchronized (this) {\n+ pfd = pollFd;\n+ if (pfd != null) {\n+ AFSelectionKey[] keys = pfd.keys;\n+ if (keys != null) {\n+ for (AFSelectionKey key : keys) {\n+ if (key != null && key.hasOpInvalid()) {\n+ SelectableChannel ch = key.channel();\n+ if (ch != null && ch.isOpen()) {\n+ ch.close();\n+ }\n+ }\n+ }\n+ }\n+ }\n+ if (num > 0) {\n+ consumeAllBytesAfterPoll();\n+ setOpsReady();\n+ }\n+ return keysSelected.size();\n+ }\n+ }\n+\n+ private synchronized void consumeAllBytesAfterPoll() throws IOException {\n+ if (pollFd == null) {\n+ return;\n+ }\n+ if ((pollFd.rops[0] & SelectionKey.OP_READ) == 0) {\n+ return;\n+ }\n+ int maxReceive;\n+ int bytesReceived;\n+\n+ int options = selectorPipe().getOptions();\n+\n+ synchronized (PIPE_MSG_RECEIVE_BUFFER) {\n+ PIPE_MSG_RECEIVE_BUFFER.clear();\n+ maxReceive = PIPE_MSG_RECEIVE_BUFFER.remaining();\n+ bytesReceived = NativeUnixSocket.receive(pollFd.fds[0], PIPE_MSG_RECEIVE_BUFFER, 0,\n+ maxReceive, null, options, null, 1);\n+ }\n+\n+ if (bytesReceived == maxReceive && maxReceive > 0) {\n+ // consume all pending bytes\n+ int read;\n+ do {\n+ if ((read = NativeUnixSocket.poll(sharedSelectorPipePollFd, 0)) > 0) {\n+ synchronized (PIPE_MSG_RECEIVE_BUFFER) {\n+ PIPE_MSG_RECEIVE_BUFFER.clear();\n+ read = NativeUnixSocket.receive(sharedSelectorPipePollFd.fds[0],\n+ PIPE_MSG_RECEIVE_BUFFER, 0, maxReceive, null, options, null, 1);\n+ }\n+ }\n+ } while (read == maxReceive && read > 0);\n+ }\n+ }\n+\n+ private synchronized void setOpsReady() {\n+ if (pollFd == null) {\n+ return;\n+ }\n+ for (int i = 1; i < pollFd.rops.length; i++) {\n+ int rops = pollFd.rops[i];\n+ if (rops == 0) {\n+ continue;\n+ }\n+ AFSelectionKey key = pollFd.keys[i];\n+ key.setOpsReady(rops);\n+ keysSelected.add0(key);\n+ }\n+ }\n+\n+ @SuppressWarnings(\"resource\")\n+ private PollFd initPollFd(PollFd existingPollFd) throws IOException {\n+ synchronized (this) {\n+ for (Iterator it = keysRegistered.iterator(); it.hasNext();) {\n+ AFSelectionKey key = it.next();\n+ if (!key.getAFCore().fd.valid()) {\n+ key.cancelNoRemove();\n+ it.remove();\n+ existingPollFd = null;\n+ }\n+ }\n+\n+ if (existingPollFd != null) {\n+ return existingPollFd;\n+ }\n+\n+ int size = keysRegistered.size() + 1;\n+ FileDescriptor[] fds = new FileDescriptor[size];\n+ int[] ops = new int[size];\n+\n+ AFSelectionKey[] keys = new AFSelectionKey[size];\n+ fds[0] = selectorPipe().sourceFD();\n+ ops[0] = SelectionKey.OP_READ;\n+\n+ int i = 1;\n+ for (AFSelectionKey key : keysRegistered) {\n+ keys[i] = key;\n+ fds[i] = key.getAFCore().fd;\n+ ops[i] = key.interestOps();\n+ i++;\n+ }\n+ return new PollFd(keys, fds, ops);\n+ }\n+ }\n+\n+ @Override\n+ protected void implCloseSelector() throws IOException {\n+ wakeup();\n+ synchronized (this) {\n+ for (AFSelectionKey key : keysRegistered) {\n+ key.cancelNoRemove();\n+ }\n+ keysRegistered.clear();\n+ }\n+ }\n+\n+ @Override\n+ public Selector wakeup() {\n+ if (isOpen()) {\n+ try {\n+ synchronized (PIPE_MSG_WAKE_UP) {\n+ PIPE_MSG_WAKE_UP.clear();\n+ selectorPipe().sink().write(PIPE_MSG_WAKE_UP);\n+ }\n+ } catch (IOException e) {\n+ // FIXME throw as runtimeexception?\n+ e.printStackTrace();\n+ }\n+ }\n+ return this;\n+ }\n+\n+ synchronized void remove(AFSelectionKey key) {\n+ deregister(key);\n+ keysRegistered.remove(key);\n+ keysSelected.remove(key);\n+ pollFd = null;\n+ }\n+\n+ private void deregister(AFSelectionKey key) {\n+ // super.deregister unnecessarily casts SelectionKey to AbstractSelectionKey, and\n+ // ((AbstractSelectableChannel)key.channel()).removeKey(key); is not visible.\n+ // so we have to resort to some JNI trickery...\n+ try {\n+ NativeUnixSocket.deregisterSelectionKey((AbstractSelectableChannel) key.channel(), key);\n+ } catch (ClassCastException e) {\n+ // because our key isn't an AbstractSelectableKey, internal invalidation fails\n+ // but at that point, the key is deregistered\n+ }\n+ }\n+\n+ static final class PollFd {\n+ // accessed from native code\n+ final FileDescriptor[] fds;\n+ // accessed from native code\n+ final int[] ops;\n+ // accessed from native code\n+ final int[] rops;\n+\n+ final AFSelectionKey[] keys;\n+\n+ PollFd(FileDescriptor pipeSourceFd) {\n+ this(pipeSourceFd, SelectionKey.OP_READ);\n+ }\n+\n+ PollFd(FileDescriptor pipeSourceFd, int op) {\n+ this.fds = new FileDescriptor[] {pipeSourceFd};\n+ this.ops = new int[] {op};\n+ this.rops = new int[1];\n+ this.keys = null;\n+ }\n+\n+ @SuppressWarnings(\"PMD.ArrayIsStoredDirectly\")\n+ PollFd(AFSelectionKey[] keys, FileDescriptor[] fds, int[] ops) {\n+ this.keys = keys;\n+ if (fds.length != ops.length) {\n+ throw new IllegalStateException();\n+ }\n+ this.fds = fds;\n+ this.ops = ops;\n+ this.rops = new int[ops.length];\n+ }\n+ }\n+\n+ private static final class SelectionKeySet extends HashSet {\n+ private static final long serialVersionUID = 1L;\n+\n+ @Override\n+ public boolean add(SelectionKey e) {\n+ throw new UnsupportedOperationException();\n+ }\n+\n+ private void add0(SelectionKey e) {\n+ super.add(e);\n+ }\n+\n+ @Override\n+ public boolean addAll(Collection c) {\n+ throw new UnsupportedOperationException();\n+ }\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSelectorProvider.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSelectorProvider.java\nnew file mode 100644\nindex 000000000..e7c0d9b10\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSelectorProvider.java\n@@ -0,0 +1,194 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.IOException;\n+import java.net.ProtocolFamily;\n+import java.net.SocketAddress;\n+import java.nio.channels.spi.AbstractSelector;\n+import java.nio.channels.spi.SelectorProvider;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+\n+/**\n+ * Service-provider class for junixsocket selectors and selectable channels.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ */\n+public abstract class AFSelectorProvider extends SelectorProvider {\n+\n+ /**\n+ * Constructs a new {@link AFSelectorProvider}.\n+ */\n+ protected AFSelectorProvider() {\n+ super();\n+ }\n+\n+ /**\n+ * Constructs a new pipe.\n+ * \n+ * @param selectable {@code true} if the pipe should be selectable.\n+ * @return The pipe.\n+ * @throws IOException on error.\n+ */\n+ private AFPipe newPipe(boolean selectable) throws IOException {\n+ return new AFPipe(this, selectable);\n+ }\n+\n+ /**\n+ * Constructs a new socket pair from two sockets.\n+ * \n+ * @param The type of the pair.\n+ * @param s1 Some socket, the first one.\n+ * @param s2 Some socket, the second one.\n+ * @return The pair.\n+ */\n+ protected abstract AFSocketPair newSocketPair(Y s1, Y s2);\n+\n+ /**\n+ * Constructs a new socket.\n+ * \n+ * @return The socket instance.\n+ * @throws IOException on error.\n+ */\n+ protected abstract AFSocket newSocket() throws IOException;\n+\n+ /**\n+ * Returns the protocol family supported by this implementation.\n+ * \n+ * @return The protocol family.\n+ */\n+ protected abstract ProtocolFamily protocolFamily();\n+\n+ /**\n+ * Returns the address family supported by this implementation.\n+ * \n+ * @return The address family.\n+ */\n+ protected abstract AFAddressFamily<@NonNull A> addressFamily();\n+\n+ /**\n+ * Returns the domain ID for the supported protocol, as specified by {@link NativeUnixSocket}.\n+ * \n+ * @return The domain ID.\n+ */\n+ protected final int domainId() {\n+ return addressFamily().getDomain();\n+ }\n+\n+ /**\n+ * Opens a socket pair of interconnected channels.\n+ * \n+ * @return The new channel pair.\n+ * @throws IOException on error.\n+ */\n+ @SuppressWarnings(\"resource\")\n+ public AFSocketPair> openSocketChannelPair() throws IOException {\n+ AFSocketChannel s1 = openSocketChannel();\n+ AFSocketChannel s2 = openSocketChannel();\n+\n+ NativeUnixSocket.socketPair(domainId(), NativeUnixSocket.SOCK_STREAM, s1.getAFCore().fd, s2\n+ .getAFCore().fd);\n+\n+ s1.socket().internalDummyConnect();\n+ s2.socket().internalDummyConnect();\n+\n+ return newSocketPair(s1, s2);\n+ }\n+\n+ /**\n+ * Opens a socket pair of interconnected datagram channels.\n+ * \n+ * @return The new channel pair.\n+ * @throws IOException on error.\n+ */\n+ @SuppressWarnings(\"resource\")\n+ public AFSocketPair> openDatagramChannelPair() throws IOException {\n+ ProtocolFamily pf = protocolFamily();\n+ AFDatagramChannel s1 = openDatagramChannel(pf);\n+ AFDatagramChannel s2 = openDatagramChannel(pf);\n+\n+ NativeUnixSocket.socketPair(domainId(), NativeUnixSocket.SOCK_STREAM, s1.getAFCore().fd, s2\n+ .getAFCore().fd);\n+\n+ s1.socket().internalDummyBind();\n+ s2.socket().internalDummyBind();\n+ s1.socket().internalDummyConnect();\n+ s2.socket().internalDummyConnect();\n+\n+ return newSocketPair(s1, s2);\n+ }\n+\n+ @Override\n+ public abstract AFDatagramChannel openDatagramChannel() throws IOException;\n+\n+ @Override\n+ public AFDatagramChannel openDatagramChannel(ProtocolFamily family) throws IOException {\n+ if (!protocolFamily().name().equals(family.name())) {\n+ throw new UnsupportedOperationException(\"Unsupported protocol family\");\n+ }\n+ return openDatagramChannel();\n+ }\n+\n+ @Override\n+ public final AFPipe openPipe() throws IOException {\n+ return newPipe(false);\n+ }\n+\n+ /**\n+ * Opens a pipe with support for selectors.\n+ * \n+ * @return The new pipe\n+ * @throws IOException on error.\n+ */\n+ final AFPipe openSelectablePipe() throws IOException {\n+ return newPipe(true);\n+ }\n+\n+ @Override\n+ public final AbstractSelector openSelector() throws IOException {\n+ return new AFSelector(this);\n+ }\n+\n+ @Override\n+ public abstract AFServerSocketChannel openServerSocketChannel() throws IOException;\n+\n+ /**\n+ * Opens a server-socket channel bound on the given {@link SocketAddress}.\n+ *\n+ * @param sa The socket address to bind on.\n+ * @return The new channel\n+ * @throws IOException on error.\n+ */\n+ public abstract AFServerSocketChannel openServerSocketChannel(SocketAddress sa)\n+ throws IOException;\n+\n+ @Override\n+ public AFSocketChannel openSocketChannel() throws IOException {\n+ return newSocket().getChannel();\n+ }\n+\n+ /**\n+ * Opens a socket channel connected to the given {@link SocketAddress}.\n+ * \n+ * @param sa The socket address to connect to.\n+ * @return The new channel\n+ * @throws IOException on error.\n+ */\n+ public abstract AFSocketChannel openSocketChannel(SocketAddress sa) throws IOException;\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFServerSocket.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFServerSocket.java\nnew file mode 100644\nindex 000000000..dce1330d2\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFServerSocket.java\n@@ -0,0 +1,502 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.Closeable;\n+import java.io.File;\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.net.ServerSocket;\n+import java.net.SocketAddress;\n+import java.net.SocketException;\n+import java.nio.channels.IllegalBlockingModeException;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.Nullable;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * The server part of a junixsocket socket.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFServerSocket extends ServerSocket implements\n+ FileDescriptorAccess {\n+ private final AFSocketImpl implementation;\n+ private @Nullable A boundEndpoint;\n+ private final Closeables closeables = new Closeables();\n+ private final AtomicBoolean created = new AtomicBoolean(false);\n+ private final AtomicBoolean deleteOnClose = new AtomicBoolean(true);\n+ private final AFServerSocketChannel channel = newChannel();\n+ private @Nullable SocketAddressFilter bindFilter;\n+\n+ /**\n+ * The constructor of the concrete subclass.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ */\n+ public interface Constructor {\n+ /**\n+ * Creates a new {@link AFServerSocket} instance.\n+ * \n+ * @param fd The file descriptor.\n+ * @return The new instance.\n+ * @throws IOException on error.\n+ */\n+ @NonNull\n+ AFServerSocket newInstance(FileDescriptor fd) throws IOException;\n+ }\n+\n+ /**\n+ * Constructs a new, unconnected instance.\n+ * \n+ * @throws IOException if the operation fails.\n+ */\n+ protected AFServerSocket() throws IOException {\n+ this(null);\n+ }\n+\n+ /**\n+ * Constructs a new instance, optionally associated with the given file descriptor.\n+ * \n+ * @param fdObj The file descriptor, or {@code null}.\n+ * @throws IOException if the operation fails.\n+ */\n+ protected AFServerSocket(FileDescriptor fdObj) throws IOException {\n+ super();\n+ this.implementation = newImpl(fdObj);\n+ NativeUnixSocket.initServerImpl(this, implementation);\n+\n+ setReuseAddress(true);\n+ }\n+\n+ /**\n+ * Creates a new AFServerSocketChannel for this socket.\n+ * \n+ * @return The new instance.\n+ */\n+ protected abstract AFServerSocketChannel newChannel();\n+\n+ /**\n+ * Creates a new AFSocketImpl.\n+ * \n+ * @param fdObj The file descriptor.\n+ * @return The new instance.\n+ * @throws IOException on error.\n+ */\n+ protected abstract AFSocketImpl newImpl(FileDescriptor fdObj) throws IOException;\n+\n+ /**\n+ * Creates a new AFServerSocket instance, using the given subclass constructor.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @param instanceSupplier The subclass constructor.\n+ * @return The new instance.\n+ * @throws IOException on error.\n+ */\n+ protected static AFServerSocket newInstance(\n+ Constructor instanceSupplier) throws IOException {\n+ return instanceSupplier.newInstance(null);\n+ }\n+\n+ /**\n+ * Creates a new AFServerSocket instance, using the given subclass constructor.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @param instanceSupplier The subclass constructor.\n+ * @param fdObj The file descriptor.\n+ * @param localPort The local port.\n+ * @param remotePort The remote port.\n+ * @return The new instance.\n+ * @throws IOException on error.\n+ */\n+ protected static AFServerSocket newInstance(\n+ Constructor instanceSupplier, FileDescriptor fdObj, int localPort, int remotePort)\n+ throws IOException {\n+ if (fdObj == null) {\n+ return instanceSupplier.newInstance(null);\n+ }\n+\n+ int status = NativeUnixSocket.socketStatus(fdObj);\n+ if (!fdObj.valid() || status == NativeUnixSocket.SOCKETSTATUS_INVALID) {\n+ throw new SocketException(\"Not a valid socket\");\n+ }\n+ AFServerSocket socket = instanceSupplier.newInstance(fdObj);\n+ socket.getAFImpl().updatePorts(localPort, remotePort);\n+\n+ switch (status) {\n+ case NativeUnixSocket.SOCKETSTATUS_CONNECTED:\n+ throw new SocketException(\"Not a ServerSocket\");\n+ case NativeUnixSocket.SOCKETSTATUS_BOUND:\n+ socket.bind(AFSocketAddress.INTERNAL_DUMMY_BIND);\n+\n+ socket.setBoundEndpoint(AFSocketAddress.getSocketAddress(fdObj, false, localPort, socket\n+ .addressFamily()));\n+ break;\n+ case NativeUnixSocket.SOCKETSTATUS_UNKNOWN:\n+ break;\n+ default:\n+ throw new IllegalStateException(\"Invalid socketStatus response: \" + status);\n+ }\n+\n+ socket.getAFImpl().setSocketAddress(socket.getLocalSocketAddress());\n+ return socket;\n+ }\n+\n+ /**\n+ * Returns a new {@link ServerSocket} that is bound to the given {@link AFSocketAddress}.\n+ * \n+ * @param instanceSupplier The constructor of the concrete subclass.\n+ * @param addr The socket file to bind to.\n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @return The new, bound {@link AFServerSocket}.\n+ * @throws IOException if the operation fails.\n+ */\n+ protected static AFServerSocket bindOn(\n+ Constructor instanceSupplier, final AFSocketAddress addr) throws IOException {\n+ AFServerSocket socket = instanceSupplier.newInstance(null);\n+ socket.bind(addr);\n+ return socket;\n+ }\n+\n+ /**\n+ * Returns a new {@link ServerSocket} that is bound to the given {@link AFSocketAddress}.\n+ * \n+ * @param instanceSupplier The constructor of the concrete subclass.\n+ * @param addr The socket file to bind to.\n+ * @param deleteOnClose If {@code true}, the socket file (if the address points to a file) will be\n+ * deleted upon {@link #close}.\n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @return The new, bound {@link AFServerSocket}.\n+ * @throws IOException if the operation fails.\n+ */\n+ protected static AFServerSocket bindOn(\n+ Constructor instanceSupplier, final A addr, boolean deleteOnClose) throws IOException {\n+ AFServerSocket socket = instanceSupplier.newInstance(null);\n+ socket.bind(addr);\n+ socket.setDeleteOnClose(deleteOnClose);\n+ return socket;\n+ }\n+\n+ /**\n+ * Returns a new, unbound {@link ServerSocket} that will always bind to the given\n+ * address, regardless of any socket address used in a call to bind.\n+ * \n+ * @param instanceSupplier The constructor of the concrete subclass.\n+ * @param forceAddr The address to use.\n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @return The new, yet unbound {@link AFServerSocket}.\n+ * @throws IOException if an exception occurs.\n+ */\n+ protected static AFServerSocket forceBindOn(\n+ Constructor instanceSupplier, final A forceAddr) throws IOException {\n+ AFServerSocket socket = instanceSupplier.newInstance(null);\n+ return socket.forceBindAddress(forceAddr);\n+ }\n+\n+ /**\n+ * Forces the address to be used for any subsequent call to {@link #bind(SocketAddress)} to be the\n+ * given one, regardless of what'll be passed to {@link #bind(SocketAddress, int)}, but doesn't\n+ * bind yet.\n+ * \n+ * @param endpoint The forced endpoint address.\n+ * @return This {@link AFServerSocket}.\n+ */\n+ public final AFServerSocket forceBindAddress(SocketAddress endpoint) {\n+ return bindHook((SocketAddress orig) -> {\n+ return orig == null ? null : endpoint;\n+ });\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ @Override\n+ public final void bind(SocketAddress endpoint, int backlog) throws IOException {\n+ if (isClosed()) {\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+\n+ boolean bindErrorOk;\n+ if (bindFilter != null) {\n+ endpoint = bindFilter.apply(endpoint);\n+ bindErrorOk = endpoint != null && isBound();\n+ } else {\n+ bindErrorOk = false;\n+ }\n+\n+ if (!(endpoint instanceof AFSocketAddress)) {\n+ throw new IllegalArgumentException(\"Can only bind to endpoints of type \"\n+ + AFSocketAddress.class.getName() + \": \" + endpoint);\n+ }\n+ A endpointCast;\n+ try {\n+ endpointCast = (A) endpoint;\n+ } catch (ClassCastException e) {\n+ throw new IllegalArgumentException(\"Can only bind to specific endpoints\", e);\n+ }\n+\n+ try {\n+ getAFImpl().bind(endpoint, getReuseAddress() ? NativeUnixSocket.BIND_OPT_REUSE : 0);\n+ } catch (SocketException e) {\n+ if (bindErrorOk) {\n+ // force-binding an address could mean double-binding the same address, that's OK.\n+ return;\n+ } else {\n+ throw e;\n+ }\n+ }\n+ setBoundEndpoint(endpointCast);\n+\n+ if (endpoint == AFSocketAddress.INTERNAL_DUMMY_BIND) { // NOPMD\n+ return;\n+ }\n+\n+ implementation.listen(backlog);\n+ }\n+\n+ @Override\n+ public final boolean isBound() {\n+ return boundEndpoint != null;\n+ }\n+\n+ @Override\n+ public final boolean isClosed() {\n+ return super.isClosed() || (isBound() && !implementation.getFD().valid());\n+ }\n+\n+ @Override\n+ public AFSocket accept() throws IOException {\n+ return accept1(true);\n+ }\n+\n+ AFSocket accept1(boolean throwOnFail) throws IOException {\n+ AFSocket as = newSocketInstance();\n+\n+ boolean success = implementation.accept0(as.getAFImpl(false));\n+ if (isClosed()) {\n+ // We may have connected to the socket to unblock it\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+\n+ if (!success) {\n+ if (throwOnFail) {\n+ if (getChannel().isBlocking()) {\n+ // unexpected\n+ return null;\n+ } else {\n+ // non-blocking socket, nothing to accept\n+ throw new IllegalBlockingModeException();\n+ }\n+ } else {\n+ return null;\n+ }\n+ }\n+\n+ as.getAFImpl(true); // trigger create\n+ as.connect(AFSocketAddress.INTERNAL_DUMMY_CONNECT);\n+ as.getAFImpl().updatePorts(getAFImpl().getLocalPort1(), getAFImpl().getRemotePort());\n+\n+ return as;\n+ }\n+\n+ /**\n+ * Returns a new {@link AFSocket} instance.\n+ * \n+ * @return The new instance.\n+ * @throws IOException on error.\n+ */\n+ protected abstract AFSocket newSocketInstance() throws IOException;\n+\n+ @Override\n+ public String toString() {\n+ return getClass().getSimpleName() + \"[\" + (isBound() ? boundEndpoint : \"unbound\") + \"]\";\n+ }\n+\n+ @Override\n+ public synchronized void close() throws IOException {\n+ if (isClosed()) {\n+ return;\n+ }\n+\n+ AFSocketAddress endpoint = boundEndpoint;\n+\n+ IOException superException = null;\n+ try {\n+ super.close();\n+ } catch (IOException e) {\n+ superException = e;\n+ }\n+ if (implementation != null) {\n+ try {\n+ implementation.close();\n+ } catch (IOException e) {\n+ if (superException == null) {\n+ superException = e;\n+ } else {\n+ superException.addSuppressed(e);\n+ }\n+ }\n+ }\n+\n+ IOException ex = null;\n+ try {\n+ closeables.close(superException);\n+ } finally {\n+ if (endpoint != null && endpoint.hasFilename() && isDeleteOnClose()) {\n+ File f = endpoint.getFile();\n+ if (!f.delete() && f.exists()) {\n+ ex = new IOException(\"Could not delete socket file after close: \" + f);\n+ }\n+ }\n+ }\n+ if (ex != null) {\n+ throw ex;\n+ }\n+ }\n+\n+ /**\n+ * Registers a {@link Closeable} that should be closed when this socket is closed.\n+ * \n+ * @param closeable The closeable.\n+ */\n+ public final void addCloseable(Closeable closeable) {\n+ closeables.add(closeable);\n+ }\n+\n+ /**\n+ * Unregisters a previously registered {@link Closeable}.\n+ * \n+ * @param closeable The closeable.\n+ */\n+ public final void removeCloseable(Closeable closeable) {\n+ closeables.remove(closeable);\n+ }\n+\n+ /**\n+ * Checks whether everything is setup to support junixsocket sockets.\n+ * \n+ * @return {@code true} if supported.\n+ */\n+ public static boolean isSupported() {\n+ return NativeUnixSocket.isLoaded();\n+ }\n+\n+ @Override\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n+ public final @Nullable A getLocalSocketAddress() {\n+ if (boundEndpoint == null) {\n+ setBoundEndpoint(getAFImpl().getLocalSocketAddress());\n+ }\n+ return boundEndpoint;\n+ }\n+\n+ final void setBoundEndpoint(@Nullable A addr) {\n+ this.boundEndpoint = addr;\n+ int port;\n+ if (addr == null) {\n+ port = -1;\n+ } else {\n+ port = addr.getPort();\n+ }\n+ getAFImpl().updatePorts(port, -1);\n+ }\n+\n+ @Override\n+ public final int getLocalPort() {\n+ if (boundEndpoint == null) {\n+ setBoundEndpoint(getAFImpl().getLocalSocketAddress());\n+ }\n+ if (boundEndpoint == null) {\n+ return -1;\n+ } else {\n+ return getAFImpl().getLocalPort1();\n+ }\n+ }\n+\n+ /**\n+ * Checks if this {@link AFServerSocket}'s file should be removed upon {@link #close()}.\n+ * \n+ * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n+ * namespace).\n+ * \n+ * @return {@code true} if an attempt is made to delete the socket file upon {@link #close()}.\n+ */\n+ public final boolean isDeleteOnClose() {\n+ return deleteOnClose.get();\n+ }\n+\n+ /**\n+ * Enables/disables deleting this {@link AFServerSocket}'s file (or other resource type) upon\n+ * {@link #close()}.\n+ * \n+ * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n+ * namespace).\n+ * \n+ * @param b Enabled if {@code true}.\n+ */\n+ public final void setDeleteOnClose(boolean b) {\n+ deleteOnClose.set(b);\n+ }\n+\n+ final AFSocketImpl getAFImpl() {\n+ if (created.compareAndSet(false, true)) {\n+ try {\n+ getSoTimeout(); // trigger create via java.net.Socket\n+ } catch (IOException e) {\n+ // ignore\n+ }\n+ }\n+ return implementation;\n+ }\n+\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n+ @Override\n+ public AFServerSocketChannel getChannel() {\n+ return channel;\n+ }\n+\n+ @Override\n+ public final FileDescriptor getFileDescriptor() throws IOException {\n+ return implementation.getFileDescriptor();\n+ }\n+\n+ /**\n+ * Returns the address family supported by this implementation.\n+ * \n+ * @return The family.\n+ */\n+ protected final AFAddressFamily addressFamily() {\n+ return getAFImpl().getAddressFamily();\n+ }\n+\n+ /**\n+ * Sets the hook for any subsequent call to {@link #bind(SocketAddress)} and\n+ * {@link #bind(SocketAddress, int)} to be the given function.\n+ * \n+ * The function can monitor calls or even alter the endpoint address.\n+ * \n+ * @param hook The function that gets called for each {@code bind} call.\n+ * @return This instance.\n+ */\n+ public final AFServerSocket bindHook(SocketAddressFilter hook) {\n+ this.bindFilter = hook;\n+ return this;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFServerSocketChannel.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFServerSocketChannel.java\nnew file mode 100644\nindex 000000000..dd021d1cb\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFServerSocketChannel.java\n@@ -0,0 +1,135 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.net.ServerSocket;\n+import java.net.SocketAddress;\n+import java.net.SocketOption;\n+import java.nio.channels.ServerSocketChannel;\n+import java.nio.channels.spi.SelectorProvider;\n+import java.util.Objects;\n+import java.util.Set;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * A selectable channel for stream-oriented listening sockets.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFServerSocketChannel extends ServerSocketChannel\n+ implements FileDescriptorAccess {\n+ private final @NonNull AFServerSocket afSocket;\n+\n+ /**\n+ * Creates a new {@link AFServerSocketChannel} instance.\n+ * \n+ * @param socket The corresponding {@link ServerSocket}.\n+ * @param sp The corresponding {@link SelectorProvider}.\n+ */\n+ @SuppressWarnings(\"null\")\n+ protected AFServerSocketChannel(AFServerSocket socket, AFSelectorProvider sp) {\n+ super(sp);\n+ this.afSocket = Objects.requireNonNull(socket);\n+ }\n+\n+ // CPD-OFF\n+\n+ @SuppressWarnings(\"unchecked\")\n+ @Override\n+ public T getOption(SocketOption name) throws IOException {\n+ if (name instanceof AFSocketOption) {\n+ return getAFCore().getOption((AFSocketOption) name);\n+ }\n+ Integer optionId = SocketOptionsMapper.resolve(name);\n+ if (optionId == null) {\n+ throw new UnsupportedOperationException(\"unsupported option\");\n+ } else {\n+ return (T) afSocket.getAFImpl().getOption(optionId.intValue());\n+ }\n+ }\n+\n+ @Override\n+ public AFServerSocketChannel setOption(SocketOption name, T value) throws IOException {\n+ if (name instanceof AFSocketOption) {\n+ getAFCore().setOption((AFSocketOption) name, value);\n+ return this;\n+ }\n+ Integer optionId = SocketOptionsMapper.resolve(name);\n+ if (optionId == null) {\n+ throw new UnsupportedOperationException(\"unsupported option\");\n+ } else {\n+ afSocket.getAFImpl().setOption(optionId.intValue(), value);\n+ }\n+ return this;\n+ }\n+\n+ @Override\n+ public final Set> supportedOptions() {\n+ return SocketOptionsMapper.SUPPORTED_SOCKET_OPTIONS;\n+ }\n+\n+ // CPD-ON\n+\n+ @Override\n+ public final AFServerSocketChannel bind(SocketAddress local, int backlog) throws IOException {\n+ afSocket.bind(local, backlog);\n+ return this;\n+ }\n+\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n+ @Override\n+ public final AFServerSocket socket() {\n+ return afSocket;\n+ }\n+\n+ @Override\n+ public AFSocketChannel accept() throws IOException {\n+ AFSocket socket = afSocket.accept1(false);\n+ return socket == null ? null : socket.getChannel();\n+ }\n+\n+ @Override\n+ public final AFSocketAddress getLocalAddress() throws IOException {\n+ return afSocket.getLocalSocketAddress();\n+ }\n+\n+ @Override\n+ protected final void implCloseSelectableChannel() throws IOException {\n+ afSocket.close();\n+ }\n+\n+ @Override\n+ protected final void implConfigureBlocking(boolean block) throws IOException {\n+ getAFCore().implConfigureBlocking(block);\n+ }\n+\n+ final AFSocketCore getAFCore() {\n+ return afSocket.getAFImpl().getCore();\n+ }\n+\n+ @Override\n+ public final FileDescriptor getFileDescriptor() throws IOException {\n+ return afSocket.getFileDescriptor();\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocket.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocket.java\nnew file mode 100644\nindex 000000000..2b7c65dd5\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocket.java\n@@ -0,0 +1,547 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.Closeable;\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.net.Socket;\n+import java.net.SocketAddress;\n+import java.net.SocketException;\n+import java.net.SocketImpl;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.Nullable;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * junixsocket's base implementation of a {@link Socket}.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFSocket extends Socket implements AFSomeSocket,\n+ AFSocketExtensions {\n+ private static final String PROP_LIBRARY_DISABLE_CAPABILITY_PREFIX =\n+ \"org.newsclub.net.unix.library.disable.\";\n+\n+ @SuppressWarnings(\"PMD.MutableStaticState\")\n+ static String loadedLibrary; // set by NativeLibraryLoader\n+\n+ private static Integer capabilities = null;\n+\n+ private final AFSocketImpl impl;\n+\n+ private final AFSocketAddressFromHostname afh;\n+ private final Closeables closeables = new Closeables();\n+ private final AtomicBoolean created = new AtomicBoolean(false);\n+ private final AFSocketChannel channel = newChannel();\n+\n+ private @Nullable SocketAddressFilter connectFilter;\n+\n+ /**\n+ * Creates a new {@link AFSocket} instance.\n+ * \n+ * @param impl The corresponding {@link SocketImpl} class.\n+ * @param afh The conversion helper to get a socket address from an encoded hostname.\n+ * @throws SocketException on error.\n+ */\n+ protected AFSocket(final AFSocketImpl impl, AFSocketAddressFromHostname afh)\n+ throws SocketException {\n+ super(impl);\n+ this.afh = afh;\n+ this.impl = impl;\n+ }\n+\n+ /**\n+ * Returns the {@link AFSocketAddress} type supported by this socket.\n+ * \n+ * @return The supported {@link AFSocketAddress}.\n+ */\n+ protected final Class socketAddressClass() {\n+ return getAFImpl(false).getAddressFamily().getSocketAddressClass();\n+ }\n+\n+ /**\n+ * Creates a new {@link AFSocketChannel} for this socket.\n+ * \n+ * @return The new instance.\n+ */\n+ protected abstract AFSocketChannel newChannel();\n+\n+ /**\n+ * The reference to the constructor of an {@link AFSocket} subclass.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ */\n+ @FunctionalInterface\n+ public interface Constructor {\n+ /**\n+ * Constructs a new {@link AFSocket} subclass instance.\n+ * \n+ * @param fdObj The file descriptor.\n+ * @param factory The socket factory instance.\n+ * @return The instance.\n+ * @throws SocketException on error.\n+ */\n+ @NonNull\n+ AFSocket newInstance(FileDescriptor fdObj, AFSocketFactory factory)\n+ throws SocketException;\n+ }\n+\n+ static AFSocket newInstance(Constructor constr,\n+ AFSocketFactory sf, FileDescriptor fdObj, int localPort, int remotePort)\n+ throws IOException {\n+ if (!fdObj.valid()) {\n+ throw new SocketException(\"Invalid file descriptor\");\n+ }\n+ int status = NativeUnixSocket.socketStatus(fdObj);\n+ if (status == NativeUnixSocket.SOCKETSTATUS_INVALID) {\n+ throw new SocketException(\"Not a valid socket\");\n+ }\n+\n+ AFSocket socket = newInstance0(constr, fdObj, sf);\n+ socket.getAFImpl().updatePorts(localPort, remotePort);\n+\n+ switch (status) {\n+ case NativeUnixSocket.SOCKETSTATUS_CONNECTED:\n+ socket.internalDummyConnect();\n+ break;\n+ case NativeUnixSocket.SOCKETSTATUS_BOUND:\n+ socket.internalDummyBind();\n+ break;\n+ case NativeUnixSocket.SOCKETSTATUS_UNKNOWN:\n+ break;\n+ default:\n+ throw new IllegalStateException(\"Invalid socketStatus response: \" + status);\n+ }\n+ socket.getAFImpl().setSocketAddress(socket.getLocalSocketAddress());\n+\n+ return socket;\n+ }\n+\n+ /**\n+ * Creates a new, unbound {@link AFSocket}.\n+ * \n+ * This \"default\" implementation is a bit \"lenient\" with respect to the specification.\n+ * \n+ * In particular, we may ignore calls to {@link Socket#getTcpNoDelay()} and\n+ * {@link Socket#setTcpNoDelay(boolean)}.\n+ * \n+ * @param The corresponding address type.\n+ * @param constr The implementation's {@link AFSocket} constructor\n+ * @param factory The corresponding socket factory, or {@code null}.\n+ * @return A new, unbound socket.\n+ * @throws SocketException if the operation fails.\n+ */\n+ protected static final AFSocket newInstance(Constructor constr,\n+ AFSocketFactory factory) throws SocketException {\n+ return newInstance0(constr, null, factory);\n+ }\n+\n+ private static @NonNull AFSocket newInstance0(\n+ Constructor constr, FileDescriptor fdObj, AFSocketFactory factory)\n+ throws SocketException {\n+ return constr.newInstance(fdObj, factory);\n+ }\n+\n+ /**\n+ * Creates a new {@link AFSocket} and connects it to the given {@link AFSocketAddress}.\n+ * \n+ * @param The corresponding address type.\n+ * @param constr The implementation's {@link AFSocket} constructor\n+ * @param addr The address to connect to.\n+ * @return A new, connected socket.\n+ * @throws IOException if the operation fails.\n+ */\n+ protected static final @NonNull AFSocket connectTo(\n+ Constructor constr, A addr) throws IOException {\n+ AFSocket socket = constr.newInstance(null, null);\n+ socket.connect(addr);\n+ return socket;\n+ }\n+\n+ /**\n+ * Creates a new {@link AFSocket} and connects it to the given {@link AFSocketAddress} using the\n+ * default implementation suited for that address type.\n+ * \n+ * @param The corresponding address type.\n+ * @param addr The address to connect to.\n+ * @return A new, connected socket.\n+ * @throws IOException if the operation fails.\n+ */\n+ public static final AFSocket connectTo(@NonNull A addr)\n+ throws IOException {\n+ AFSocket socket = addr.getAddressFamily().getSocketConstructor().newInstance(null, null);\n+ socket.connect(addr);\n+ return socket;\n+ }\n+\n+ /**\n+ * Not supported, since it's not necessary for client sockets.\n+ * \n+ * @see AFServerSocket\n+ */\n+ @Override\n+ public final void bind(SocketAddress bindpoint) throws IOException {\n+ if (bindpoint == null) {\n+ throw new IllegalArgumentException();\n+ }\n+ if (isClosed()) {\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+ if (isBound()) {\n+ throw new SocketException(\"Already bound\");\n+ }\n+ preprocessSocketAddress(bindpoint);\n+ throw new SocketException(\"Use AF*ServerSocket#bind or #bindOn\");\n+ }\n+\n+ @Override\n+ public final boolean isBound() {\n+ return super.isBound() || impl.isBound();\n+ }\n+\n+ @Override\n+ public final boolean isConnected() {\n+ return super.isConnected() || impl.isConnected();\n+ }\n+\n+ @Override\n+ public final void connect(SocketAddress endpoint) throws IOException {\n+ connect(endpoint, 0);\n+ }\n+\n+ @Override\n+ public final void connect(SocketAddress endpoint, int timeout) throws IOException {\n+ connect0(endpoint, timeout);\n+ }\n+\n+ private AFSocketAddress preprocessSocketAddress(SocketAddress endpoint) throws SocketException {\n+ if (endpoint == null) {\n+ throw new IllegalArgumentException(\"endpoint is null\");\n+ } else if (endpoint instanceof SentinelSocketAddress) {\n+ return (AFSocketAddress) endpoint;\n+ } else {\n+ return AFSocketAddress.preprocessSocketAddress(socketAddressClass(), endpoint, afh);\n+ }\n+ }\n+\n+ final boolean connect0(SocketAddress endpoint, int timeout) throws IOException {\n+ if (timeout < 0) {\n+ throw new IllegalArgumentException(\"connect: timeout can't be negative\");\n+ }\n+ if (isClosed()) {\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+\n+ if (connectFilter != null) {\n+ endpoint = connectFilter.apply(endpoint);\n+ }\n+\n+ AFSocketAddress address = preprocessSocketAddress(endpoint);\n+\n+ if (!isBound()) {\n+ internalDummyBind();\n+ }\n+\n+ boolean success = getAFImpl().connect0(address, timeout);\n+ if (success) {\n+ int port = address.getPort();\n+ if (port > 0) {\n+ getAFImpl().updatePorts(getLocalPort(), port);\n+ }\n+ }\n+ internalDummyConnect();\n+ return success;\n+ }\n+\n+ final void internalDummyConnect() throws IOException {\n+ if (!isConnected()) {\n+ super.connect(AFSocketAddress.INTERNAL_DUMMY_CONNECT, 0);\n+ }\n+ }\n+\n+ final void internalDummyBind() throws IOException {\n+ if (!isBound()) {\n+ super.bind(AFSocketAddress.INTERNAL_DUMMY_BIND);\n+ }\n+ }\n+\n+ @Override\n+ public final String toString() {\n+ return getClass().getName() + \"@\" + Integer.toHexString(hashCode()) + toStringSuffix();\n+ }\n+\n+ final String toStringSuffix() {\n+ if (impl.getFD().valid()) {\n+ return \"[local=\" + getLocalSocketAddress() + \";remote=\" + getRemoteSocketAddress() + \"]\";\n+ } else {\n+ return \"[invalid]\";\n+ }\n+ }\n+\n+ /**\n+ * Returns true iff {@link AFSocket}s are supported by the current Java VM.\n+ * \n+ * To support {@link AFSocket}s, a custom JNI library must be loaded that is supplied with\n+ * junixsocket.\n+ * \n+ * @return {@code true} iff supported.\n+ */\n+ public static boolean isSupported() {\n+ return NativeUnixSocket.isLoaded();\n+ }\n+\n+ /**\n+ * Checks if {@link AFSocket}s are supported by the current Java VM.\n+ * \n+ * If not, an {@link UnsupportedOperationException} is thrown.\n+ * \n+ * @throws UnsupportedOperationException if not supported.\n+ */\n+ public static void ensureSupported() throws UnsupportedOperationException {\n+ NativeUnixSocket.ensureSupported();\n+ }\n+\n+ /**\n+ * Returns the version of the junixsocket library, as a string, for debugging purposes.\n+ * \n+ * NOTE: Do not rely on the format of the version identifier, use socket capabilities instead.\n+ * \n+ * @return String The version identifier, or {@code null} if it could not be determined.\n+ * @see #supports(AFSocketCapability)\n+ */\n+ public static final String getVersion() {\n+ try {\n+ return NativeLibraryLoader.getJunixsocketVersion();\n+ } catch (IOException e) {\n+ return null;\n+ }\n+ }\n+\n+ /**\n+ * Returns an identifier of the loaded native library, or {@code null} if the library hasn't been\n+ * loaded yet.\n+ * \n+ * The identifier is useful mainly for debugging purposes.\n+ * \n+ * @return The identifier of the loaded junixsocket-native library, or {@code null}.\n+ */\n+ public static final String getLoadedLibrary() {\n+ return loadedLibrary;\n+ }\n+\n+ @Override\n+ public final boolean isClosed() {\n+ return super.isClosed() || (isConnected() && !impl.getFD().valid());\n+ }\n+\n+ @Override\n+ public final int getAncillaryReceiveBufferSize() {\n+ return impl.getAncillaryReceiveBufferSize();\n+ }\n+\n+ @Override\n+ public final void setAncillaryReceiveBufferSize(int size) {\n+ impl.setAncillaryReceiveBufferSize(size);\n+ }\n+\n+ @Override\n+ public final void ensureAncillaryReceiveBufferSize(int minSize) {\n+ impl.ensureAncillaryReceiveBufferSize(minSize);\n+ }\n+\n+ private static synchronized int getCapabilities() {\n+ if (capabilities == null) {\n+ if (!isSupported()) {\n+ capabilities = 0;\n+ } else {\n+ int v = NativeUnixSocket.capabilities();\n+\n+ if (System.getProperty(\"osv.version\") != null) {\n+ // no fork, no redirect...\n+ v &= ~(AFSocketCapability.CAPABILITY_FD_AS_REDIRECT.getBitmask());\n+ }\n+\n+ capabilities = v;\n+ }\n+ }\n+ return capabilities.intValue();\n+ }\n+\n+ private static boolean isCapDisabled(String name) {\n+ return Boolean.valueOf(System.getProperty(PROP_LIBRARY_DISABLE_CAPABILITY_PREFIX + name,\n+ \"false\"));\n+ }\n+\n+ /**\n+ * Checks if the current environment (system platform, native library, etc.) supports a given\n+ * junixsocket capability.\n+ * \n+ * Deprecated. Please use {@link #supports(AFSocketCapability)} instead.\n+ * \n+ * NOTE: The result may or may not be cached from a previous call or from a check upon\n+ * initialization.\n+ * \n+ * @param capability The capability.\n+ * @return true if supported.\n+ * @see #supports(AFSocketCapability)\n+ */\n+ @Deprecated\n+ public static final boolean supports(AFUNIXSocketCapability capability) {\n+ return !isCapDisabled(capability.name()) && (getCapabilities() & capability.getBitmask()) != 0;\n+ }\n+\n+ /**\n+ * Checks if the current environment (system platform, native library, etc.) supports a given\n+ * junixsocket capability.\n+ * \n+ * NOTE: The result may or may not be cached from a previous call or from a check upon\n+ * initialization.\n+ * \n+ * @param capability The capability.\n+ * @return true if supported.\n+ */\n+ public static final boolean supports(AFSocketCapability capability) {\n+ return !isCapDisabled(capability.name()) && (getCapabilities() & capability.getBitmask()) != 0;\n+ }\n+\n+ @Override\n+ public final synchronized void close() throws IOException {\n+ IOException superException = null;\n+ try {\n+ super.close();\n+ } catch (IOException e) {\n+ superException = e;\n+ }\n+ closeables.close(superException);\n+ }\n+\n+ /**\n+ * Registers a {@link Closeable} that should be closed when this socket is closed.\n+ * \n+ * @param closeable The closeable.\n+ */\n+ public final void addCloseable(Closeable closeable) {\n+ closeables.add(closeable);\n+ }\n+\n+ /**\n+ * Unregisters a previously registered {@link Closeable}.\n+ * \n+ * @param closeable The closeable.\n+ */\n+ public final void removeCloseable(Closeable closeable) {\n+ closeables.remove(closeable);\n+ }\n+\n+ final AFSocketImpl getAFImpl() {\n+ return getAFImpl(true);\n+ }\n+\n+ final AFSocketImpl getAFImpl(boolean createSocket) {\n+ if (createSocket && created.compareAndSet(false, true)) {\n+ try {\n+ getSoTimeout(); // trigger create via java.net.Socket\n+ } catch (SocketException e) {\n+ // ignore\n+ }\n+ }\n+ return impl;\n+ }\n+\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n+ @Override\n+ public AFSocketChannel getChannel() {\n+ return channel;\n+ }\n+\n+ @SuppressWarnings(\"null\")\n+ @Override\n+ public final synchronized A getRemoteSocketAddress() {\n+ if (!isConnected()) {\n+ return null;\n+ }\n+ return impl.getRemoteSocketAddress();\n+ }\n+\n+ @SuppressWarnings(\"null\")\n+ @Override\n+ public final A getLocalSocketAddress() {\n+ if (isClosed()) {\n+ return null;\n+ }\n+ return impl.getLocalSocketAddress();\n+ }\n+\n+ @Override\n+ public final FileDescriptor getFileDescriptor() throws IOException {\n+ return impl.getFileDescriptor();\n+ }\n+\n+ @Override\n+ public final AFInputStream getInputStream() throws IOException {\n+ return getAFImpl().getInputStream();\n+ }\n+\n+ @Override\n+ public final AFOutputStream getOutputStream() throws IOException {\n+ return getAFImpl().getOutputStream();\n+ }\n+\n+ /**\n+ * Returns the internal helper instance for address-specific extensions.\n+ * \n+ * @return The helper instance.\n+ * @throws UnsupportedOperationException if such extensions are not supported for this address\n+ * type.\n+ */\n+ protected final AFSocketImplExtensions getImplExtensions() {\n+ return getAFImpl(false).getImplExtensions();\n+ }\n+\n+ /**\n+ * Forces the address to be used for any subsequent call to {@link #connect(SocketAddress)} to be\n+ * the given one, regardless of what'll be passed there.\n+ * \n+ * @param endpoint The forced endpoint address.\n+ * @return This instance.\n+ */\n+ public final AFSocket forceConnectAddress(SocketAddress endpoint) {\n+ return connectHook((SocketAddress orig) -> {\n+ return orig == null ? null : endpoint;\n+ });\n+ }\n+\n+ /**\n+ * Sets the hook for any subsequent call to {@link #connect(SocketAddress)} or\n+ * {@link #connect(SocketAddress, int)} to be the given function.\n+ * \n+ * The function can monitor events or even alter the target address.\n+ * \n+ * @param hook The function that gets called for each connect call.\n+ * @return This instance.\n+ */\n+ public final AFSocket connectHook(SocketAddressFilter hook) {\n+ this.connectFilter = hook;\n+ return this;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketAddress.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketAddress.java\nnew file mode 100644\nindex 000000000..89248083d\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketAddress.java\n@@ -0,0 +1,682 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.File;\n+import java.io.FileDescriptor;\n+import java.io.FileNotFoundException;\n+import java.io.IOException;\n+import java.net.DatagramSocket;\n+import java.net.InetAddress;\n+import java.net.InetSocketAddress;\n+import java.net.ServerSocket;\n+import java.net.SocketAddress;\n+import java.net.SocketException;\n+import java.net.URI;\n+import java.nio.ByteBuffer;\n+import java.util.HashMap;\n+import java.util.Locale;\n+import java.util.Map;\n+import java.util.Objects;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.Nullable;\n+\n+/**\n+ * Some {@link SocketAddress} that is supported by junixsocket, such as {@link AFUNIXSocketAddress}.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFSocketAddress extends InetSocketAddress {\n+ private static final long serialVersionUID = 1L;\n+\n+ /**\n+ * Just a marker for \"don't actually bind\" (checked with \"==\"). Used in combination with a\n+ * superclass' bind method, which should trigger \"setBound()\", etc.\n+ */\n+ static final AFSocketAddress INTERNAL_DUMMY_BIND = new SentinelSocketAddress(0);\n+ static final AFSocketAddress INTERNAL_DUMMY_CONNECT = new SentinelSocketAddress(1);\n+ static final AFSocketAddress INTERNAL_DUMMY_DONT_CONNECT = new SentinelSocketAddress(2);\n+\n+ private static final int SOCKADDR_NATIVE_FAMILY_OFFSET = NativeUnixSocket.isLoaded() //\n+ ? NativeUnixSocket.sockAddrNativeFamilyOffset() : -1;\n+\n+ private static final int SOCKADDR_NATIVE_DATA_OFFSET = NativeUnixSocket.isLoaded() //\n+ ? NativeUnixSocket.sockAddrNativeDataOffset() : -1;\n+\n+ private static final int SOCKADDR_MAX_LEN = NativeUnixSocket.isLoaded() //\n+ ? NativeUnixSocket.sockAddrLength(0) : 256;\n+\n+ private static final Map, Map>> ADDRESS_CACHE =\n+ new HashMap<>();\n+\n+ static final ThreadLocal SOCKETADDRESS_BUFFER_TL = new ThreadLocal() {\n+\n+ @Override\n+ protected ByteBuffer initialValue() {\n+ return AFSocketAddress.newSockAddrDirectBuffer(SOCKADDR_MAX_LEN);\n+ }\n+ };\n+\n+ /**\n+ * Some byte-level representation of this address, which can only be converted to a native\n+ * representation in combination with the domain ID.\n+ */\n+ private final byte[] bytes;\n+\n+ /**\n+ * An {@link InetAddress}-wrapped representation of this address. Only created upon demand.\n+ */\n+ private InetAddress inetAddress = null;\n+\n+ /**\n+ * The system-native representation of this address, or {@code null}.\n+ */\n+ private final ByteBuffer nativeAddress;\n+\n+ /**\n+ * The address family.\n+ */\n+ private final AFAddressFamily addressFamily;\n+\n+ /**\n+ * Creates a new socket address.\n+ * \n+ * @param port The port.\n+ * @param socketAddress The socket address in junixsocket-specific byte-array representation.\n+ * @param nativeAddress The socket address in system-native representation.\n+ * @param af The address family.\n+ * @throws SocketException on error.\n+ */\n+ protected AFSocketAddress(int port, final byte[] socketAddress, ByteBuffer nativeAddress,\n+ AFAddressFamily af) throws SocketException {\n+ /*\n+ * Initializing the superclass with an unresolved hostname helps us pass the #equals and\n+ * #hashCode checks, which unfortunately are declared final in InetSocketAddress.\n+ * \n+ * Using a resolved address (with the address bit initialized) would be ideal, but resolved\n+ * addresses can only be IPv4 or IPv6 (at least as of Java 16 and earlier).\n+ */\n+ super(AFInetAddress.createUnresolvedHostname(socketAddress, af), 0);\n+ this.nativeAddress = nativeAddress == null ? null : (ByteBuffer) nativeAddress.duplicate()\n+ .rewind();\n+ if (port < -1) {\n+ throw new IllegalArgumentException(\"port out of range\");\n+ }\n+ if (port > 0) {\n+ if (!NativeUnixSocket.isLoaded()) {\n+ throw (SocketException) new SocketException(\n+ \"Cannot set SocketAddress port - junixsocket JNI library is not available\").initCause(\n+ NativeUnixSocket.unsupportedException());\n+ }\n+ NativeUnixSocket.setPort1(this, port);\n+ }\n+ if (socketAddress.length == 0) {\n+ throw new SocketException(\"Illegal address length: \" + socketAddress.length);\n+ }\n+\n+ this.bytes = socketAddress.clone();\n+ this.addressFamily = af;\n+ }\n+\n+ /**\n+ * Only for {@link SentinelSocketAddress}.\n+ * \n+ * @param clazz The {@link SentinelSocketAddress} class.\n+ * @param port A sentinel port number.\n+ */\n+ @SuppressWarnings(\"PMD.UnusedFormalParameter\")\n+ protected AFSocketAddress(Class clazz, int port) {\n+ super(InetAddress.getLoopbackAddress(), port);\n+ this.nativeAddress = null;\n+ this.bytes = new byte[0];\n+ this.addressFamily = null;\n+ }\n+\n+ /**\n+ * Checks if the address can be resolved to a {@link File}.\n+ * \n+ * @return {@code true} if the address has a filename.\n+ */\n+ public abstract boolean hasFilename();\n+\n+ /**\n+ * Returns the {@link File} corresponding with this address, if possible.\n+ * \n+ * A {@link FileNotFoundException} is thrown if there is no filename associated with the address,\n+ * which applies to addresses in the abstract namespace, for example.\n+ * \n+ * @return The filename.\n+ * @throws FileNotFoundException if the address is not associated with a filename.\n+ */\n+ public abstract File getFile() throws FileNotFoundException;\n+\n+ /**\n+ * Returns the corresponding {@link AFAddressFamily}.\n+ * \n+ * @return The address family instance.\n+ */\n+ public final AFAddressFamily getAddressFamily() {\n+ return addressFamily;\n+ }\n+\n+ /**\n+ * Wraps the socket name/peer name of a file descriptor as an {@link InetAddress}.\n+ * \n+ * @param fdesc The file descriptor.\n+ * @param peerName If {@code true}, the remote peer name (instead of the local name) is retrieved.\n+ * @param af The address family.\n+ * @return The {@link InetAddress}.\n+ */\n+ protected static final InetAddress getInetAddress(FileDescriptor fdesc, boolean peerName,\n+ AFAddressFamily af) {\n+ if (!fdesc.valid()) {\n+ return null;\n+ }\n+ byte[] addr = NativeUnixSocket.sockname(af.getDomain(), fdesc, peerName); // FIXME\n+ if (addr == null) {\n+ return null;\n+ }\n+ return AFInetAddress.wrapAddress(addr, af);\n+ }\n+\n+ /**\n+ * Gets the socket name/peer name of a file descriptor as an {@link AFSocketAddress}.\n+ * \n+ * @param The corresponding address type.\n+ * @param fdesc The file descriptor.\n+ * @param peerName If {@code true}, the remote peer name (instead of the local name) is retrieved.\n+ * @param port The port.\n+ * @param af The address family.\n+ * @return The {@link InetAddress}.\n+ */\n+ protected static final @Nullable A getSocketAddress(\n+ FileDescriptor fdesc, boolean peerName, int port, AFAddressFamily af) {\n+ if (!fdesc.valid()) {\n+ return null;\n+ }\n+ byte[] addr = NativeUnixSocket.sockname(af.getDomain(), fdesc, peerName); // FIXME\n+ if (addr == null) {\n+ return null;\n+ }\n+ try {\n+ // FIXME we could infer the \"port\" from the path if the socket factory supports that\n+ return AFSocketAddress.unwrap(AFInetAddress.wrapAddress(addr, af), port, af);\n+ } catch (SocketException e) {\n+ throw new IllegalStateException(e);\n+ }\n+ }\n+\n+ static final AFSocketAddress preprocessSocketAddress(\n+ Class supportedAddressClass, SocketAddress endpoint,\n+ AFSocketAddressFromHostname afh) throws SocketException {\n+ Objects.requireNonNull(endpoint);\n+ if (endpoint instanceof SentinelSocketAddress) {\n+ return (SentinelSocketAddress) endpoint;\n+ }\n+\n+ if (!(endpoint instanceof AFSocketAddress)) {\n+ if (afh != null) {\n+ if (endpoint instanceof InetSocketAddress) {\n+ InetSocketAddress isa = (InetSocketAddress) endpoint;\n+\n+ String hostname = isa.getHostString();\n+ if (afh.isHostnameSupported(hostname)) {\n+ try {\n+ endpoint = afh.addressFromHost(hostname, isa.getPort());\n+ } catch (SocketException e) {\n+ throw e;\n+ }\n+ }\n+ }\n+ }\n+ }\n+\n+ Objects.requireNonNull(endpoint);\n+\n+ if (!supportedAddressClass.isAssignableFrom(endpoint.getClass())) {\n+ throw new IllegalArgumentException(\"Can only connect to endpoints of type \"\n+ + supportedAddressClass.getName() + \", got: \" + endpoint.getClass() + \": \" + endpoint);\n+ }\n+\n+ return (AFSocketAddress) endpoint;\n+ }\n+\n+ /**\n+ * Returns the (non-native) byte-level representation of this address.\n+ * \n+ * @return The byte array.\n+ */\n+ protected final byte[] getBytes() {\n+ return bytes; // NOPMD\n+ }\n+\n+ /**\n+ * Returns a \"special\" {@link InetAddress} that contains information about this\n+ * {@link AFSocketAddress}.\n+ * \n+ * IMPORTANT: This {@link InetAddress} does not properly compare (using\n+ * {@link InetAddress#equals(Object)} and {@link InetAddress#hashCode()}). It should be used\n+ * exclusively to circumvent existing APIs like {@link DatagramSocket} that only accept/return\n+ * {@link InetAddress} and not arbitrary {@link SocketAddress} types.\n+ * \n+ * @return The \"special\" {@link InetAddress}.\n+ */\n+ public final InetAddress wrapAddress() {\n+ return AFInetAddress.wrapAddress(bytes, getAddressFamily());\n+ }\n+\n+ /**\n+ * A reference to the constructor of an AFSocketAddress subclass.\n+ * \n+ * @param The actual subclass.\n+ * @author Christian Kohlschütter\n+ */\n+ @FunctionalInterface\n+ protected interface AFSocketAddressConstructor {\n+ /**\n+ * Constructs a new AFSocketAddress instance.\n+ * \n+ * @param port The port.\n+ * @param socketAddress The socket address in junixsocket-specific byte-array representation.\n+ * @param nativeAddress The socket address in system-native representation.\n+ * @return The instance.\n+ * @throws SocketException on error.\n+ */\n+ @NonNull\n+ T newAFSocketAddress(int port, byte[] socketAddress, ByteBuffer nativeAddress)\n+ throws SocketException;\n+ }\n+\n+ /**\n+ * Resolves a junixsocket-specific byte-array representation of an {@link AFSocketAddress} to an\n+ * actual {@link AFSocketAddress} instance, possibly reusing a cached instance.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @param socketAddress The socket address in junixsocket-specific byte-array representation.\n+ * @param port The port.\n+ * @param af The address family.\n+ * @return The instance.\n+ * @throws SocketException on error.\n+ */\n+ @SuppressWarnings({\"unchecked\", \"null\"})\n+ protected static final A resolveAddress(final byte[] socketAddress,\n+ int port, AFAddressFamily af) throws SocketException {\n+ A instance;\n+\n+ if (socketAddress.length == 0) {\n+ throw new SocketException(\"Address cannot be empty\");\n+ }\n+\n+ if (port == -1) {\n+ port = 0;\n+ }\n+\n+ ByteBuffer direct = SOCKETADDRESS_BUFFER_TL.get();\n+ int limit = NativeUnixSocket.isLoaded() ? NativeUnixSocket.bytesToSockAddr(af.getDomain(),\n+ direct, socketAddress) : -1;\n+ if (limit == -1) {\n+ // not supported, but we can still create an address\n+ return af.getAddressConstructor().newAFSocketAddress(port, socketAddress, null);\n+ } else if (limit > SOCKADDR_MAX_LEN) {\n+ throw new IllegalStateException(\"Unexpected address length\");\n+ }\n+ direct.rewind();\n+ direct.limit(limit);\n+\n+ synchronized (AFSocketAddress.class) {\n+ Map map;\n+ Map> mapPorts = ADDRESS_CACHE.get(af);\n+ if (mapPorts == null) {\n+ instance = null;\n+ mapPorts = new HashMap<>();\n+ map = new HashMap<>();\n+ mapPorts.put(port, map);\n+ ADDRESS_CACHE.put(af, mapPorts);\n+ } else {\n+ map = mapPorts.get(port);\n+ if (map == null) {\n+ instance = null;\n+ map = new HashMap<>();\n+ mapPorts.put(port, map);\n+ } else {\n+ instance = (A) map.get(direct);\n+ }\n+ }\n+\n+ if (instance == null) {\n+ ByteBuffer key = newSockAddrKeyBuffer(limit);\n+ key.put(direct);\n+ key = key.asReadOnlyBuffer();\n+\n+ instance = af.getAddressConstructor().newAFSocketAddress(port, socketAddress, key);\n+\n+ map.put(key, instance);\n+ }\n+ }\n+\n+ return instance;\n+ }\n+\n+ @SuppressWarnings(\"null\")\n+ static final A ofInternal(ByteBuffer socketAddressBuffer,\n+ AFAddressFamily af) throws SocketException {\n+ synchronized (AFSocketAddress.class) {\n+ Map> mapPorts = ADDRESS_CACHE.get(af);\n+ if (mapPorts != null) {\n+ Map map = mapPorts.get(0); // FIXME get port, something like\n+ // sockAddrToPort\n+ if (map != null) {\n+ @SuppressWarnings(\"unchecked\")\n+ A address = (A) map.get(socketAddressBuffer.rewind());\n+ if (address != null) {\n+ return address;\n+ }\n+ }\n+ }\n+\n+ if (!socketAddressBuffer.isDirect()) {\n+ ByteBuffer buf = getNativeAddressDirectBuffer(Math.min(socketAddressBuffer.limit(),\n+ SOCKADDR_MAX_LEN));\n+ buf.put(socketAddressBuffer);\n+ socketAddressBuffer = buf;\n+ }\n+ byte[] sockAddrToBytes = NativeUnixSocket.sockAddrToBytes(af.getDomain(),\n+ socketAddressBuffer);\n+ if (sockAddrToBytes == null) {\n+ return null;\n+ } else {\n+ return AFSocketAddress.resolveAddress(sockAddrToBytes, 0, af);\n+ }\n+ }\n+ }\n+\n+ /**\n+ * Wraps an address as an {@link InetAddress}.\n+ * \n+ * @param af The address family.\n+ * @return The {@link InetAddress}.\n+ */\n+ protected final synchronized InetAddress getInetAddress(AFAddressFamily af) {\n+ if (inetAddress == null) {\n+ inetAddress = AFInetAddress.wrapAddress(bytes, af);\n+ }\n+ return inetAddress;\n+ }\n+\n+ /**\n+ * Wraps this address as an {@link InetAddress}.\n+ * \n+ * @return The {@link InetAddress}.\n+ */\n+ protected final InetAddress getInetAddress() {\n+ return getInetAddress(getAddressFamily());\n+ }\n+\n+ static final ByteBuffer newSockAddrDirectBuffer(int length) {\n+ return ByteBuffer.allocateDirect(length);\n+ }\n+\n+ static final ByteBuffer newSockAddrKeyBuffer(int length) {\n+ return ByteBuffer.allocate(length);\n+ }\n+\n+ /**\n+ * Returns an {@link AFSocketAddress} given a special {@link InetAddress} that encodes the byte\n+ * sequence of an AF_UNIX etc. socket address, like those returned by {@link #wrapAddress()}.\n+ * \n+ * @param The corresponding address type.\n+ * @param address The \"special\" {@link InetAddress}.\n+ * @param port The port (use 0 for \"none\").\n+ * @param af The address family.\n+ * @return The {@link AFSocketAddress} instance.\n+ * @throws SocketException if the operation fails, for example when an unsupported address is\n+ * specified.\n+ */\n+ @SuppressWarnings(\"null\")\n+ @NonNull\n+ protected static final A unwrap(InetAddress address, int port,\n+ AFAddressFamily af) throws SocketException {\n+ Objects.requireNonNull(address);\n+ return resolveAddress(AFInetAddress.unwrapAddress(address, af), port, af);\n+ }\n+\n+ /**\n+ * Returns an {@link AFSocketAddress} given a special {@link InetAddress} hostname that encodes\n+ * the byte sequence of an AF_UNIX etc. socket address, like those returned by\n+ * {@link #wrapAddress()}.\n+ * \n+ * @param The corresponding address type.\n+ * @param hostname The \"special\" hostname, as provided by {@link InetAddress#getHostName()}.\n+ * @param port The port (use 0 for \"none\").\n+ * @param af The address family.\n+ * @return The {@link AFSocketAddress} instance.\n+ * @throws SocketException if the operation fails, for example when an unsupported address is\n+ * specified.\n+ */\n+ @SuppressWarnings(\"null\")\n+ @NonNull\n+ protected static final A unwrap(String hostname, int port,\n+ AFAddressFamily af) throws SocketException {\n+ Objects.requireNonNull(hostname);\n+ return resolveAddress(AFInetAddress.unwrapAddress(hostname, af), port, af);\n+ }\n+\n+ static final int unwrapAddressDirectBufferInternal(ByteBuffer socketAddressBuffer,\n+ SocketAddress address) throws SocketException {\n+ Objects.requireNonNull(address);\n+ // FIXME: add support for UnixDomainSocketAddress\n+ if (!(address instanceof AFSocketAddress)) {\n+ throw new SocketException(\"Unsupported address\");\n+ }\n+\n+ byte[] addr = ((AFSocketAddress) address).getBytes();\n+ int domain = ((AFSocketAddress) address).getAddressFamily().getDomain();\n+ int len = NativeUnixSocket.isLoaded() ? NativeUnixSocket.bytesToSockAddr(domain,\n+ socketAddressBuffer, addr) : -1;\n+ if (len == -1) {\n+ throw new SocketException(\"Unsupported domain\");\n+ }\n+ return len;\n+ }\n+\n+ /**\n+ * Returns a thread-local direct ByteBuffer containing the native socket address representation of\n+ * this {@link AFSocketAddress}.\n+ * \n+ * @return The direct {@link ByteBuffer}.\n+ */\n+ final ByteBuffer getNativeAddressDirectBuffer() {\n+ ByteBuffer direct = getNativeAddressDirectBuffer(nativeAddress.limit());\n+ nativeAddress.position(0);\n+ direct.put(nativeAddress);\n+\n+ return direct;\n+ }\n+\n+ static final ByteBuffer getNativeAddressDirectBuffer(int limit) {\n+ ByteBuffer direct = SOCKETADDRESS_BUFFER_TL.get();\n+ direct.position(0);\n+ direct.limit(limit);\n+ return direct;\n+ }\n+\n+ /**\n+ * Checks if the given address is supported by this address family.\n+ * \n+ * @param addr The address.\n+ * @param af The address family.\n+ * @return {@code true} if supported.\n+ */\n+ protected static final boolean isSupportedAddress(InetAddress addr, AFAddressFamily af) {\n+ return AFInetAddress.isSupportedAddress(addr, af);\n+ }\n+\n+ /**\n+ * Writes the native (system-level) representation of this address to the given buffer.\n+ * \n+ * The position of the target buffer will be at the end (i.e., after) the written data.\n+ * \n+ * @param buf The target buffer.\n+ * @throws IOException on error.\n+ */\n+ public final void writeNativeAddressTo(ByteBuffer buf) throws IOException {\n+ if (nativeAddress == null) {\n+ throw new IOException(\"Cannot access native address\");\n+ }\n+ buf.put(nativeAddress);\n+ }\n+\n+ /**\n+ * Creates a new socket connected to this address.\n+ * \n+ * @return The socket instance.\n+ * @throws IOException on error.\n+ */\n+ public AFSocket newConnectedSocket() throws IOException {\n+ AFSocket socket = getAddressFamily().newSocket();\n+ socket.connect(this);\n+ return socket;\n+ }\n+\n+ /**\n+ * Creates a new server socket bound to this address.\n+ * \n+ * @return The server socket instance.\n+ * @throws IOException on error.\n+ */\n+ public AFServerSocket newBoundServerSocket() throws IOException {\n+ AFServerSocket serverSocket = getAddressFamily().newServerSocket();\n+ serverSocket.bind(this);\n+ return serverSocket;\n+ }\n+\n+ /**\n+ * Creates a new server socket force-bound to this address (i.e., any additional call to\n+ * {@link ServerSocket#bind(SocketAddress)} will ignore the passed address and use this one\n+ * instead.\n+ * \n+ * @return The server socket instance.\n+ * @throws IOException on error.\n+ */\n+ public AFServerSocket newForceBoundServerSocket() throws IOException {\n+ AFServerSocket serverSocket = getAddressFamily().newServerSocket();\n+ serverSocket.forceBindAddress(this).bind(this);\n+ return serverSocket;\n+ }\n+\n+ /**\n+ * Tries to parse the given URI and return a corresponding {@link AFSocketAddress} for it.\n+ * \n+ * NOTE: Only certain URI schemes are supported, such as {@code unix://} (for\n+ * {@link AFUNIXSocketAddress}) and {@code tipc://} for {@link AFTIPCSocketAddress}.\n+ * \n+ * @param u The URI.\n+ * @return The address.\n+ * @throws SocketException on error.\n+ * @see AFAddressFamily#uriSchemes()\n+ */\n+ @SuppressWarnings(\"PMD.ShortMethodName\")\n+ public static AFSocketAddress of(URI u) throws SocketException {\n+ return of(u, -1);\n+ }\n+\n+ /**\n+ * Tries to parse the given URI and return a corresponding {@link AFSocketAddress} for it.\n+ * \n+ * NOTE: Only certain URI schemes are supported, such as {@code unix://} (for\n+ * {@link AFUNIXSocketAddress}) and {@code tipc://} for {@link AFTIPCSocketAddress}.\n+ * \n+ * @param u The URI.\n+ * @param overridePort The port to forcibly use, or {@code -1} for \"don't override\".\n+ * @return The address.\n+ * @throws SocketException on error.\n+ * @see AFAddressFamily#uriSchemes()\n+ */\n+ @SuppressWarnings(\"PMD.ShortMethodName\")\n+ public static AFSocketAddress of(URI u, int overridePort) throws SocketException {\n+ AFAddressFamily af = AFAddressFamily.getAddressFamily(u);\n+ if (af == null) {\n+ throw new SocketException(\"Cannot resolve AFSocketAddress from URI scheme: \" + u.getScheme());\n+ }\n+ return af.parseURI(u, overridePort);\n+ }\n+\n+ /**\n+ * Tries to create a URI based on this {@link AFSocketAddress}.\n+ * \n+ * @param scheme The target scheme.\n+ * @param template An optional template to reuse certain parameters (e.g., the \"path\" component\n+ * for an {@code http} request), or {@code null}.\n+ * @return The URI.\n+ * @throws IOException on error.\n+ */\n+ public URI toURI(String scheme, URI template) throws IOException {\n+ throw new IOException(\"Unsupported operation\");\n+ }\n+\n+ /**\n+ * Returns a address string that can be used with {@code socat}'s {@code SOCKET-CONNECT},\n+ * {@code SOCKET-LISTEN}, {@code SOCKET-DATAGRAM}, etc., address types, or {@code null} if the\n+ * address type is not natively supported by this platform.\n+ * \n+ * This call is mostly suited for debugging purposes. The resulting string is specific to the\n+ * platform the code is executed on, and thus may be different among platforms (or {@code null}).\n+ * \n+ * @param socketType The socket type, or {@code null} to omit from string.\n+ * @param socketProtocol The socket protocol, or {@code null} to omit from string.\n+ * @return The string (such as 1:0:x2f746d702f796f), or {@code null} if unable to retrieve.\n+ * @throws IOException on error.\n+ */\n+ public @Nullable @SuppressWarnings(\"PMD.NPathComplexity\") String toSocatAddressString(\n+ AFSocketType socketType, AFSocketProtocol socketProtocol) throws IOException {\n+\n+ if (SOCKADDR_NATIVE_FAMILY_OFFSET == -1 || SOCKADDR_NATIVE_DATA_OFFSET == -1) {\n+ return null;\n+ }\n+ if (nativeAddress == null) {\n+ return null;\n+ }\n+ if (socketProtocol != null && socketProtocol.getId() != 0) {\n+ throw new IOException(\"Protocol not (yet) supported\"); // FIXME\n+ }\n+\n+ int family = (nativeAddress.get(SOCKADDR_NATIVE_FAMILY_OFFSET) & 0xFF);\n+ int type = socketType == null ? -1 : NativeUnixSocket.sockTypeToNative(socketType.getId());\n+ StringBuilder sb = new StringBuilder();\n+ sb.append(family);\n+ if (type != -1) {\n+ sb.append(':');\n+ sb.append(type);\n+ }\n+ if (socketProtocol != null) {\n+ sb.append(':');\n+ sb.append(socketProtocol.getId()); // FIXME needs native conversion\n+ }\n+ sb.append(\":x\");\n+ int n = nativeAddress.limit();\n+ while (n > 1 && nativeAddress.get(n - 1) == 0) {\n+ n--;\n+ }\n+ for (int pos = SOCKADDR_NATIVE_DATA_OFFSET; pos < n; pos++) {\n+ byte b = nativeAddress.get(pos);\n+ sb.append(String.format(Locale.ENGLISH, \"%02x\", b));\n+ }\n+ return sb.toString();\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketAddressConfig.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketAddressConfig.java\nnew file mode 100644\nindex 000000000..33127e8bc\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketAddressConfig.java\n@@ -0,0 +1,73 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.net.SocketException;\n+import java.net.URI;\n+import java.util.Set;\n+\n+import org.newsclub.net.unix.AFSocketAddress.AFSocketAddressConstructor;\n+\n+/**\n+ * The implementation-specifics for a given {@link AFSocketAddress} subclass implementation.\n+ * \n+ * @param The supported address type.\n+ * @author Christian Kohlschütter\n+ * @see AFAddressFamilyConfig\n+ */\n+public abstract class AFSocketAddressConfig {\n+\n+ /**\n+ * Constructor.\n+ */\n+ protected AFSocketAddressConfig() {\n+ }\n+\n+ /**\n+ * Tries to parse the given address-specific URI.\n+ * \n+ * @param u The URI.\n+ * @param port The port to use, or {@code -1} for \"unspecified\".\n+ * @return The address.\n+ * @throws SocketException on error.\n+ */\n+ protected abstract A parseURI(URI u, int port) throws SocketException;\n+ \n+ /**\n+ * Returns the implementation's address constructor.\n+ * \n+ * @return The implementation's address constructor.\n+ */\n+ protected abstract AFSocketAddressConstructor addressConstructor();\n+\n+ /**\n+ * Returns the name of the implementation's selector provider class.\n+ * \n+ * @return The name of the implementation's selector provider class.\n+ */\n+ protected abstract String selectorProviderClassname();\n+\n+ /**\n+ * Returns the set of supported URI schemes that can be parsed via {@link #parseURI(URI,int)}.\n+ * \n+ * These schemes must be unique to this {@link AFSocketAddress} type.\n+ * \n+ * @return The set of supported URI schemes.\n+ */\n+ protected abstract Set uriSchemes();\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketAddressFromHostname.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketAddressFromHostname.java\nnew file mode 100644\nindex 000000000..ba1e1975b\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketAddressFromHostname.java\n@@ -0,0 +1,50 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.net.SocketAddress;\n+import java.net.SocketException;\n+\n+/**\n+ * Helps converting an internet \"hostname\" to an {@link AFSocketAddress}.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public interface AFSocketAddressFromHostname {\n+ /**\n+ * Translates a \"host\" string (and port) to an {@link AFSocketAddress}.\n+ * \n+ * @param host The hostname\n+ * @param port The port, or 0.\n+ * @return The {@link AFSocketAddress}\n+ * @throws SocketException If there was a problem converting the hostname\n+ * @throws NullPointerException If host was {@code null}.\n+ */\n+ SocketAddress addressFromHost(String host, int port) throws SocketException;\n+\n+ /**\n+ * Checks whether the given hostname is supported by this socket factory. If not, calls to\n+ * createSocket will cause a {@link SocketException}.\n+ * \n+ * @param host The host to check.\n+ * @return {@code true} if supported.\n+ */\n+ default boolean isHostnameSupported(String host) {\n+ return host != null;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketCapability.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketCapability.java\nnew file mode 100644\nindex 000000000..698510e12\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketCapability.java\n@@ -0,0 +1,95 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.lang.ProcessBuilder.Redirect;\n+\n+/**\n+ * Describes junixsocket capabilities the current environment (system platform, native library,\n+ * etc.) may or may not support.\n+ * \n+ * You can check whether your environment supports a given capability by calling\n+ * {@link AFSocket#supports(AFSocketCapability)}.\n+ */\n+public enum AFSocketCapability {\n+ // see org_newsclub_net_unix_NativeUnixSocket.c in junixsocket-native\n+\n+ /** Socket supports retrieving peer credentials. */\n+ CAPABILITY_PEER_CREDENTIALS(0),\n+\n+ /** Socket supports sending and receiving ancillary messages. */\n+ CAPABILITY_ANCILLARY_MESSAGES(1),\n+\n+ /** Socket supports passing file descriptors via ancillary messages. */\n+ CAPABILITY_FILE_DESCRIPTORS(2),\n+\n+ /** Socket addressing supports the abstract namespace (Linux). */\n+ CAPABILITY_ABSTRACT_NAMESPACE(3),\n+\n+ /** Support for AF_UNIX datagrams (not on Windows yet). */\n+ CAPABILITY_UNIX_DATAGRAMS(4),\n+\n+ /**\n+ * A pair of interconnected sockets can be created natively as AF_UNIX sockets.\n+ * \n+ * This currently not possible on Windows, but instead emulated via anonymous AF_INET ports when\n+ * you use {@link AFSocketPair}. Other systems, such as OSv, may provide partial implementations\n+ * of pipe-based (i.e., non-socket) pairs.\n+ */\n+ CAPABILITY_NATIVE_SOCKETPAIR(5),\n+\n+ /**\n+ * A file descriptor can be converted to {@link Redirect}.\n+ * \n+ * This feature currently uses Java SDK internals that may change/disappear.\n+ */\n+ CAPABILITY_FD_AS_REDIRECT(6),\n+\n+ /**\n+ * Support for AF_TIPC.\n+ * \n+ * Availability of this feature is checked upon launch and therefore loading the \"tipc\" kernel\n+ * module at a later point may not be properly reflected.\n+ */\n+ CAPABILITY_TIPC(7),\n+\n+ /**\n+ * Support for AF_UNIX.\n+ * \n+ * Availability of this feature is checked upon launch and therefore, on systems adding support at\n+ * a later point, may not be properly reflected when checking at a later point.\n+ * \n+ * NOTE: While this capability is typically supported on most systems that can actually load a\n+ * junixsocket JNI library, it is unavailable for older Windows versions (such as 8.1, 10 before\n+ * AFUNIX.SYS was included, etc.) and on systems where support for UNIX domain sockets is actively\n+ * disabled. Therefore, it is still recommended to check for this capability.\n+ */\n+ CAPABILITY_UNIX_DOMAIN(8),\n+\n+ ; // end of list\n+\n+ private final int bitmask;\n+\n+ AFSocketCapability(int bit) {\n+ this.bitmask = 1 << bit;\n+ }\n+\n+ int getBitmask() {\n+ return bitmask;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketChannel.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketChannel.java\nnew file mode 100644\nindex 000000000..6175c5894\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketChannel.java\n@@ -0,0 +1,307 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.net.SocketAddress;\n+import java.net.SocketOption;\n+import java.nio.ByteBuffer;\n+import java.nio.channels.SocketChannel;\n+import java.nio.channels.spi.SelectorProvider;\n+import java.util.Objects;\n+import java.util.Set;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * A selectable channel for stream-oriented connecting sockets.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFSocketChannel extends SocketChannel implements\n+ AFSomeSocket, AFSocketExtensions {\n+ private final @NonNull AFSocket afSocket;\n+ private final AtomicBoolean connectPending = new AtomicBoolean(false);\n+\n+ /**\n+ * Creates a new socket channel for the given socket, using the given {@link SelectorProvider}.\n+ * \n+ * @param socket The socket.\n+ * @param sp The {@link SelectorProvider}.\n+ */\n+ @SuppressWarnings(\"null\")\n+ protected AFSocketChannel(AFSocket socket, AFSelectorProvider sp) {\n+ super(sp);\n+ this.afSocket = Objects.requireNonNull(socket);\n+ }\n+\n+ /**\n+ * Returns the corresponding {@link AFSocket}.\n+ * \n+ * @return The corresponding socket.\n+ */\n+ protected final AFSocket getAFSocket() {\n+ return afSocket;\n+ }\n+\n+ /**\n+ * A reference to a method that provides an {@link AFSocket} instance.\n+ * \n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ */\n+ @FunctionalInterface\n+ protected interface AFSocketSupplier {\n+ /**\n+ * Returns a new {@link AFSocket} instance.\n+ * \n+ * @return The instance.\n+ * @throws IOException on error.\n+ */\n+ AFSocket newInstance() throws IOException;\n+ }\n+\n+ /**\n+ * Opens a socket channel.\n+ *\n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @param supplier The AFSocketChannel constructor.\n+ * \n+ * @return The new channel\n+ * @throws IOException on error.\n+ */\n+ protected static final AFSocketChannel open(\n+ AFSocketSupplier supplier) throws IOException {\n+ return supplier.newInstance().getChannel();\n+ }\n+\n+ /**\n+ * Opens a socket channel, connecting to the given socket address.\n+ *\n+ * @param The concrete {@link AFSocketAddress} that is supported by this type.\n+ * @param remote The socket address to connect to.\n+ * @param supplier The AFSocketChannel constructor.\n+ * @return The new channel\n+ * @throws IOException on error.\n+ */\n+ protected static final AFSocketChannel open(\n+ AFSocketSupplier supplier, SocketAddress remote) throws IOException {\n+ @SuppressWarnings(\"resource\")\n+ AFSocketChannel sc = open(supplier);\n+ try {\n+ sc.connect(remote);\n+ } catch (Throwable x) { // NOPMD\n+ try {\n+ sc.close();\n+ } catch (Throwable suppressed) { // NOPMD\n+ x.addSuppressed(suppressed);\n+ }\n+ throw x;\n+ }\n+ assert sc.isConnected();\n+ return sc;\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ @Override\n+ public final T getOption(SocketOption name) throws IOException {\n+ if (name instanceof AFSocketOption) {\n+ return getAFCore().getOption((AFSocketOption) name);\n+ }\n+ Integer optionId = SocketOptionsMapper.resolve(name);\n+ if (optionId == null) {\n+ throw new UnsupportedOperationException(\"unsupported option\");\n+ } else {\n+ return (T) afSocket.getAFImpl().getOption(optionId.intValue());\n+ }\n+ }\n+\n+ @Override\n+ public final AFSocketChannel setOption(SocketOption name, T value) throws IOException {\n+ if (name instanceof AFSocketOption) {\n+ getAFCore().setOption((AFSocketOption) name, value);\n+ return this;\n+ }\n+ Integer optionId = SocketOptionsMapper.resolve(name);\n+ if (optionId == null) {\n+ throw new UnsupportedOperationException(\"unsupported option\");\n+ } else {\n+ afSocket.getAFImpl().setOption(optionId.intValue(), value);\n+ }\n+ return this;\n+ }\n+\n+ @Override\n+ public final Set> supportedOptions() {\n+ return SocketOptionsMapper.SUPPORTED_SOCKET_OPTIONS;\n+ }\n+\n+ @Override\n+ public final AFSocketChannel bind(SocketAddress local) throws IOException {\n+ afSocket.bind(local);\n+ return this;\n+ }\n+\n+ @Override\n+ public final AFSocketChannel shutdownInput() throws IOException {\n+ afSocket.getAFImpl().shutdownInput();\n+ return this;\n+ }\n+\n+ @Override\n+ public final AFSocketChannel shutdownOutput() throws IOException {\n+ afSocket.getAFImpl().shutdownOutput();\n+ return this;\n+ }\n+\n+ @Override\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n+ public final AFSocket socket() {\n+ return afSocket;\n+ }\n+\n+ @Override\n+ public final boolean isConnected() {\n+ boolean connected = afSocket.isConnected();\n+ if (connected) {\n+ connectPending.set(false);\n+ }\n+ return connected;\n+ }\n+\n+ @Override\n+ public final boolean isConnectionPending() {\n+ return connectPending.get();\n+ }\n+\n+ @Override\n+ public final boolean connect(SocketAddress remote) throws IOException {\n+ boolean connected = afSocket.connect0(remote, 0);\n+ if (!connected) {\n+ connectPending.set(true);\n+ }\n+ return connected;\n+ }\n+\n+ @Override\n+ public final boolean finishConnect() throws IOException {\n+ if (isConnected()) {\n+ return true;\n+ } else if (!isConnectionPending()) {\n+ return false;\n+ }\n+\n+ boolean connected = NativeUnixSocket.finishConnect(afSocket.getFileDescriptor())\n+ || isConnected();\n+ if (connected) {\n+ connectPending.set(false);\n+ }\n+ return connected;\n+ }\n+\n+ @Override\n+ public final A getRemoteAddress() throws IOException {\n+ return getRemoteSocketAddress();\n+ }\n+\n+ @Override\n+ public final A getRemoteSocketAddress() {\n+ return afSocket.getRemoteSocketAddress();\n+ }\n+\n+ @Override\n+ public final int read(ByteBuffer dst) throws IOException {\n+ return afSocket.getAFImpl().read(dst, null);\n+ }\n+\n+ @Override\n+ public final long read(ByteBuffer[] dsts, int offset, int length) throws IOException {\n+ if (length == 0) {\n+ return 0;\n+ }\n+ // FIXME support more than one buffer for scatter-gather access\n+ return read(dsts[offset]);\n+ }\n+\n+ @Override\n+ public final long write(ByteBuffer[] srcs, int offset, int length) throws IOException {\n+ if (length == 0) {\n+ return 0;\n+ }\n+ // FIXME support more than one buffer for scatter-gather access\n+ return write(srcs[offset]);\n+ }\n+\n+ @Override\n+ public final int write(ByteBuffer src) throws IOException {\n+ return afSocket.getAFImpl().write(src);\n+ }\n+\n+ @Override\n+ public final A getLocalAddress() throws IOException {\n+ return getLocalSocketAddress();\n+ }\n+\n+ @Override\n+ public final A getLocalSocketAddress() {\n+ return afSocket.getLocalSocketAddress();\n+ }\n+\n+ @Override\n+ protected final void implCloseSelectableChannel() throws IOException {\n+ afSocket.close();\n+ }\n+\n+ @Override\n+ protected final void implConfigureBlocking(boolean block) throws IOException {\n+ getAFCore().implConfigureBlocking(block);\n+ }\n+\n+ @Override\n+ public final int getAncillaryReceiveBufferSize() {\n+ return afSocket.getAncillaryReceiveBufferSize();\n+ }\n+\n+ @Override\n+ public final void setAncillaryReceiveBufferSize(int size) {\n+ afSocket.setAncillaryReceiveBufferSize(size);\n+ }\n+\n+ @Override\n+ public final void ensureAncillaryReceiveBufferSize(int minSize) {\n+ afSocket.ensureAncillaryReceiveBufferSize(minSize);\n+ }\n+\n+ final AFSocketCore getAFCore() {\n+ return afSocket.getAFImpl().getCore();\n+ }\n+\n+ @Override\n+ public final FileDescriptor getFileDescriptor() throws IOException {\n+ return afSocket.getFileDescriptor();\n+ }\n+\n+ @Override\n+ public final String toString() {\n+ return super.toString() + afSocket.toStringSuffix();\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketCore.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketCore.java\nnew file mode 100644\nindex 000000000..7843c8a5c\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketCore.java\n@@ -0,0 +1,135 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.lang.reflect.InvocationTargetException;\n+import java.nio.ByteBuffer;\n+import java.util.concurrent.atomic.AtomicLong;\n+\n+/**\n+ * A shared core that is common for all AF* sockets (datagrams, streams).\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+class AFSocketCore extends AFCore {\n+ private static final int SHUT_RD_WR = 2;\n+\n+ /**\n+ * We keep track of the server's inode to detect when another server connects to our address.\n+ */\n+ final AtomicLong inode = new AtomicLong(-1);\n+\n+ AFSocketAddress socketAddress;\n+\n+ private final AFAddressFamily af;\n+\n+ protected AFSocketCore(Object observed, FileDescriptor fd,\n+ AncillaryDataSupport ancillaryDataSupport, AFAddressFamily af, boolean datagramMode) {\n+ super(observed, fd, ancillaryDataSupport, datagramMode);\n+ this.af = af;\n+ }\n+\n+ protected AFAddressFamily addressFamily() {\n+ return af;\n+ }\n+\n+ @Override\n+ protected void doClose() throws IOException {\n+ NativeUnixSocket.shutdown(fd, SHUT_RD_WR);\n+ unblockAccepts();\n+\n+ super.doClose();\n+ }\n+\n+ protected void unblockAccepts() {\n+ }\n+\n+ AFSocketAddress receive(ByteBuffer dst) throws IOException {\n+ ByteBuffer socketAddressBuffer = AFSocketAddress.SOCKETADDRESS_BUFFER_TL.get();\n+ int read = read(dst, socketAddressBuffer, 0);\n+ if (read > 0) {\n+ return AFSocketAddress.ofInternal(socketAddressBuffer, af);\n+ } else {\n+ return null;\n+ }\n+ }\n+\n+ boolean isConnected(boolean boundOk) {\n+ try {\n+ if (fd.valid()) {\n+ switch (NativeUnixSocket.socketStatus(fd)) {\n+ case NativeUnixSocket.SOCKETSTATUS_CONNECTED:\n+ return true;\n+ case NativeUnixSocket.SOCKETSTATUS_BOUND:\n+ if (boundOk) {\n+ return true;\n+ }\n+ break;\n+ default:\n+ }\n+ }\n+ } catch (IOException e) {\n+ throw new IllegalStateException(e);\n+ }\n+ return false;\n+ }\n+\n+ @SuppressWarnings({\"unchecked\", \"null\"})\n+ T getOption(AFSocketOption name) throws IOException {\n+ Class type = name.type();\n+ if (Boolean.class.isAssignableFrom(type)) {\n+ return (T) (Object) (NativeUnixSocket.getSocketOption(fd, name.level(), name.optionName(),\n+ Integer.class).intValue() != 0);\n+ } else if (NamedInteger.HasOfValue.class.isAssignableFrom(type)) {\n+ int v = NativeUnixSocket.getSocketOption(fd, name.level(), name.optionName(), Integer.class);\n+ try {\n+ return (T) type.getMethod(\"ofValue\", int.class).invoke(null, v);\n+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException\n+ | NoSuchMethodException | SecurityException e) {\n+ throw new IOException(\"Value casting problem\", e);\n+ }\n+ } else {\n+ return NativeUnixSocket.getSocketOption(fd, name.level(), name.optionName(), type);\n+ }\n+ }\n+\n+ void setOption(AFSocketOption name, T value) throws IOException {\n+ final Object val;\n+ if (value instanceof Boolean) {\n+ val = (((Boolean) value).booleanValue() ? 1 : 0);\n+ } else if (value instanceof NamedInteger) {\n+ val = ((NamedInteger) value).value();\n+ } else {\n+ val = value;\n+ }\n+ int level = name.level();\n+ int optionName = name.optionName();\n+ NativeUnixSocket.setSocketOption(fd, level, optionName, val);\n+ if (level == 271 && optionName == 135) {\n+ // AFTIPCSocketOptions.TIPC_GROUP_JOIN\n+ // unclear why, but sleeping for at least 1ms prevents issues with GROUP_JOIN\n+ try {\n+ Thread.sleep(1);\n+ } catch (InterruptedException e) {\n+ // ignore\n+ }\n+ }\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketExtensions.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketExtensions.java\nnew file mode 100644\nindex 000000000..9fd591d26\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketExtensions.java\n@@ -0,0 +1,55 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+/**\n+ * Defines certain methods that all junixsocket socket implementations share and extend beyond the\n+ * standard socket API.\n+ * \n+ * The set of features include methods to support working with ancillary messages (such as file\n+ * descriptors) as well as socket credentials.\n+ * \n+ * Keep in mind that the platform this code runs on may not support these features, and exceptions\n+ * may be thrown when not checking for the corresponding {@link AFSocketCapability} first.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public interface AFSocketExtensions {\n+ /**\n+ * Returns the size of the receive buffer for ancillary messages (in bytes).\n+ * \n+ * @return The size.\n+ */\n+ int getAncillaryReceiveBufferSize();\n+\n+ /**\n+ * Sets the size of the receive buffer for ancillary messages (in bytes).\n+ * \n+ * To disable handling ancillary messages, set it to 0 (default).\n+ * \n+ * @param size The size.\n+ */\n+ void setAncillaryReceiveBufferSize(int size);\n+\n+ /**\n+ * Ensures a minimum ancillary receive buffer size.\n+ * \n+ * @param minSize The minimum size (in bytes).\n+ */\n+ void ensureAncillaryReceiveBufferSize(int minSize);\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketFactory.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketFactory.java\nnew file mode 100644\nindex 000000000..833871132\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketFactory.java\n@@ -0,0 +1,195 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.IOException;\n+import java.net.InetAddress;\n+import java.net.Socket;\n+import java.net.SocketAddress;\n+import java.net.SocketException;\n+import java.util.Objects;\n+\n+import javax.net.SocketFactory;\n+\n+/**\n+ * The base for a SocketFactory that connects to UNIX sockets.\n+ * \n+ * Typically, the \"hostname\" is used as a reference to a socketFile on the file system. The actual\n+ * mapping is left to the implementor.\n+ * \n+ * @see AFUNIXSocketFactory\n+ */\n+public abstract class AFSocketFactory extends SocketFactory implements\n+ AFSocketAddressFromHostname {\n+\n+ /**\n+ * Creates a new socket factory instance.\n+ */\n+ protected AFSocketFactory() {\n+ super();\n+ }\n+\n+ /**\n+ * Checks whether the given {@link InetAddress} is supported by this socket factory. If not, calls\n+ * to createSocket will cause a {@link SocketException}.\n+ * \n+ * By default, this only checks the hostname part of the address via\n+ * {@link #isHostnameSupported(String)}.\n+ * \n+ * @param address The address to check.\n+ * @return {@code true} if supported.\n+ */\n+ protected final boolean isInetAddressSupported(InetAddress address) {\n+ return address != null && isHostnameSupported(address.getHostName());\n+ }\n+\n+ @Override\n+ public abstract Socket createSocket() throws SocketException;\n+\n+ /**\n+ * Creates a new {@link AFSocket}, connected to the given address.\n+ * \n+ * @param addr The address to connect to.\n+ * @return The socket instance.\n+ * @throws IOException on error.\n+ */\n+ protected abstract Socket connectTo(A addr) throws IOException;\n+\n+ @SuppressWarnings(\"unchecked\")\n+ private Socket connectTo(SocketAddress addr) throws IOException {\n+ if (addr instanceof AFSocketAddress) {\n+ return connectTo((A) addr);\n+ } else {\n+ Socket sock = new Socket();\n+ sock.connect(addr);\n+ return sock;\n+ }\n+ }\n+\n+ @Override\n+ public final Socket createSocket(String host, int port) throws IOException {\n+ if (!isHostnameSupported(host)) {\n+ throw new SocketException(\"Unsupported hostname\");\n+ }\n+ if (port < 0) {\n+ throw new IllegalArgumentException(\"Illegal port\");\n+ }\n+\n+ SocketAddress socketAddress = addressFromHost(host, port);\n+ return connectTo(socketAddress);\n+ }\n+\n+ @Override\n+ public final Socket createSocket(String host, int port, InetAddress localHost, int localPort)\n+ throws IOException {\n+ if (!isHostnameSupported(host)) {\n+ throw new SocketException(\"Unsupported hostname\");\n+ }\n+ if (localPort < 0) {\n+ throw new IllegalArgumentException(\"Illegal local port\");\n+ }\n+ // NOTE: we simply ignore localHost and localPort\n+ return createSocket(host, port);\n+ }\n+\n+ @Override\n+ public final Socket createSocket(InetAddress address, int port) throws IOException {\n+ if (!isInetAddressSupported(address)) {\n+ throw new SocketException(\"Unsupported address\");\n+ }\n+ String hostname = address.getHostName();\n+ if (!isHostnameSupported(hostname)) {\n+ throw new SocketException(\"Unsupported hostname\");\n+ }\n+ return createSocket(hostname, port);\n+ }\n+\n+ @Override\n+ public final Socket createSocket(InetAddress address, int port, InetAddress localAddress,\n+ int localPort) throws IOException {\n+ if (!isInetAddressSupported(address)) {\n+ throw new SocketException(\"Unsupported address\");\n+ }\n+ if (localPort < 0) {\n+ throw new IllegalArgumentException(\"Illegal local port\");\n+ }\n+ // NOTE: we simply ignore localAddress and localPort\n+ return createSocket(address, port);\n+ }\n+\n+ /**\n+ * A socket factory that always connects to a fixed socket address, no matter what.\n+ */\n+ public static final class FixedAddressSocketFactory extends AFSocketFactory {\n+ private final SocketAddress forceAddr;\n+\n+ /**\n+ * Creates a {@link FixedAddressSocketFactory}.\n+ * \n+ * @param address The address to use for all connections.\n+ */\n+ public FixedAddressSocketFactory(SocketAddress address) {\n+ super();\n+ this.forceAddr = Objects.requireNonNull(address);\n+ }\n+\n+ @Override\n+ public boolean isHostnameSupported(String host) {\n+ return true;\n+ }\n+\n+ @Override\n+ public SocketAddress addressFromHost(String host, int port) throws SocketException {\n+ return forceAddr;\n+ }\n+\n+ @Override\n+ public Socket createSocket() throws SocketException {\n+ try {\n+ if (forceAddr instanceof AFSocketAddress) {\n+ AFSocket socket = ((AFSocketAddress) forceAddr).getAddressFamily().newSocket();\n+ socket.forceConnectAddress(forceAddr);\n+ return socket;\n+ } else {\n+ return new Socket() {\n+ @Override\n+ public void connect(SocketAddress endpoint) throws IOException {\n+ super.connect(forceAddr);\n+ }\n+\n+ @Override\n+ public void connect(SocketAddress endpoint, int timeout) throws IOException {\n+ super.connect(forceAddr, timeout);\n+ }\n+ };\n+ }\n+ } catch (SocketException e) {\n+ throw e;\n+ } catch (IOException e) {\n+ throw (SocketException) new SocketException().initCause(e);\n+ }\n+ }\n+\n+ @Override\n+ protected Socket connectTo(AFSocketAddress addr) throws IOException {\n+ Socket sock = createSocket();\n+ sock.connect(forceAddr);\n+ return sock;\n+ }\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketImpl.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketImpl.java\nnew file mode 100644\nindex 000000000..0ee5884ed\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketImpl.java\n@@ -0,0 +1,952 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.EOFException;\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.io.InterruptedIOException;\n+import java.io.OutputStream;\n+import java.net.InetAddress;\n+import java.net.SocketAddress;\n+import java.net.SocketException;\n+import java.net.SocketImpl;\n+import java.net.SocketOption;\n+import java.net.SocketOptions;\n+import java.nio.ByteBuffer;\n+import java.util.Set;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+import java.util.concurrent.atomic.AtomicInteger;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.Nullable;\n+\n+/**\n+ * junixsocket-based {@link SocketImpl}.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+@SuppressWarnings({\"PMD.CyclomaticComplexity\"})\n+public abstract class AFSocketImpl extends SocketImplShim {\n+ private static final int SHUT_RD = 0;\n+ private static final int SHUT_WR = 1;\n+ private static final int SHUT_RD_WR = 2;\n+ private static final int SHUTDOWN_RD_WR = (1 << SHUT_RD) | (1 << SHUT_WR);\n+\n+ private final AFSocketStreamCore core;\n+ final AncillaryDataSupport ancillaryDataSupport = new AncillaryDataSupport();\n+\n+ private final AtomicBoolean bound = new AtomicBoolean(false);\n+ private Boolean createType = null;\n+ private final AtomicBoolean connected = new AtomicBoolean(false);\n+\n+ private volatile boolean closedInputStream = false;\n+ private volatile boolean closedOutputStream = false;\n+\n+ private final AFInputStream in;\n+ private final AFOutputStream out;\n+\n+ private boolean reuseAddr = true;\n+\n+ private final AtomicInteger socketTimeout = new AtomicInteger(0);\n+ private final AFAddressFamily addressFamily;\n+\n+ private int shutdownState = 0;\n+\n+ private AFSocketImplExtensions implExtensions = null;\n+\n+ /**\n+ * When the {@link AFSocketImpl} becomes unreachable (but not yet closed), we must ensure that the\n+ * underlying socket and all related file descriptors are closed.\n+ *\n+ * @author Christian Kohlschütter\n+ */\n+ static final class AFSocketStreamCore extends AFSocketCore {\n+ private final AtomicInteger pendingAccepts = new AtomicInteger(0);\n+\n+ AFSocketStreamCore(AFSocketImpl observed, FileDescriptor fd,\n+ AncillaryDataSupport ancillaryDataSupport, AFAddressFamily af) {\n+ super(observed, fd, ancillaryDataSupport, af, false);\n+ }\n+\n+ private void incPendingAccepts() throws SocketException {\n+ if (pendingAccepts.incrementAndGet() >= Integer.MAX_VALUE) {\n+ throw new SocketException(\"Too many pending accepts\");\n+ }\n+ }\n+\n+ private void decPendingAccepts() throws SocketException {\n+ pendingAccepts.decrementAndGet();\n+ }\n+\n+ protected void createSocket(FileDescriptor fdTarget, AFSocketType type) throws IOException {\n+ NativeUnixSocket.createSocket(fdTarget, addressFamily().getDomain(), type.getId());\n+ }\n+\n+ /**\n+ * Unblock other threads that are currently waiting on accept, simply by connecting to the\n+ * socket.\n+ */\n+ @Override\n+ protected void unblockAccepts() {\n+ if (socketAddress == null || socketAddress.getBytes() == null || inode.get() < 0) {\n+ return;\n+ }\n+\n+ while (pendingAccepts.get() > 0) {\n+ try {\n+ FileDescriptor tmpFd = new FileDescriptor();\n+\n+ try {\n+ createSocket(tmpFd, AFSocketType.SOCK_STREAM);\n+ ByteBuffer ab = socketAddress.getNativeAddressDirectBuffer();\n+ NativeUnixSocket.connect(ab, ab.limit(), tmpFd, inode.get());\n+ } catch (IOException e) {\n+ // there's nothing more we can do to unlock these accepts\n+ // (e.g., SocketException: No such file or directory)\n+ return;\n+ }\n+ try {\n+ NativeUnixSocket.shutdown(tmpFd, SHUT_RD_WR);\n+ } catch (Exception e) {\n+ // ignore\n+ }\n+ try {\n+ NativeUnixSocket.close(tmpFd);\n+ } catch (Exception e) {\n+ // ignore\n+ }\n+ } catch (Exception e) {\n+ // ignore\n+ }\n+\n+ // sleep a little to give the cleaners some CPU time to actually clean up\n+ try {\n+ Thread.sleep(5);\n+ } catch (InterruptedException e) {\n+ // ignore\n+ }\n+ }\n+ }\n+ }\n+\n+ /**\n+ * Creates a new {@link AFSocketImpl} instance.\n+ * \n+ * @param addressFamily The address family.\n+ * @param fdObj The socket's {@link FileDescriptor}.\n+ * @throws SocketException on error.\n+ */\n+ protected AFSocketImpl(AFAddressFamily<@NonNull A> addressFamily, FileDescriptor fdObj)\n+ throws SocketException {\n+ super();\n+ this.addressFamily = addressFamily;\n+ this.address = InetAddress.getLoopbackAddress();\n+ this.core = new AFSocketStreamCore(this, fdObj, ancillaryDataSupport, addressFamily);\n+ this.fd = core.fd;\n+ this.in = newInputStream();\n+ this.out = newOutputStream();\n+ }\n+\n+ /**\n+ * Creates a new {@link InputStream} for this socket.\n+ * \n+ * @return The new stream.\n+ */\n+ protected final AFInputStream newInputStream() {\n+ return new AFInputStreamImpl();\n+ }\n+\n+ /**\n+ * Creates a new {@link OutputStream} for this socket.\n+ * \n+ * @return The new stream.\n+ */\n+ protected final AFOutputStream newOutputStream() {\n+ return new AFOutputStreamImpl();\n+ }\n+\n+ final FileDescriptor getFD() {\n+ return fd;\n+ }\n+\n+ // CPD-OFF\n+ final boolean isConnected() {\n+ if (connected.get()) {\n+ return true;\n+ }\n+ if (isClosed()) {\n+ return false;\n+ }\n+ if (core.isConnected(false)) {\n+ connected.set(true);\n+ return true;\n+ }\n+ return false;\n+ }\n+\n+ final boolean isBound() {\n+ if (bound.get()) {\n+ return true;\n+ }\n+ if (isClosed()) {\n+ return false;\n+ }\n+ if (core.isConnected(true)) {\n+ bound.set(true);\n+ return true;\n+ }\n+ return false;\n+ }\n+\n+ final AFSocketCore getCore() {\n+ return core;\n+ }\n+\n+ private boolean isClosed() {\n+ return core.isClosed();\n+ }\n+ // CPD-ON\n+\n+ @Override\n+ protected final void accept(SocketImpl socket) throws IOException {\n+ accept0(socket);\n+ }\n+\n+ final boolean accept0(SocketImpl socket) throws IOException {\n+ FileDescriptor fdesc = core.validFdOrException();\n+ if (isClosed()) {\n+ throw new SocketException(\"Socket is closed\");\n+ } else if (!isBound()) {\n+ throw new SocketException(\"Socket is not bound\");\n+ }\n+\n+ AFSocketAddress socketAddress = core.socketAddress;\n+ if (socketAddress == null) {\n+ core.socketAddress = socketAddress = getLocalSocketAddress();\n+ }\n+ if (socketAddress == null) {\n+ throw new SocketException(\"Socket is not bound\");\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ final AFSocketImpl si = (AFSocketImpl) socket;\n+ try {\n+ core.incPendingAccepts();\n+ ByteBuffer ab = socketAddress.getNativeAddressDirectBuffer();\n+ if (!NativeUnixSocket.accept(ab, ab.limit(), fdesc, si.fd, core.inode.get(), socketTimeout\n+ .get())) {\n+ return false;\n+ }\n+\n+ if (!isBound() || isClosed()) {\n+ try {\n+ NativeUnixSocket.shutdown(si.fd, SHUT_RD_WR);\n+ } catch (Exception e) {\n+ // ignore\n+ }\n+ try {\n+ NativeUnixSocket.close(si.fd);\n+ } catch (Exception e) {\n+ // ignore\n+ }\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+ } finally {\n+ core.decPendingAccepts();\n+ }\n+ si.setSocketAddress(socketAddress);\n+ si.connected.set(true);\n+\n+ return true;\n+ }\n+\n+ final void setSocketAddress(AFSocketAddress socketAddress) {\n+ if (socketAddress == null) {\n+ this.core.socketAddress = null;\n+ this.address = null;\n+ this.localport = -1;\n+ } else {\n+ this.core.socketAddress = socketAddress;\n+ this.address = socketAddress.getAddress();\n+ if (this.localport <= 0) {\n+ this.localport = socketAddress.getPort();\n+ }\n+ }\n+ }\n+\n+ @Override\n+ protected final int available() throws IOException {\n+ FileDescriptor fdesc = core.validFdOrException();\n+ return NativeUnixSocket.available(fdesc, core.getThreadLocalDirectByteBuffer(0));\n+ }\n+\n+ final void bind(SocketAddress addr, int options) throws IOException {\n+ if (addr == null) {\n+ throw new IllegalArgumentException(\"Cannot bind to null address\");\n+ }\n+ if (!(addr instanceof AFSocketAddress)) {\n+ throw new SocketException(\"Cannot bind to this type of address: \" + addr.getClass());\n+ }\n+\n+ bound.set(true);\n+\n+ if (addr == AFSocketAddress.INTERNAL_DUMMY_BIND) { // NOPMD\n+ core.inode.set(0);\n+ return;\n+ }\n+\n+ AFSocketAddress socketAddress = (AFSocketAddress) addr;\n+\n+ this.setSocketAddress(socketAddress);\n+ ByteBuffer ab = socketAddress.getNativeAddressDirectBuffer();\n+ core.inode.set(NativeUnixSocket.bind(ab, ab.limit(), fd, options));\n+ core.validFdOrException();\n+ }\n+\n+ @Override\n+ @SuppressWarnings(\"hiding\")\n+ protected final void bind(InetAddress host, int port) throws IOException {\n+ // ignored\n+ }\n+\n+ private void checkClose() throws IOException {\n+ if (closedInputStream && closedOutputStream) {\n+ close();\n+ }\n+ }\n+\n+ @Override\n+ protected final void close() throws IOException {\n+ shutdown();\n+ core.runCleaner();\n+ }\n+\n+ @Override\n+ @SuppressWarnings(\"hiding\")\n+ protected final void connect(String host, int port) throws IOException {\n+ throw new SocketException(\"Cannot bind to this type of address: \" + InetAddress.class);\n+ }\n+\n+ @Override\n+ @SuppressWarnings(\"hiding\")\n+ protected final void connect(InetAddress address, int port) throws IOException {\n+ throw new SocketException(\"Cannot bind to this type of address: \" + InetAddress.class);\n+ }\n+\n+ @Override\n+ protected final void connect(SocketAddress addr, int connectTimeout) throws IOException {\n+ connect0(addr, connectTimeout);\n+ }\n+\n+ final boolean connect0(SocketAddress addr, int connectTimeout) throws IOException {\n+ if (addr == AFSocketAddress.INTERNAL_DUMMY_CONNECT) { // NOPMD\n+ this.connected.set(true);\n+ return true;\n+ } else if (addr == AFSocketAddress.INTERNAL_DUMMY_CONNECT) { // NOPMD)\n+ return false;\n+ }\n+\n+ if (!(addr instanceof AFSocketAddress)) {\n+ throw new SocketException(\"Cannot connect to this type of address: \" + addr.getClass());\n+ }\n+\n+ AFSocketAddress socketAddress = (AFSocketAddress) addr;\n+ ByteBuffer ab = socketAddress.getNativeAddressDirectBuffer();\n+ boolean success = NativeUnixSocket.connect(ab, ab.limit(), fd, -1);\n+ if (success) {\n+ setSocketAddress(socketAddress);\n+ this.connected.set(true);\n+ }\n+ core.validFdOrException();\n+ return success;\n+ }\n+\n+ @Override\n+ protected final void create(boolean stream) throws IOException {\n+ if (isClosed()) {\n+ throw new SocketException(\"Already closed\");\n+ }\n+ if (fd.valid()) {\n+ if (createType != null) {\n+ if (createType.booleanValue() != stream) {\n+ throw new IllegalStateException(\"Already created with different mode\");\n+ }\n+ } else {\n+ createType = stream;\n+ }\n+ return;\n+ }\n+ createType = stream;\n+ createSocket(fd, stream ? AFSocketType.SOCK_STREAM : AFSocketType.SOCK_DGRAM);\n+ }\n+\n+ @Override\n+ protected final AFInputStream getInputStream() throws IOException {\n+ if (!isConnected() && !isBound()) {\n+ throw new IOException(\"Not connected/not bound\");\n+ }\n+ core.validFdOrException();\n+ return in;\n+ }\n+\n+ @Override\n+ protected final AFOutputStream getOutputStream() throws IOException {\n+ if (!isClosed() && !isBound()) {\n+ throw new IOException(\"Not connected/not bound\");\n+ }\n+ core.validFdOrException();\n+ return out;\n+ }\n+\n+ @Override\n+ protected final void listen(int backlog) throws IOException {\n+ FileDescriptor fdesc = core.validFdOrException();\n+ if (backlog <= 0) {\n+ backlog = 50;\n+ }\n+ NativeUnixSocket.listen(fdesc, backlog);\n+ }\n+\n+ @Override\n+ protected final boolean supportsUrgentData() {\n+ return false;\n+ }\n+\n+ @Override\n+ protected final void sendUrgentData(int data) throws IOException {\n+ throw new UnsupportedOperationException();\n+ }\n+\n+ private final class AFInputStreamImpl extends AFInputStream {\n+ private volatile boolean streamClosed = false;\n+ private final AtomicBoolean eofReached = new AtomicBoolean(false);\n+\n+ private final int opt = (core.isBlocking() ? 0 : NativeUnixSocket.OPT_NON_BLOCKING);\n+\n+ @Override\n+ public int read(byte[] buf, int off, int len) throws IOException {\n+ if (streamClosed) {\n+ throw new IOException(\"This InputStream has already been closed.\");\n+ }\n+ if (eofReached.get()) {\n+ return -1;\n+ }\n+\n+ FileDescriptor fdesc = core.validFdOrException();\n+ if (len == 0) {\n+ return 0;\n+ } else if (off < 0 || len < 0 || (len > buf.length - off)) {\n+ throw new IndexOutOfBoundsException();\n+ }\n+\n+ try {\n+ return NativeUnixSocket.read(fdesc, buf, off, len, opt, ancillaryDataSupport, socketTimeout\n+ .get());\n+ } catch (EOFException e) {\n+ eofReached.set(true);\n+ throw e;\n+ }\n+ }\n+\n+ @Override\n+ public int read() throws IOException {\n+ FileDescriptor fdesc = core.validFdOrException();\n+\n+ if (eofReached.get()) {\n+ return -1;\n+ }\n+\n+ int byteRead = NativeUnixSocket.read(fdesc, null, 0, 1, opt, ancillaryDataSupport,\n+ socketTimeout.get());\n+ if (byteRead < 0) {\n+ eofReached.set(true);\n+ return -1;\n+ } else {\n+ return byteRead;\n+ }\n+ }\n+\n+ @Override\n+ public synchronized void close() throws IOException {\n+ streamClosed = true;\n+ FileDescriptor fdesc = core.validFd();\n+ if (fdesc != null) {\n+ NativeUnixSocket.shutdown(fdesc, SHUT_RD);\n+ }\n+\n+ closedInputStream = true;\n+ checkClose();\n+ }\n+\n+ @Override\n+ public int available() throws IOException {\n+ if (streamClosed) {\n+ throw new IOException(\"This InputStream has already been closed.\");\n+ }\n+\n+ return AFSocketImpl.this.available();\n+ }\n+\n+ @Override\n+ public FileDescriptor getFileDescriptor() throws IOException {\n+ return getFD();\n+ }\n+ }\n+\n+ private static boolean checkWriteInterruptedException(int bytesTransferred)\n+ throws InterruptedIOException {\n+ if (Thread.interrupted()) {\n+ InterruptedIOException ex = new InterruptedIOException(\"Thread interrupted during write\");\n+ ex.bytesTransferred = bytesTransferred;\n+ Thread.currentThread().interrupt();\n+ throw ex;\n+ }\n+ return true;\n+ }\n+\n+ private final class AFOutputStreamImpl extends AFOutputStream {\n+ private volatile boolean streamClosed = false;\n+\n+ private final int opt = (core.isBlocking() ? 0 : NativeUnixSocket.OPT_NON_BLOCKING);\n+\n+ @Override\n+ public void write(int oneByte) throws IOException {\n+ FileDescriptor fdesc = core.validFdOrException();\n+\n+ int written;\n+ do {\n+ written = NativeUnixSocket.write(fdesc, null, oneByte, 1, opt, ancillaryDataSupport);\n+ if (written != 0) {\n+ break;\n+ }\n+ } while (checkWriteInterruptedException(0));\n+ }\n+\n+ @Override\n+ public void write(byte[] buf, int off, int len) throws IOException {\n+ if (streamClosed) {\n+ throw new SocketException(\"This OutputStream has already been closed.\");\n+ }\n+ if (len < 0 || off < 0 || len > buf.length - off) {\n+ throw new IndexOutOfBoundsException();\n+ }\n+ FileDescriptor fdesc = core.validFdOrException();\n+ if (len == 0) {\n+ return;\n+ }\n+\n+ int writtenTotal = 0;\n+\n+ do {\n+ final int written = NativeUnixSocket.write(fdesc, buf, off, len, opt, ancillaryDataSupport);\n+ if (written < 0) {\n+ throw new IOException(\"Unspecific error while writing\");\n+ }\n+\n+ len -= written;\n+ off += written;\n+ writtenTotal += written;\n+ } while (len > 0 && checkWriteInterruptedException(writtenTotal));\n+ }\n+\n+ @Override\n+ public synchronized void close() throws IOException {\n+ if (streamClosed) {\n+ return;\n+ }\n+ streamClosed = true;\n+ FileDescriptor fdesc = core.validFd();\n+ if (fdesc != null) {\n+ NativeUnixSocket.shutdown(fdesc, SHUT_WR);\n+ }\n+ closedOutputStream = true;\n+ checkClose();\n+ }\n+\n+ @Override\n+ public FileDescriptor getFileDescriptor() throws IOException {\n+ return getFD();\n+ }\n+ }\n+\n+ @Override\n+ public final String toString() {\n+ return super.toString() + \"[fd=\" + fd + \"; addr=\" + this.core.socketAddress + \"; connected=\"\n+ + connected + \"; bound=\" + bound + \"]\";\n+ }\n+\n+ private static int expectInteger(Object value) throws SocketException {\n+ if (value == null) {\n+ throw (SocketException) new SocketException(\"Value must not be null\").initCause(\n+ new NullPointerException());\n+ }\n+ try {\n+ return (Integer) value;\n+ } catch (final ClassCastException e) {\n+ throw (SocketException) new SocketException(\"Unsupported value: \" + value).initCause(e);\n+ }\n+ }\n+\n+ private static int expectBoolean(Object value) throws SocketException {\n+ if (value == null) {\n+ throw (SocketException) new SocketException(\"Value must not be null\").initCause(\n+ new NullPointerException());\n+ }\n+ try {\n+ return ((Boolean) value).booleanValue() ? 1 : 0;\n+ } catch (final ClassCastException e) {\n+ throw (SocketException) new SocketException(\"Unsupported value: \" + value).initCause(e);\n+ }\n+ }\n+\n+ @Override\n+ public Object getOption(int optID) throws SocketException {\n+ return getOption0(optID);\n+ }\n+\n+ private Object getOption0(int optID) throws SocketException {\n+ if (isClosed()) {\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+ if (optID == SocketOptions.SO_REUSEADDR) {\n+ return reuseAddr;\n+ }\n+\n+ FileDescriptor fdesc = core.validFdOrException();\n+ return getOptionDefault(fdesc, optID, socketTimeout, addressFamily);\n+ }\n+\n+ static final Object getOptionDefault(FileDescriptor fdesc, int optID, AtomicInteger acceptTimeout,\n+ AFAddressFamily af) throws SocketException {\n+ try {\n+ switch (optID) {\n+ case SocketOptions.SO_KEEPALIVE:\n+ try {\n+ return (NativeUnixSocket.getSocketOptionInt(fdesc, optID) != 0);\n+ } catch (SocketException e) {\n+ // ignore\n+ return false;\n+ }\n+ case SocketOptions.TCP_NODELAY:\n+ return (NativeUnixSocket.getSocketOptionInt(fdesc, optID) != 0);\n+ case SocketOptions.SO_TIMEOUT:\n+ return Math.max((acceptTimeout == null ? 0 : acceptTimeout.get()), Math.max(\n+ NativeUnixSocket.getSocketOptionInt(fdesc, 0x1005), NativeUnixSocket\n+ .getSocketOptionInt(fdesc, 0x1006)));\n+ case SocketOptions.SO_LINGER:\n+ case SocketOptions.SO_RCVBUF:\n+ case SocketOptions.SO_SNDBUF:\n+ return NativeUnixSocket.getSocketOptionInt(fdesc, optID);\n+ case SocketOptions.IP_TOS:\n+ return 0;\n+ case SocketOptions.SO_BINDADDR:\n+ return AFSocketAddress.getInetAddress(fdesc, false, af);\n+ case SocketOptions.SO_REUSEADDR:\n+ return false;\n+ default:\n+ throw new SocketException(\"Unsupported option: \" + optID);\n+ }\n+ } catch (final SocketException e) {\n+ throw e;\n+ } catch (final Exception e) {\n+ throw (SocketException) new SocketException(\"Could not get option\").initCause(e);\n+ }\n+ }\n+\n+ @Override\n+ public void setOption(int optID, Object value) throws SocketException {\n+ setOption0(optID, value);\n+ }\n+\n+ private void setOption0(int optID, Object value) throws SocketException {\n+ if (isClosed()) {\n+ throw new SocketException(\"Socket is closed\");\n+ }\n+ if (optID == SocketOptions.SO_REUSEADDR) {\n+ reuseAddr = (expectBoolean(value) != 0);\n+ return;\n+ }\n+\n+ FileDescriptor fdesc = core.validFdOrException();\n+ setOptionDefault(fdesc, optID, value, socketTimeout);\n+ }\n+\n+ /**\n+ * Like {@link #getOption(int)}, but ignores exceptions for certain option IDs.\n+ * \n+ * @param optID The option ID.\n+ * @return The value.\n+ * @throws SocketException on error.\n+ */\n+ protected final Object getOptionLenient(int optID) throws SocketException {\n+ try {\n+ return getOption0(optID);\n+ } catch (SocketException e) {\n+ switch (optID) {\n+ case SocketOptions.TCP_NODELAY:\n+ case SocketOptions.SO_KEEPALIVE:\n+ return false;\n+ default:\n+ throw e;\n+ }\n+ }\n+ }\n+\n+ /**\n+ * Like {@link #setOption(int, Object)}, but ignores exceptions for certain option IDs.\n+ * \n+ * @param optID The option ID.\n+ * @param value The value.\n+ * @throws SocketException on error.\n+ */\n+ protected final void setOptionLenient(int optID, Object value) throws SocketException {\n+ try {\n+ setOption0(optID, value);\n+ } catch (SocketException e) {\n+ switch (optID) {\n+ case SocketOptions.TCP_NODELAY:\n+ return;\n+ default:\n+ throw e;\n+ }\n+ }\n+ }\n+\n+ static final void setOptionDefault(FileDescriptor fdesc, int optID, Object value,\n+ AtomicInteger acceptTimeout) throws SocketException {\n+ try {\n+ switch (optID) {\n+ case SocketOptions.SO_LINGER:\n+\n+ if (value instanceof Boolean) {\n+ final boolean b = (Boolean) value;\n+ if (b) {\n+ throw new SocketException(\"Only accepting Boolean.FALSE here\");\n+ }\n+ NativeUnixSocket.setSocketOptionInt(fdesc, optID, -1);\n+ return;\n+ }\n+ NativeUnixSocket.setSocketOptionInt(fdesc, optID, expectInteger(value));\n+ return;\n+ case SocketOptions.SO_TIMEOUT: {\n+ int timeout = expectInteger(value);\n+ NativeUnixSocket.setSocketOptionInt(fdesc, 0x1005, timeout);\n+ NativeUnixSocket.setSocketOptionInt(fdesc, 0x1006, timeout);\n+ if (acceptTimeout != null) {\n+ acceptTimeout.set(timeout);\n+ }\n+ return;\n+ }\n+ case SocketOptions.SO_RCVBUF:\n+ case SocketOptions.SO_SNDBUF:\n+ NativeUnixSocket.setSocketOptionInt(fdesc, optID, expectInteger(value));\n+ return;\n+ case SocketOptions.SO_KEEPALIVE:\n+ try {\n+ NativeUnixSocket.setSocketOptionInt(fdesc, optID, expectBoolean(value));\n+ } catch (SocketException e) {\n+ // ignore\n+ }\n+ return;\n+ case SocketOptions.TCP_NODELAY:\n+ NativeUnixSocket.setSocketOptionInt(fdesc, optID, expectBoolean(value));\n+ return;\n+ case SocketOptions.IP_TOS:\n+ // ignore\n+ return;\n+ case SocketOptions.SO_REUSEADDR:\n+ // ignore\n+ return;\n+ default:\n+ throw new SocketException(\"Unsupported option: \" + optID);\n+ }\n+ } catch (final SocketException e) {\n+ throw e;\n+ } catch (final Exception e) {\n+ throw (SocketException) new SocketException(\"Error while setting option\").initCause(e);\n+ }\n+ }\n+\n+ /**\n+ * Shuts down both input and output at once. Equivalent to calling {@link #shutdownInput()} and\n+ * {@link #shutdownOutput()}.\n+ * \n+ * @throws IOException on error.\n+ */\n+ protected final void shutdown() throws IOException {\n+ FileDescriptor fdesc = core.validFd();\n+ if (fdesc != null) {\n+ NativeUnixSocket.shutdown(fdesc, SHUT_RD_WR);\n+ shutdownState = 0;\n+ }\n+ }\n+\n+ @Override\n+ protected final void shutdownInput() throws IOException {\n+ FileDescriptor fdesc = core.validFd();\n+ if (fdesc != null) {\n+ NativeUnixSocket.shutdown(fdesc, SHUT_RD);\n+ shutdownState |= 1 << (SHUT_RD);\n+ if (shutdownState == SHUTDOWN_RD_WR) {\n+ NativeUnixSocket.shutdown(fdesc, SHUT_RD_WR);\n+ shutdownState = 0;\n+ }\n+ }\n+ }\n+\n+ @Override\n+ protected final void shutdownOutput() throws IOException {\n+ FileDescriptor fdesc = core.validFd();\n+ if (fdesc != null) {\n+ NativeUnixSocket.shutdown(fdesc, SHUT_WR);\n+ shutdownState |= 1 << (SHUT_RD_WR);\n+ if (shutdownState == SHUTDOWN_RD_WR) {\n+ NativeUnixSocket.shutdown(fdesc, SHUT_RD_WR);\n+ shutdownState = 0;\n+ }\n+ }\n+ }\n+\n+ final int getAncillaryReceiveBufferSize() {\n+ return ancillaryDataSupport.getAncillaryReceiveBufferSize();\n+ }\n+\n+ final void setAncillaryReceiveBufferSize(int size) {\n+ ancillaryDataSupport.setAncillaryReceiveBufferSize(size);\n+ }\n+\n+ final void ensureAncillaryReceiveBufferSize(int minSize) {\n+ ancillaryDataSupport.ensureAncillaryReceiveBufferSize(minSize);\n+ }\n+\n+ AncillaryDataSupport getAncillaryDataSupport() {\n+ return ancillaryDataSupport;\n+ }\n+\n+ final SocketAddress receive(ByteBuffer dst) throws IOException {\n+ return core.receive(dst);\n+ }\n+\n+ final int send(ByteBuffer src, SocketAddress target) throws IOException {\n+ return core.write(src, target, 0);\n+ }\n+\n+ final int read(ByteBuffer dst, ByteBuffer socketAddressBuffer) throws IOException {\n+ return core.read(dst, socketAddressBuffer, 0);\n+ }\n+\n+ final int write(ByteBuffer src) throws IOException {\n+ return core.write(src);\n+ }\n+\n+ @Override\n+ protected final FileDescriptor getFileDescriptor() {\n+ return core.fd;\n+ }\n+\n+ final void updatePorts(int local, int remote) {\n+ this.localport = local;\n+ if (remote >= 0) {\n+ this.port = remote;\n+ }\n+ }\n+\n+ final @Nullable A getLocalSocketAddress() {\n+ return AFSocketAddress.getSocketAddress(getFileDescriptor(), false, localport, addressFamily);\n+ }\n+\n+ final @Nullable A getRemoteSocketAddress() {\n+ return AFSocketAddress.getSocketAddress(getFileDescriptor(), true, port, addressFamily);\n+ }\n+\n+ final int getLocalPort1() {\n+ return localport;\n+ }\n+\n+ final int getRemotePort() {\n+ return port;\n+ }\n+\n+ @Override\n+ protected final InetAddress getInetAddress() {\n+ @Nullable\n+ A rsa = getRemoteSocketAddress();\n+ if (rsa == null) {\n+ return InetAddress.getLoopbackAddress();\n+ } else {\n+ return rsa.getInetAddress();\n+ }\n+ }\n+\n+ final void createSocket(FileDescriptor fdTarget, AFSocketType type) throws IOException {\n+ NativeUnixSocket.createSocket(fdTarget, addressFamily.getDomain(), type.getId());\n+ }\n+\n+ final AFAddressFamily getAddressFamily() {\n+ return addressFamily;\n+ }\n+\n+ @Override\n+ protected void setOption(SocketOption name, T value) throws IOException {\n+ if (name instanceof AFSocketOption) {\n+ ((AFSocketImpl) this).getCore().setOption((AFSocketOption) name, value);\n+ return;\n+ }\n+ Integer optionId = SocketOptionsMapper.resolve(name);\n+ if (optionId == null) {\n+ super.setOption(name, value);\n+ } else {\n+ setOption(optionId, value);\n+ }\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ @Override\n+ protected T getOption(SocketOption name) throws IOException {\n+ if (name instanceof AFSocketOption) {\n+ return ((AFSocketImpl) this).getCore().getOption((AFSocketOption) name);\n+ }\n+ Integer optionId = SocketOptionsMapper.resolve(name);\n+ if (optionId == null) {\n+ return super.getOption(name);\n+ } else {\n+ return (T) getOption(optionId);\n+ }\n+ }\n+\n+ @Override\n+ protected Set> supportedOptions() {\n+ return SocketOptionsMapper.SUPPORTED_SOCKET_OPTIONS;\n+ }\n+\n+ /**\n+ * Returns the internal helper instance for address-specific extensions.\n+ * \n+ * @return The helper instance.\n+ * @throws UnsupportedOperationException if such extensions are not supported for this address\n+ * type.\n+ */\n+ protected final synchronized AFSocketImplExtensions getImplExtensions() {\n+ if (implExtensions == null) {\n+ implExtensions = addressFamily.initImplExtensions(ancillaryDataSupport);\n+ }\n+ return implExtensions;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSomeSocket.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketImplExtensions.java\nsimilarity index 71%\nrename from junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSomeSocket.java\nrename to junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketImplExtensions.java\nindex d1bfcd85e..7a12b3973 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSomeSocket.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketImplExtensions.java\n@@ -17,14 +17,13 @@\n */\n package org.newsclub.net.unix;\n \n-import java.io.Closeable;\n-\n /**\n- * Marker interface that combines {@link AFUNIXSocketChannel}, {@link AFUNIXSocket},\n- * {@link AFUNIXDatagramChannel} and {@link AFUNIXDatagramSocket}.\n+ * Placeholder for protocol-specific code that resides in the native library.\n * \n+ * @param The corresponding address type.\n * @author Christian Kohlschütter\n- * @see AFUNIXSocketPair\n+ * @see AFTIPCSocketImplExtensions\n */\n-public interface AFUNIXSomeSocket extends Closeable, FileDescriptorAccess {\n+public interface AFSocketImplExtensions {\n+\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketOption.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketOption.java\nnew file mode 100644\nindex 000000000..b29206bbf\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketOption.java\n@@ -0,0 +1,71 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.net.SocketOption;\n+\n+/**\n+ * A special socket option supported by some junixsocket-based implementation.\n+ * \n+ * @param The option's value type.\n+ * @author Christian Kohlschütter\n+ */\n+public final class AFSocketOption implements SocketOption {\n+ private final String name; // NOPMD.AvoidFieldNameMatchingMethodName\n+ private final Class type; // NOPMD.AvoidFieldNameMatchingMethodName\n+ private final int level; // NOPMD.AvoidFieldNameMatchingMethodName\n+ private final int optionName; // NOPMD.AvoidFieldNameMatchingMethodName\n+\n+ /**\n+ * Creates a new socket option. This should only be called by {@link AFSocket} implementations.\n+ * \n+ * @param name The name of the option.\n+ * @param type The value type.\n+ * @param level The socket level (as defined in junixsocket-native).\n+ * @param optionName The option name (as defined in junixsocket-native).\n+ */\n+ public AFSocketOption(String name, Class type, int level, int optionName) {\n+ this.name = name;\n+ this.type = type;\n+ this.level = level;\n+ this.optionName = optionName;\n+ }\n+\n+ @Override\n+ public String name() {\n+ return name;\n+ }\n+\n+ @Override\n+ public Class type() {\n+ return type;\n+ }\n+\n+ int level() {\n+ return level;\n+ }\n+\n+ int optionName() {\n+ return optionName;\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return getClass() + \":\" + name;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketPair.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketPair.java\nnew file mode 100644\nindex 000000000..b7e164ec4\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketPair.java\n@@ -0,0 +1,69 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.Closeable;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+\n+/**\n+ * A pair of sockets.\n+ * \n+ * @param The socket type.\n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFSocketPair extends CloseablePair {\n+ /**\n+ * Creates a socket pair.\n+ * \n+ * @param a The first socket.\n+ * @param b The second socket.\n+ */\n+ protected AFSocketPair(T a, T b) {\n+ super(a, b);\n+ }\n+\n+ /**\n+ * Creates a socket pair.\n+ * \n+ * @param a The first socket.\n+ * @param b The second socket.\n+ * @param alsoClose Some closeable that is also closed upon {@link #close()}, or {@code null}.\n+ */\n+ protected AFSocketPair(T a, T b, Closeable alsoClose) {\n+ super(a, b, alsoClose);\n+ }\n+\n+ /**\n+ * Returns the first socket of the pair.\n+ * \n+ * @return The first socket.\n+ */\n+ public final @NonNull T getSocket1() {\n+ return getFirst();\n+ }\n+\n+ /**\n+ * Returns the second socket of the pair.\n+ * \n+ * @return The second socket.\n+ */\n+ public final @NonNull T getSocket2() {\n+ return getSecond();\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketProtocol.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketProtocol.java\nnew file mode 100644\nindex 000000000..e6e36f9d5\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketProtocol.java\n@@ -0,0 +1,40 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+/**\n+ * Describes the \"protocol\" part of a socket.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public enum AFSocketProtocol {\n+ /**\n+ * The \"default\" protocol.\n+ */\n+ DEFAULT(0);\n+\n+ private final int id;\n+\n+ AFSocketProtocol(int id) {\n+ this.id = id;\n+ }\n+\n+ int getId() {\n+ return id;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketType.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketType.java\nnew file mode 100644\nindex 000000000..641ca74b9\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSocketType.java\n@@ -0,0 +1,60 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+/**\n+ * Describes the \"type\" of a socket.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public enum AFSocketType {\n+ /**\n+ * Stream-oriented socket.\n+ */\n+ SOCK_STREAM(NativeUnixSocket.SOCK_STREAM), //\n+\n+ /**\n+ * Datagram-oriented socket. Usually permitting data loss (but not with {@link AFUNIXSocket}).\n+ */\n+ SOCK_DGRAM(NativeUnixSocket.SOCK_DGRAM), //\n+\n+ /**\n+ * Sequential packet socket.\n+ */\n+ SOCK_SEQPACKET(NativeUnixSocket.SOCK_SEQPACKET), //\n+\n+ /**\n+ * Reliably-delivered datagram messages.\n+ * \n+ * Used by {@code AFTIPCDatagramSocket} to differentiate between datagram connects that may or may\n+ * not permit package loss.\n+ */\n+ SOCK_RDM(NativeUnixSocket.SOCK_RDM), //\n+\n+ ;\n+\n+ private final int id;\n+\n+ AFSocketType(int id) {\n+ this.id = id;\n+ }\n+\n+ int getId() {\n+ return id;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSomeSocket.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSomeSocket.java\nnew file mode 100644\nindex 000000000..c2bddf12d\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFSomeSocket.java\n@@ -0,0 +1,58 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.Closeable;\n+import java.net.DatagramSocket;\n+import java.net.Socket;\n+import java.net.SocketAddress;\n+import java.nio.channels.DatagramChannel;\n+import java.nio.channels.SocketChannel;\n+\n+import org.eclipse.jdt.annotation.Nullable;\n+\n+/**\n+ * Marker interface that combines junixsocket-based {@link SocketChannel}s, {@link Socket}s,\n+ * {@link DatagramChannel}s and {@link DatagramSocket}s.\n+ * \n+ * @author Christian Kohlschütter\n+ * @see AFSocketPair\n+ * @see AFSocket\n+ * @see AFSocketChannel\n+ * @see AFDatagramSocket\n+ * @see AFDatagramChannel\n+ */\n+public interface AFSomeSocket extends Closeable, FileDescriptorAccess {\n+ /**\n+ * Returns the socket's local socket address, or {@code null} if unavailable or if there was a\n+ * problem retrieving it.\n+ * \n+ * @return The local socket address, or {@code null}.\n+ */\n+ @Nullable\n+ SocketAddress getLocalSocketAddress();\n+\n+ /**\n+ * Returns the socket's remote socket address, or {@code null} if unavailable/not connected, or if\n+ * there was a problem retrieving it.\n+ * \n+ * @return The remote socket address, or {@code null}.\n+ */\n+ @Nullable\n+ SocketAddress getRemoteSocketAddress();\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFTIPCSocketAddress.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFTIPCSocketAddress.java\nnew file mode 100644\nindex 000000000..53e9a1c52\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFTIPCSocketAddress.java\n@@ -0,0 +1,892 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.File;\n+import java.io.FileNotFoundException;\n+import java.io.IOException;\n+import java.io.Serializable;\n+import java.net.InetAddress;\n+import java.net.InetSocketAddress;\n+import java.net.SocketAddress;\n+import java.net.SocketException;\n+import java.net.URI;\n+import java.nio.ByteBuffer;\n+import java.util.Arrays;\n+import java.util.HashSet;\n+import java.util.Locale;\n+import java.util.Objects;\n+import java.util.Set;\n+import java.util.regex.Matcher;\n+import java.util.regex.Pattern;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.NonNullByDefault;\n+\n+/**\n+ * An {@link AFSocketAddress} for TIPC sockets.\n+ * \n+ * The TIPC socket API provides three different address types:\n+ *
    \n+ *
  • Service Address.\n+ *

    \n+ * This address type consists of a 32-bit service type identifier and a 32-bit service instance\n+ * identifier.\n+ *

    \n+ *

    \n+ * The type identifier is typically determined and hard-coded by the user application programmer,\n+ * but its value may have to be coordinated with other applications which might be present in the\n+ * same cluster. The instance identifier is often calculated by the program, based on application\n+ * specific criteria.\n+ *

    \n+ *

    \n+ * Typical invocation: {@link #ofService(int, int)}.\n+ *

    \n+ *
  • \n+ *
  • Service Range.\n+ *

    \n+ * This address type represents a range of service addresses of the same type and with instances\n+ * between a lower and an upper range limit.\n+ *

    \n+ *

    \n+ * By binding a socket to this address type one can make it represent many instances, something\n+ * which has proved useful in many cases. This address type is also used as multicast address.\n+ *

    \n+ *

    \n+ * Typical invocation: {@link #ofServiceRange(int, int, int)}.\n+ *

    \n+ *
  • \n+ *
  • Socket Address.\n+ *

    \n+ * This address is a reference to a specific socket in the cluster.\n+ *

    \n+ *

    \n+ * It contains a 32-bit port number and a 32-bit node hash number. The port number is generated by\n+ * the system when the socket is created, and the node hash is generated from the corresponding node\n+ * identity.\n+ *

    \n+ *

    \n+ * An address of this type can be used for connecting or for sending messages in the same way as\n+ * service addresses can be used, but is only valid as long as the referenced socket exists.\n+ *

    \n+ *

    \n+ * Typical invocation: {@link #ofSocket(int, int)}.\n+ *

    \n+ *
  • \n+ *
\n+ *

\n+ * When binding a socket to a service address or address range, the visibility scope of the binding\n+ * must be indicated. There are two options, {@link Scope#SCOPE_NODE} if the user only wants node\n+ * local visibility, and {@link Scope#SCOPE_CLUSTER} if he wants cluster global visibility. There\n+ * are almost no limitations to how sockets can be bound to service addresses: one socket can be\n+ * bound to many addresses or ranges, and many sockets can be bound to the same address or range.\n+ *

\n+ *

\n+ * The service types 0 through 63 are however reserved for system internal use, and are not\n+ * available for user space applications.\n+ *

\n+ *

\n+ * When sending a message by service address the sender may indicate a lookup domain, also called\n+ * lookup scope. This is a node hash number, limiting the set of eligible destination sockets to the\n+ * indicated node. If this value is zero, all matching sockets in the whole cluster, as visible from\n+ * the source node, are eligible.\n+ *

\n+ * \n+ * @author Christian Kohlschütter (documentation credits to Jon Maloy and the TIPC team).\n+ */\n+public final class AFTIPCSocketAddress extends AFSocketAddress {\n+ private static final long serialVersionUID = 1L;\n+\n+ private static final Pattern PAT_TIPC_URI_HOST_AND_PORT = Pattern.compile(\n+ \"^((?:(?:(?cluster|node|default|[0-9a-fx]+)\\\\-)?(?service|service-range|socket)\\\\.)|\"\n+ + \"(?cluster|node|default|[0-9a-fx]+)\\\\-(?[0-9a-fx]+)\\\\.)?\"\n+ + \"(?
[0-9a-fx]+)\\\\.(?[0-9a-fx]+)(?:\\\\.(?[0-9a-fx]+))?(?:\\\\:(?[0-9]+))?$\");\n+\n+ /**\n+ * The \"topology\" service name type.\n+ */\n+ public static final int TIPC_TOP_SRV = 1;\n+\n+ /**\n+ * The lowest user-publishable name type.\n+ */\n+ public static final int TIPC_RESERVED_TYPES = 64;\n+\n+ private static AFAddressFamily afTipc;\n+\n+ /**\n+ * The TIPC address type.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+ @NonNullByDefault\n+ public static final class AddressType extends NamedInteger {\n+ private static final long serialVersionUID = 1L;\n+\n+ /**\n+ * Describes a TIPC \"service range\" address.\n+ */\n+ public static final AddressType SERVICE_RANGE;\n+\n+ /**\n+ * Describes a TIPC \"service\" address.\n+ */\n+ public static final AddressType SERVICE_ADDR;\n+\n+ /**\n+ * Describes a TIPC \"socket\" address.\n+ */\n+ public static final AddressType SOCKET_ADDR;\n+\n+ private static final @NonNull AddressType[] VALUES = init(new @NonNull AddressType[] {\n+ SERVICE_RANGE = new AddressType(\"SERVICE_RANGE\", 1, //\n+ (a, b, c) -> formatTIPCInt(a) + \"@\" + formatTIPCInt(b) + \"-\" + formatTIPCInt(c)), //\n+ SERVICE_ADDR = new AddressType(\"SERVICE_ADDR\", 2, //\n+ (a, b, c) -> formatTIPCInt(a) + \"@\" + formatTIPCInt(b) + (c == 0 ? \"\" : \":\"\n+ + formatTIPCInt(c))), //\n+ SOCKET_ADDR = new AddressType(\"SOCKET_ADDR\", 3, //\n+ (a, b, c) -> formatTIPCInt(a) + \"@\" + formatTIPCInt(b) + (c == 0 ? \"\" : \":\"\n+ + formatTIPCInt(c))), //\n+ });\n+\n+ /**\n+ * The provider of a debug string.\n+ */\n+ private final DebugStringProvider ds;\n+\n+ private AddressType(int id) {\n+ super(id);\n+ this.ds = (a, b, c) -> \":\" + Integer.toUnsignedString(a) + \":\" + Integer.toUnsignedString(b)\n+ + \":\" + Integer.toUnsignedString(c);\n+ }\n+\n+ private AddressType(String name, int id, DebugStringProvider ds) {\n+ super(name, id);\n+ this.ds = ds;\n+ }\n+\n+ static AddressType ofValue(int v) {\n+ return ofValue(VALUES, AddressType::new, v);\n+ }\n+\n+ @FunctionalInterface\n+ interface DebugStringProvider extends Serializable {\n+ String toDebugString(int a, int b, int c);\n+ }\n+\n+ /**\n+ * Formats an integer as an unsigned, zero-padded 32-bit hexadecimal number.\n+ * \n+ * @param i The number.\n+ * @return The string.\n+ */\n+ @SuppressWarnings(\"null\")\n+ public static String formatTIPCInt(int i) {\n+ return String.format(Locale.ENGLISH, \"0x%08x\", (i & 0xFFFFFFFFL));\n+ }\n+\n+ private String toDebugString(Scope scope, int a, int b, int c) {\n+ if (this == SOCKET_ADDR && scope.equals(Scope.SCOPE_NOT_SPECIFIED)) {\n+ return name() + \"(\" + value() + \");\" + ds.toDebugString(a, b, c);\n+ } else {\n+ return name() + \"(\" + value() + \");\" + scope + \":\" + ds.toDebugString(a, b, c);\n+ }\n+ }\n+ }\n+\n+ /**\n+ * The TIPC visibility scope.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+ @NonNullByDefault\n+ public static final class Scope extends NamedInteger {\n+ private static final long serialVersionUID = 1L;\n+\n+ /**\n+ * Cluster-wide scope.\n+ */\n+ public static final Scope SCOPE_CLUSTER;\n+\n+ /**\n+ * Node-only scope.\n+ */\n+ public static final Scope SCOPE_NODE;\n+\n+ /**\n+ * Scope not specified (for example, when using socket addresses).\n+ */\n+ public static final Scope SCOPE_NOT_SPECIFIED;\n+\n+ private static final @NonNull Scope[] VALUES = init(new @NonNull Scope[] {\n+ SCOPE_NOT_SPECIFIED = new Scope(\"SCOPE_NOT_SPECIFIED\", 0), //\n+ SCOPE_CLUSTER = new Scope(\"SCOPE_CLUSTER\", 2), //\n+ SCOPE_NODE = new Scope(\"SCOPE_NODE\", 3), //\n+ });\n+\n+ private Scope(int id) {\n+ super(id);\n+ }\n+\n+ private Scope(String name, int id) {\n+ super(name, id);\n+ }\n+\n+ /**\n+ * Returns a {@link Scope} instance given an integer value.\n+ * \n+ * @param v The scope value.\n+ * @return The {@link Scope} instance.\n+ */\n+ public static Scope ofValue(int v) {\n+ return ofValue(VALUES, Scope::new, v);\n+ }\n+ }\n+\n+ private AFTIPCSocketAddress(int port, final byte[] socketAddress, ByteBuffer nativeAddress)\n+ throws SocketException {\n+ super(port, socketAddress, nativeAddress, addressFamily());\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} that refers to a given service type and instance, using\n+ * the given scope.\n+ *\n+ * @param scope The address scope.\n+ * @param type The service type (0-63 are reserved).\n+ * @param instance The service instance ID.\n+ * @return A corresponding {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFTIPCSocketAddress ofService(Scope scope, int type, int instance)\n+ throws SocketException {\n+ return ofService(scope, type, instance, 0);\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} that refers to a given service type and instance,\n+ * implicitly using cluster scope ({@link Scope#SCOPE_CLUSTER}).\n+ *\n+ * @param type The service type (0-63 are reserved).\n+ * @param instance The service instance ID.\n+ * @return A corresponding {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFTIPCSocketAddress ofService(int type, int instance) throws SocketException {\n+ return ofService(Scope.SCOPE_CLUSTER, type, instance, 0);\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} that refers to a given service type and instance, using\n+ * the given scope and the given lookup domain.\n+ * \n+ * @param scope The address scope.\n+ * @param type The service type (0-63 are reserved).\n+ * @param instance The service instance ID.\n+ * @param domain The lookup domain. 0 indicates cluster global lookup, otherwise a node hash,\n+ * indicating that lookup should be performed only on that node\n+ * @return A corresponding {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFTIPCSocketAddress ofService(Scope scope, int type, int instance, int domain)\n+ throws SocketException {\n+ return ofService(0, scope, type, instance, domain);\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} that refers to a given service type and instance, using\n+ * the given scope and the given lookup domain. A Java-only \"IP port number\" is stored along the\n+ * instance for compatibility reasons.\n+ *\n+ * @param javaPort The emulated \"port\" number (not part of TIPC).\n+ * @param scope The address scope.\n+ * @param type The service type (0-63 are reserved).\n+ * @param instance The service instance ID.\n+ * @param domain The lookup domain. 0 indicates cluster global lookup, otherwise a node hash,\n+ * indicating that lookup should be performed only on that node\n+ * @return A corresponding {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFTIPCSocketAddress ofService(int javaPort, Scope scope, int type, int instance,\n+ int domain) throws SocketException {\n+ return resolveAddress(toBytes(AddressType.SERVICE_ADDR, scope, type, instance, domain),\n+ javaPort, addressFamily());\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} that refers to a given service range type and instance\n+ * boundaries (lower/upper values), using the given scope.\n+ *\n+ * @param scope The address scope.\n+ * @param type The service type (0-63 are reserved).\n+ * @param lower Lower end of service instance ID range.\n+ * @param upper Upper end of service instance ID range.\n+ * @return A corresponding {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFTIPCSocketAddress ofServiceRange(Scope scope, int type, int lower, int upper)\n+ throws SocketException {\n+ return ofServiceRange(0, scope, type, lower, upper);\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} that refers to a given service range type and instance\n+ * boundaries (lower/upper values), implicitly using cluster scope ({@link Scope#SCOPE_CLUSTER}).\n+ *\n+ * @param type The service type (0-63 are reserved).\n+ * @param lower Lower end of service instance ID range.\n+ * @param upper Upper end of service instance ID range.\n+ * @return A corresponding {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFTIPCSocketAddress ofServiceRange(int type, int lower, int upper)\n+ throws SocketException {\n+ return ofServiceRange(0, Scope.SCOPE_CLUSTER, type, lower, upper);\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} that refers to a given service range type and instance\n+ * boundaries (lower/upper values), implicitly using cluster scope ({@link Scope#SCOPE_CLUSTER}).\n+ * A Java-only \"IP port number\" is stored along the instance for compatibility reasons.\n+ *\n+ * @param javaPort The emulated \"port\" number (not part of TIPC).\n+ * @param scope The address scope.\n+ * @param type The service type (0-63 are reserved).\n+ * @param lower Lower end of service instance ID range.\n+ * @param upper Upper end of service instance ID range.\n+ * @return A corresponding {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFTIPCSocketAddress ofServiceRange(int javaPort, Scope scope, int type, int lower,\n+ int upper) throws SocketException {\n+ return resolveAddress(toBytes(AddressType.SERVICE_RANGE, scope, type, lower, upper), javaPort,\n+ addressFamily());\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} that refers to a given TIPC socket address (i.e.,\n+ * referring to a particular socket instance instead of a service address).\n+ *\n+ * @param ref 32-bit port reference ID (not to be confused with the\n+ * {@link InetSocketAddress#getPort()} port).\n+ * @param node Node hash number (can be used as lookup domain with\n+ * {@link #ofService(Scope, int, int, int)}).\n+ * @return A corresponding {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFTIPCSocketAddress ofSocket(int ref, int node) throws SocketException {\n+ return ofSocket(0, ref, node);\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} that refers to a given TIPC socket address (i.e.,\n+ * referring to a particular socket instance instead of a service address). A Java-only \"IP port\n+ * number\" is stored along the instance for compatibility reasons.\n+ *\n+ * @param javaPort The emulated \"port\" number (not part of TIPC).\n+ * @param ref 32-bit port reference ID (not to be confused with the\n+ * {@link InetSocketAddress#getPort()} port).\n+ * @param node Node hash number (can be used as lookup domain with\n+ * {@link #ofService(Scope, int, int, int)}).\n+ * @return A corresponding {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFTIPCSocketAddress ofSocket(int javaPort, int ref, int node)\n+ throws SocketException {\n+ return resolveAddress(toBytes(AddressType.SOCKET_ADDR, Scope.SCOPE_NOT_SPECIFIED, ref, node, 0),\n+ javaPort, addressFamily());\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} that refers to the topology service.\n+ *\n+ * @return A corresponding {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFTIPCSocketAddress ofTopologyService() throws SocketException {\n+ return resolveAddress(toBytes(AddressType.SERVICE_ADDR, Scope.SCOPE_NOT_SPECIFIED, TIPC_TOP_SRV,\n+ TIPC_TOP_SRV, 0), 0, addressFamily());\n+ }\n+\n+ private static int parseUnsignedInt(String v) {\n+ if (v.startsWith(\"0x\")) {\n+ return Integer.parseUnsignedInt(v.substring(2), 16);\n+ } else {\n+ return Integer.parseUnsignedInt(v);\n+ }\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} given a special {@link InetAddress} that encodes the\n+ * byte sequence of an AF_TIPC socket address, like those returned by {@link #wrapAddress()}.\n+ * \n+ * @param address The \"special\" {@link InetAddress}.\n+ * @param port The port (use 0 for \"none\").\n+ * @return The {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails, for example when an unsupported address is\n+ * specified.\n+ */\n+ public static AFTIPCSocketAddress unwrap(InetAddress address, int port) throws SocketException {\n+ return AFSocketAddress.unwrap(address, port, addressFamily());\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} given a special {@link InetAddress} hostname that\n+ * encodes the byte sequence of an AF_TIPC socket address, like those returned by\n+ * {@link #wrapAddress()}.\n+ * \n+ * @param hostname The \"special\" hostname, as provided by {@link InetAddress#getHostName()}.\n+ * @param port The port (use 0 for \"none\").\n+ * @return The {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails, for example when an unsupported address is\n+ * specified.\n+ */\n+ public static AFTIPCSocketAddress unwrap(String hostname, int port) throws SocketException {\n+ return AFSocketAddress.unwrap(hostname, port, addressFamily());\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} given a generic {@link SocketAddress}.\n+ * \n+ * @param address The address to unwrap.\n+ * @return The {@link AFTIPCSocketAddress} instance.\n+ * @throws SocketException if the operation fails, for example when an unsupported address is\n+ * specified.\n+ */\n+ public static AFTIPCSocketAddress unwrap(SocketAddress address) throws SocketException {\n+ Objects.requireNonNull(address);\n+ if (!isSupportedAddress(address)) {\n+ throw new SocketException(\"Unsupported address\");\n+ }\n+ return (AFTIPCSocketAddress) address;\n+ }\n+\n+ /**\n+ * Returns the scope of this address.\n+ * \n+ * @return The scope.\n+ */\n+ public Scope getScope() {\n+ byte[] bytes = getBytes();\n+ if (bytes.length != (5 * 4)) {\n+ return Scope.SCOPE_NOT_SPECIFIED;\n+ }\n+ return Scope.ofValue(ByteBuffer.wrap(bytes, 4, 4).getInt());\n+ }\n+\n+ /**\n+ * Returns the TIPC type part of this address.\n+ * \n+ * @return The type identifier\n+ */\n+ public int getTIPCType() {\n+ ByteBuffer bb = ByteBuffer.wrap(getBytes());\n+ int a = bb.getInt(2 * 4);\n+ return a;\n+ }\n+\n+ /**\n+ * Returns the TIPC instance part of this address.\n+ * \n+ * @return The instance identifier.\n+ */\n+ public int getTIPCInstance() {\n+ ByteBuffer bb = ByteBuffer.wrap(getBytes());\n+ int a = bb.getInt(3 * 4);\n+ return a;\n+ }\n+\n+ /**\n+ * Returns the TIPC domain part of this address.\n+ * \n+ * @return The domain identifier.\n+ */\n+ public int getTIPCDomain() {\n+ ByteBuffer bb = ByteBuffer.wrap(getBytes());\n+ int a = bb.getInt(4 * 4);\n+ return a;\n+ }\n+\n+ /**\n+ * Returns the TIPC lower instance of this address.\n+ * \n+ * @return The lower instance identifier.\n+ */\n+ public int getTIPCLower() {\n+ ByteBuffer bb = ByteBuffer.wrap(getBytes());\n+ int a = bb.getInt(2 * 4);\n+ return a;\n+ }\n+\n+ /**\n+ * Returns the TIPC upper instance of this address.\n+ * \n+ * @return The lower instance identifier.\n+ */\n+ public int getTIPCUpper() {\n+ ByteBuffer bb = ByteBuffer.wrap(getBytes());\n+ int a = bb.getInt(3 * 4);\n+ return a;\n+ }\n+\n+ /**\n+ * Returns the TIPC ref of this address.\n+ * \n+ * @return The ref identifier.\n+ */\n+ public int getTIPCRef() {\n+ ByteBuffer bb = ByteBuffer.wrap(getBytes());\n+ int a = bb.getInt(2 * 4);\n+ return a;\n+ }\n+\n+ /**\n+ * Returns the TIPC node hash of this address.\n+ * \n+ * @return The node hash.\n+ */\n+ public int getTIPCNodeHash() {\n+ ByteBuffer bb = ByteBuffer.wrap(getBytes());\n+ int a = bb.getInt(3 * 4);\n+ return a;\n+ }\n+\n+ @Override\n+ public String toString() {\n+ int port = getPort();\n+\n+ byte[] bytes = getBytes();\n+ if (bytes.length != (5 * 4)) {\n+ return getClass().getName() + \"[\" + (port == 0 ? \"\" : \"port=\" + port) + \";UNKNOWN\" + \"]\";\n+ }\n+\n+ ByteBuffer bb = ByteBuffer.wrap(bytes);\n+ int typeId = bb.getInt();\n+ int scopeId = bb.getInt();\n+ int a = bb.getInt();\n+ int b = bb.getInt();\n+ int c = bb.getInt();\n+\n+ Scope scope = Scope.ofValue((byte) scopeId);\n+\n+ AddressType type = AddressType.ofValue(typeId);\n+ String typeString = type.toDebugString(scope, a, b, c);\n+\n+ return getClass().getName() + \"[\" + (port == 0 ? \"\" : \"port=\" + port + \";\") + typeString + \"]\";\n+ }\n+\n+ @Override\n+ public boolean hasFilename() {\n+ return false;\n+ }\n+\n+ @Override\n+ public File getFile() throws FileNotFoundException {\n+ throw new FileNotFoundException(\"no file\");\n+ }\n+\n+ /**\n+ * Checks if an {@link InetAddress} can be unwrapped to an {@link AFTIPCSocketAddress}.\n+ * \n+ * @param addr The instance to check.\n+ * @return {@code true} if so.\n+ * @see #wrapAddress()\n+ * @see #unwrap(InetAddress, int)\n+ */\n+ public static boolean isSupportedAddress(InetAddress addr) {\n+ return AFSocketAddress.isSupportedAddress(addr, addressFamily());\n+ }\n+\n+ /**\n+ * Checks if a {@link SocketAddress} can be unwrapped to an {@link AFTIPCSocketAddress}.\n+ * \n+ * @param addr The instance to check.\n+ * @return {@code true} if so.\n+ * @see #unwrap(InetAddress, int)\n+ */\n+ public static boolean isSupportedAddress(SocketAddress addr) {\n+ return (addr instanceof AFTIPCSocketAddress);\n+ }\n+\n+ @SuppressWarnings(\"cast\")\n+ private static byte[] toBytes(AddressType addrType, Scope scope, int a, int b, int c) {\n+ ByteBuffer bb = ByteBuffer.allocate(5 * 4);\n+ bb.putInt(addrType.value());\n+ bb.putInt(scope.value());\n+ bb.putInt(a);\n+ bb.putInt(b);\n+ bb.putInt(c);\n+ return (byte[]) bb.flip().array();\n+ }\n+\n+ /**\n+ * Returns the corresponding {@link AFAddressFamily}.\n+ * \n+ * @return The address family instance.\n+ */\n+ @SuppressWarnings(\"null\")\n+ public static synchronized AFAddressFamily addressFamily() {\n+ if (afTipc == null) {\n+ afTipc = AFAddressFamily.registerAddressFamily(\"tipc\", //\n+ AFTIPCSocketAddress.class, new AFSocketAddressConfig() {\n+\n+ @Override\n+ protected AFTIPCSocketAddress parseURI(URI u, int port) throws SocketException {\n+ return AFTIPCSocketAddress.of(u, port);\n+ }\n+\n+ @Override\n+ protected AFSocketAddressConstructor addressConstructor() {\n+ return AFTIPCSocketAddress::new;\n+ }\n+\n+ @Override\n+ protected String selectorProviderClassname() {\n+ return \"org.newsclub.net.unix.tipc.AFTIPCSelectorProvider\";\n+ }\n+\n+ @Override\n+ protected Set uriSchemes() {\n+ return new HashSet<>(Arrays.asList(\"tipc\", \"http+tipc\", \"https+tipc\"));\n+ }\n+ });\n+ try {\n+ Class.forName(\"org.newsclub.net.unix.tipc.AFTIPCSelectorProvider\");\n+ } catch (ClassNotFoundException e) {\n+ // ignore\n+ }\n+ }\n+ return afTipc;\n+ }\n+\n+ private String toTipcInt(int v) {\n+ if (v < 0) {\n+ return \"0x\" + Integer.toUnsignedString(v, 16);\n+ } else {\n+ return Integer.toUnsignedString(v);\n+ }\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} for the given URI, if possible.\n+ * \n+ * @param uri The URI.\n+ * @return The address.\n+ * @throws SocketException if the operation fails.\n+ */\n+ @SuppressWarnings(\"PMD.ShortMethodName\")\n+ public static AFTIPCSocketAddress of(URI uri) throws SocketException {\n+ return of(uri, -1);\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCSocketAddress} for the given URI, if possible.\n+ * \n+ * @param uri The URI.\n+ * @param overridePort The port to forcibly use, or {@code -1} for \"don't override\".\n+ * @return The address.\n+ * @throws SocketException if the operation fails.\n+ */\n+ @SuppressWarnings({\n+ \"PMD.CognitiveComplexity\", \"PMD.CyclomaticComplexity\", \"PMD.ExcessiveMethodLength\",\n+ \"PMD.NcssCount\", \"PMD.NPathComplexity\", \"PMD.ShortMethodName\"})\n+ public static AFTIPCSocketAddress of(URI uri, int overridePort) throws SocketException {\n+ switch (uri.getScheme()) {\n+ case \"tipc\":\n+ case \"http+tipc\":\n+ case \"https+tipc\":\n+ break;\n+ default:\n+ throw new SocketException(\"Unsupported URI scheme: \" + uri.getScheme());\n+ }\n+\n+ String host = uri.getHost();\n+ if (host == null) {\n+ host = uri.getAuthority();\n+ if (host != null) {\n+ int at = host.indexOf('@');\n+ if (at >= 0) {\n+ host = host.substring(at + 1);\n+ }\n+ }\n+ }\n+ if (host == null) {\n+ throw new SocketException(\"Cannot get hostname from URI: \" + uri);\n+ }\n+ int port = overridePort != -1 ? overridePort : uri.getPort();\n+ if (port != -1) {\n+ host += \":\" + port;\n+ }\n+ try {\n+ Matcher m = PAT_TIPC_URI_HOST_AND_PORT.matcher(host);\n+ if (!m.matches()) {\n+ throw new SocketException(\"Invalid TIPC URI: \" + uri);\n+ }\n+\n+ String typeStr = m.group(\"type\");\n+ String scopeStr = m.group(\"scope\");\n+ if (typeStr == null) {\n+ typeStr = m.group(\"type2\");\n+ scopeStr = m.group(\"scope2\");\n+ }\n+ String strA = m.group(\"a\");\n+ String strB = m.group(\"b\");\n+ String strC = m.group(\"c\");\n+ String javaPortStr = m.group(\"javaPort\");\n+\n+ final AddressType addrType;\n+ switch (typeStr == null ? \"\" : typeStr) {\n+ case \"service\":\n+ addrType = AddressType.SERVICE_ADDR;\n+ break;\n+ case \"service-range\":\n+ addrType = AddressType.SERVICE_RANGE;\n+ break;\n+ case \"socket\":\n+ addrType = AddressType.SOCKET_ADDR;\n+ break;\n+ case \"\":\n+ addrType = AddressType.SERVICE_ADDR;\n+ break;\n+ default:\n+ addrType = AddressType.ofValue(parseUnsignedInt(typeStr));\n+ break;\n+ }\n+\n+ final Scope scope;\n+ switch (scopeStr == null ? \"\" : scopeStr) {\n+ case \"cluster\":\n+ scope = Scope.SCOPE_CLUSTER;\n+ break;\n+ case \"node\":\n+ scope = Scope.SCOPE_NODE;\n+ break;\n+ case \"default\":\n+ scope = Scope.SCOPE_NOT_SPECIFIED;\n+ break;\n+ case \"\":\n+ if (addrType == AddressType.SERVICE_ADDR || addrType == AddressType.SERVICE_RANGE) { // NOPMD\n+ scope = Scope.SCOPE_CLUSTER;\n+ } else {\n+ scope = Scope.SCOPE_NOT_SPECIFIED;\n+ }\n+ break;\n+ default:\n+ scope = Scope.ofValue(parseUnsignedInt(scopeStr));\n+ break;\n+ }\n+\n+ int a = parseUnsignedInt(strA);\n+ int b = parseUnsignedInt(strB);\n+\n+ int c;\n+ if (strC == null || strC.isEmpty()) {\n+ if (addrType == AddressType.SERVICE_RANGE) { // NOPMD\n+ c = b;\n+ } else {\n+ c = 0;\n+ }\n+ } else {\n+ c = parseUnsignedInt(strC);\n+ }\n+\n+ int javaPort = javaPortStr == null || javaPortStr.isEmpty() ? port : Integer.parseInt(\n+ javaPortStr);\n+ if (overridePort != -1) {\n+ javaPort = overridePort;\n+ }\n+\n+ return resolveAddress(toBytes(addrType, scope, a, b, c), javaPort, addressFamily());\n+ } catch (IllegalArgumentException e) {\n+ throw (SocketException) new SocketException(\"Invalid TIPC URI: \" + uri).initCause(e);\n+ }\n+ }\n+\n+ @Override\n+ @SuppressWarnings({\"PMD.CognitiveComplexity\", \"PMD.CompareObjectsWithEquals\"})\n+ public URI toURI(String scheme, URI template) throws IOException {\n+ switch (scheme) {\n+ case \"tipc\":\n+ case \"http+tipc\":\n+ case \"https+tipc\":\n+ break;\n+ default:\n+ return super.toURI(scheme, template);\n+ }\n+\n+ byte[] bytes = getBytes();\n+ if (bytes.length != (5 * 4)) {\n+ return super.toURI(scheme, template);\n+ }\n+\n+ ByteBuffer bb = ByteBuffer.wrap(bytes);\n+ AddressType addrType = AddressType.ofValue(bb.getInt());\n+ Scope scope = Scope.ofValue(bb.getInt());\n+\n+ StringBuilder sb = new StringBuilder();\n+\n+ boolean haveScope = true;\n+ if (scope == Scope.SCOPE_NOT_SPECIFIED) {\n+ sb.append(\"default-\");\n+ } else if (scope == Scope.SCOPE_CLUSTER) {\n+ if (addrType == AddressType.SERVICE_ADDR || addrType == AddressType.SERVICE_RANGE) { // NOPMD\n+ // implied\n+ haveScope = false;\n+ } else {\n+ sb.append(\"cluster-\");\n+ }\n+ } else if (scope == Scope.SCOPE_NODE) {\n+ sb.append(\"node-\");\n+ } else {\n+ sb.append(toTipcInt(scope.value()));\n+ sb.append('-');\n+ }\n+\n+ boolean addrTypeImplied = false;\n+ if (addrType == AddressType.SERVICE_ADDR) {\n+ if (!haveScope) {\n+ addrTypeImplied = true;\n+ } else {\n+ sb.append(\"service\");\n+ }\n+ } else if (addrType == AddressType.SERVICE_RANGE) {\n+ sb.append(\"service-range\");\n+ } else if (addrType == AddressType.SOCKET_ADDR) {\n+ sb.append(\"socket\");\n+ } else {\n+ sb.append(toTipcInt(addrType.value()));\n+ }\n+ if (!addrTypeImplied) {\n+ sb.append('.');\n+ }\n+\n+ int a = bb.getInt();\n+ int b = bb.getInt();\n+ int c = bb.getInt();\n+\n+ sb.append(toTipcInt(a));\n+ sb.append('.');\n+ sb.append(toTipcInt(b));\n+ if (c != 0) {\n+ sb.append('.');\n+ sb.append(toTipcInt(c));\n+ }\n+\n+ return new HostAndPort(sb.toString(), getPort()).toURI(scheme, template);\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFTIPCSocketImplExtensions.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFTIPCSocketImplExtensions.java\nnew file mode 100644\nindex 000000000..0b678baae\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFTIPCSocketImplExtensions.java\n@@ -0,0 +1,82 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.IOException;\n+import java.nio.charset.StandardCharsets;\n+\n+/**\n+ * TIPC-specific code that resides in the native library. To be used by {@code AFTIPCSocket} and\n+ * {@code AFTIPCDatagramSocket} only.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public final class AFTIPCSocketImplExtensions implements\n+ AFSocketImplExtensions {\n+ private final AncillaryDataSupport ancillaryDataSupport;\n+\n+ AFTIPCSocketImplExtensions(AncillaryDataSupport ancillaryDataSupport) {\n+ this.ancillaryDataSupport = ancillaryDataSupport;\n+ }\n+\n+ /**\n+ * Returns the TIPC \"ErrInfo\" data from the ancillary receive buffer.\n+ * \n+ * Invalid for any other use.\n+ * \n+ * @return The errinfo.\n+ */\n+ public int[] getTIPCErrInfo() {\n+ return ancillaryDataSupport.getTIPCErrorInfo();\n+ }\n+\n+ /**\n+ * Returns the TIPC \"DestName\" data from the ancillary receive buffer.\n+ * \n+ * Invalid for any other use.\n+ * \n+ * @return The DestName.\n+ */\n+ public int[] getTIPCDestName() {\n+ return ancillaryDataSupport.getTIPCDestName();\n+ }\n+\n+ /**\n+ * Retrieves the 16-byte TIPC node identity given a node hash.\n+ * \n+ * @param peer The node hash.\n+ * @return The node identity, or {@code null} if unsupported.\n+ * @throws IOException on error.\n+ */\n+ public byte[] getTIPCNodeId(int peer) throws IOException {\n+ return NativeUnixSocket.tipcGetNodeId(peer);\n+ }\n+\n+ /**\n+ * Retrieves the TIPC link name given a node hash and bearer Id.\n+ * \n+ * @param peer The node hash.\n+ * @param bearerId The bearer Id.\n+ * @return The link name, or {@code null} if unsupported.\n+ * @throws IOException on error.\n+ */\n+ public String getTIPCLinkName(int peer, int bearerId) throws IOException {\n+ byte[] name = NativeUnixSocket.tipcGetLinkName(peer, bearerId);\n+ return name == null ? null : new String(name, StandardCharsets.UTF_8);\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramChannel.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramChannel.java\nindex 96b53622d..672192fc5 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramChannel.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramChannel.java\n@@ -19,35 +19,19 @@ package org.newsclub.net.unix;\n \n import java.io.FileDescriptor;\n import java.io.IOException;\n-import java.net.InetAddress;\n-import java.net.NetworkInterface;\n import java.net.ProtocolFamily;\n-import java.net.SocketAddress;\n import java.net.SocketException;\n-import java.net.SocketOption;\n-import java.nio.ByteBuffer;\n import java.nio.channels.DatagramChannel;\n-import java.nio.channels.MembershipKey;\n-import java.util.Set;\n-\n-import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n /**\n * A {@link DatagramChannel} implementation that works with AF_UNIX Unix domain sockets.\n * \n * @author Christian Kohlschütter\n */\n-public final class AFUNIXDatagramChannel extends DatagramChannel implements AFUNIXSomeSocket,\n+public final class AFUNIXDatagramChannel extends AFDatagramChannel implements\n AFUNIXSocketExtensions {\n- private final AFUNIXDatagramSocket afSocket;\n-\n AFUNIXDatagramChannel(AFUNIXDatagramSocket socket) {\n- super(AFUNIXSelectorProvider.getInstance());\n- this.afSocket = socket;\n- }\n-\n- AFUNIXDatagramSocket getAFSocket() {\n- return afSocket;\n+ super(AFUNIXSelectorProvider.getInstance(), socket);\n }\n \n /**\n@@ -75,121 +59,14 @@ public final class AFUNIXDatagramChannel extends DatagramChannel implements AFUN\n \n // CPD-OFF\n \n- @Override\n- public MembershipKey join(InetAddress group, NetworkInterface interf) throws IOException {\n- throw new UnsupportedOperationException();\n- }\n-\n- @Override\n- public MembershipKey join(InetAddress group, NetworkInterface interf, InetAddress source)\n- throws IOException {\n- throw new UnsupportedOperationException();\n- }\n-\n- @Override\n- public AFUNIXDatagramChannel bind(SocketAddress local) throws IOException {\n- afSocket.bind(local);\n- return this;\n- }\n-\n- @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n- @Override\n- public AFUNIXDatagramSocket socket() {\n- return afSocket;\n- }\n-\n- /**\n- * Returns the binding state of the socket.\n- * \n- * @return true if the socket successfully bound to an address\n- */\n- public boolean isBound() {\n- return afSocket.isBound();\n- }\n-\n- @Override\n- public boolean isConnected() {\n- return afSocket.isConnected();\n- }\n-\n- @Override\n- public AFUNIXDatagramChannel connect(SocketAddress remote) throws IOException {\n- afSocket.connect(remote);\n- return this;\n- }\n-\n- @Override\n- public AFUNIXDatagramChannel disconnect() throws IOException {\n- afSocket.disconnect();\n- return this;\n- }\n-\n- @Override\n- public AFUNIXSocketAddress getRemoteAddress() throws IOException {\n- return afSocket.getRemoteSocketAddress();\n- }\n-\n- @Override\n- public AFUNIXSocketAddress getLocalAddress() throws IOException {\n- return afSocket.getLocalSocketAddress();\n- }\n-\n- @Override\n- public AFUNIXSocketAddress receive(ByteBuffer dst) throws IOException {\n- return afSocket.getAFImpl().receive(dst);\n- }\n-\n- @Override\n- public int send(ByteBuffer src, SocketAddress target) throws IOException {\n- return afSocket.getAFImpl().send(src, target);\n- }\n-\n- @Override\n- public int read(ByteBuffer dst) throws IOException {\n- return afSocket.getAFImpl().read(dst, null);\n- }\n-\n- @Override\n- public long read(ByteBuffer[] dsts, int offset, int length) throws IOException {\n- if (length == 0) {\n- return 0;\n- }\n- // FIXME support more than one buffer for scatter-gather access\n- return read(dsts[offset]);\n- }\n-\n- @Override\n- public int write(ByteBuffer src) throws IOException {\n- return afSocket.getAFImpl().write(src);\n- }\n-\n- @Override\n- public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {\n- if (length == 0) {\n- return 0;\n- }\n- // FIXME support more than one buffer for scatter-gather access\n- return write(srcs[offset]);\n- }\n-\n- @Override\n- protected void implCloseSelectableChannel() throws IOException {\n- getAFSocket().close();\n- }\n-\n- @Override\n- protected void implConfigureBlocking(boolean block) throws IOException {\n- getAFCore().implConfigureBlocking(block);\n- }\n-\n @Override\n public FileDescriptor[] getReceivedFileDescriptors() throws IOException {\n- return afSocket.getReceivedFileDescriptors();\n+ return ((AFUNIXSocketExtensions) getAFSocket()).getReceivedFileDescriptors();\n }\n \n @Override\n public void clearReceivedFileDescriptors() {\n- afSocket.clearReceivedFileDescriptors();\n+ ((AFUNIXSocketExtensions) getAFSocket()).clearReceivedFileDescriptors();\n }\n \n @Override\n@@ -197,93 +74,16 @@ public final class AFUNIXDatagramChannel extends DatagramChannel implements AFUN\n if (fdescs != null && fdescs.length > 0 && !isConnected()) {\n throw new SocketException(\"Not connected\");\n }\n- afSocket.setOutboundFileDescriptors(fdescs);\n+ ((AFUNIXSocketExtensions) getAFSocket()).setOutboundFileDescriptors(fdescs);\n }\n \n @Override\n public boolean hasOutboundFileDescriptors() {\n- return afSocket.hasOutboundFileDescriptors();\n+ return ((AFUNIXSocketExtensions) getAFSocket()).hasOutboundFileDescriptors();\n }\n \n @Override\n public AFUNIXSocketCredentials getPeerCredentials() throws IOException {\n- return afSocket.getPeerCredentials();\n- }\n-\n- @Override\n- public int getAncillaryReceiveBufferSize() {\n- return afSocket.getAncillaryReceiveBufferSize();\n- }\n-\n- @Override\n- public void setAncillaryReceiveBufferSize(int size) {\n- afSocket.setAncillaryReceiveBufferSize(size);\n- }\n-\n- @Override\n- public void ensureAncillaryReceiveBufferSize(int minSize) {\n- afSocket.ensureAncillaryReceiveBufferSize(minSize);\n- }\n-\n- @Override\n- public AFUNIXDatagramChannel setOption(SocketOption name, T value) throws IOException {\n- Integer optionId = SocketOptionsMapper.resolve(name);\n- if (optionId == null) {\n- throw new UnsupportedOperationException(\"unsupported option\");\n- } else {\n- afSocket.getAFImpl().setOption(optionId.intValue(), value);\n- }\n- return this;\n- }\n-\n- @SuppressWarnings(\"unchecked\")\n- @Override\n- public T getOption(SocketOption name) throws IOException {\n- Integer optionId = SocketOptionsMapper.resolve(name);\n- if (optionId == null) {\n- throw new UnsupportedOperationException(\"unsupported option\");\n- } else {\n- return (T) afSocket.getAFImpl().getOption(optionId.intValue());\n- }\n- }\n-\n- @Override\n- public Set> supportedOptions() {\n- return SocketOptionsMapper.SUPPORTED_SOCKET_OPTIONS;\n- }\n-\n- AFUNIXSocketCore getAFCore() {\n- return afSocket.getAFImpl().getCore();\n- }\n-\n- @Override\n- public FileDescriptor getFileDescriptor() throws IOException {\n- return afSocket.getFileDescriptor();\n- }\n-\n- /**\n- * Checks if this {@link AFUNIXDatagramSocket}'s bound filename should be removed upon\n- * {@link #close()}.\n- * \n- * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n- * namespace).\n- * \n- * @return {@code true} if an attempt is made to delete the socket file upon {@link #close()}.\n- */\n- public boolean isDeleteOnClose() {\n- return afSocket.isDeleteOnClose();\n- }\n-\n- /**\n- * Enables/disables deleting this {@link AFUNIXDatagramSocket}'s bound filename upon\n- * {@link #close()}.\n- * \n- * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n- * namespace).\n- * \n- * @param b Enabled if {@code true}.\n- */\n- public void setDeleteOnClose(boolean b) {\n- afSocket.setDeleteOnClose(b);\n+ return ((AFUNIXSocketExtensions) getAFSocket()).getPeerCredentials();\n }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramSocket.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramSocket.java\nindex bedf09d44..e9682c017 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramSocket.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramSocket.java\n@@ -19,35 +19,24 @@ package org.newsclub.net.unix;\n \n import java.io.FileDescriptor;\n import java.io.IOException;\n-import java.net.DatagramPacket;\n import java.net.DatagramSocket;\n-import java.net.InetAddress;\n-import java.net.InetSocketAddress;\n-import java.net.SocketAddress;\n import java.net.SocketException;\n-import java.util.concurrent.atomic.AtomicBoolean;\n-\n-import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n /**\n * A {@link DatagramSocket} implementation that works with AF_UNIX Unix domain sockets.\n * \n * @author Christian Kohlschütter\n */\n-public final class AFUNIXDatagramSocket extends DatagramSocket implements AFUNIXSomeSocket,\n+public final class AFUNIXDatagramSocket extends AFDatagramSocket implements\n AFUNIXSocketExtensions {\n- private static final InetSocketAddress WILDCARD_ADDRESS = new InetSocketAddress(0);\n \n- private final AFUNIXDatagramSocketImpl impl;\n- private final AncillaryDataSupport ancillaryDataSupport;\n- private final AtomicBoolean created = new AtomicBoolean(false);\n- private final AtomicBoolean deleteOnClose = new AtomicBoolean(true);\n- private final AFUNIXDatagramChannel channel = new AFUNIXDatagramChannel(this);\n+ AFUNIXDatagramSocket(final FileDescriptor fd) throws IOException {\n+ super(new AFUNIXDatagramSocketImpl(fd));\n+ }\n \n- private AFUNIXDatagramSocket(final AFUNIXDatagramSocketImpl impl) throws IOException {\n- super(impl);\n- this.impl = impl;\n- this.ancillaryDataSupport = impl.ancillaryDataSupport;\n+ @Override\n+ protected AFUNIXDatagramChannel newChannel() {\n+ return new AFUNIXDatagramChannel(this);\n }\n \n /**\n@@ -57,244 +46,28 @@ public final class AFUNIXDatagramSocket extends DatagramSocket implements AFUNIX\n * @throws IOException on error.\n */\n public static AFUNIXDatagramSocket newInstance() throws IOException {\n- return new AFUNIXDatagramSocket(new AFUNIXDatagramSocketImpl((FileDescriptor) null));\n+ return (AFUNIXDatagramSocket) newInstance(AFUNIXDatagramSocket::new);\n }\n \n static AFUNIXDatagramSocket newInstance(FileDescriptor fdObj, int localPort, int remotePort)\n throws IOException {\n- if (fdObj == null) {\n- return newInstance();\n- }\n- if (!fdObj.valid()) {\n- throw new SocketException(\"Invalid file descriptor\");\n- }\n-\n- int status = NativeUnixSocket.socketStatus(fdObj);\n- if (status == NativeUnixSocket.SOCKETSTATUS_INVALID) {\n- throw new SocketException(\"Not a valid socket\");\n- }\n-\n- AFUNIXDatagramSocket socket = new AFUNIXDatagramSocket(new AFUNIXDatagramSocketImpl(fdObj));\n- socket.getAFImpl().updatePorts(localPort, remotePort);\n-\n- switch (status) {\n- case NativeUnixSocket.SOCKETSTATUS_CONNECTED:\n- socket.internalDummyConnect();\n- break;\n- case NativeUnixSocket.SOCKETSTATUS_BOUND:\n- socket.internalDummyBind();\n- break;\n- case NativeUnixSocket.SOCKETSTATUS_UNKNOWN:\n- break;\n- default:\n- throw new IllegalStateException(\"Invalid socketStatus response: \" + status);\n- }\n-\n- return socket;\n- }\n-\n- @Override\n- public void connect(InetAddress address, int port) {\n- throw new IllegalArgumentException(\"Cannot connect to InetAddress\");\n- }\n-\n- /**\n- * Reads the next received packet without actually removing it from the queue.\n- * \n- * In other words, once a packet is received, calling this method multiple times in a row will not\n- * have further effects on the packet contents.\n- * \n- * This call still blocks until at least one packet has been received and added to the queue.\n- * \n- * @param p The packet.\n- * @throws IOException on error.\n- */\n- public void peek(DatagramPacket p) throws IOException {\n- synchronized (p) {\n- if (isClosed()) {\n- throw new SocketException(\"Socket is closed\");\n- }\n- getAFImpl().peekData(p);\n- }\n- }\n-\n- @Override\n- public void send(DatagramPacket p) throws IOException {\n- synchronized (p) {\n- if (isClosed()) {\n- throw new SocketException(\"Socket is closed\");\n- }\n- if (!isBound()) {\n- internalDummyBind();\n- }\n- getAFImpl().send(p);\n- }\n- }\n-\n- void internalDummyConnect() throws SocketException {\n- super.connect(AFUNIXSocketAddress.INTERNAL_DUMMY_DONT_CONNECT);\n- }\n-\n- void internalDummyBind() throws SocketException {\n- bind(AFUNIXSocketAddress.INTERNAL_DUMMY_BIND);\n- }\n-\n- @Override\n- public synchronized void connect(SocketAddress addr) throws SocketException {\n- if (!isBound()) {\n- internalDummyBind();\n- }\n- internalDummyConnect();\n- try {\n- getAFImpl().connect(AFUNIXSocketAddress.preprocessSocketAddress(addr, null));\n- } catch (SocketException e) {\n- throw e;\n- } catch (IOException e) {\n- throw (SocketException) new SocketException(e.getMessage()).initCause(e);\n- }\n+ return (AFUNIXDatagramSocket) newInstance(AFUNIXDatagramSocket::new, fdObj, localPort,\n+ remotePort);\n }\n \n @Override\n- public synchronized AFUNIXSocketAddress getRemoteSocketAddress() {\n- return getAFImpl().getRemoteSocketAddress();\n- }\n-\n- @Override\n- public boolean isConnected() {\n- return super.isConnected() || impl.isConnected();\n- }\n-\n- @Override\n- public boolean isBound() {\n- return super.isBound() || impl.isBound();\n- }\n-\n- @Override\n- public void close() {\n- // IMPORTANT This method must not be synchronized on \"this\",\n- // otherwise we can't unblock a pending read\n- if (isClosed()) {\n- return;\n- }\n- getAFImpl().close();\n- boolean wasBound = isBound();\n- if (wasBound && deleteOnClose.get()) {\n- InetAddress addr = getLocalAddress();\n- if (AFUNIXSocketAddress.isSupportedAddress(addr)) {\n- try {\n- AFUNIXSocketAddress socketAddress = AFUNIXSocketAddress.unwrap(addr, 0);\n- if (socketAddress.hasFilename()) {\n- if (!socketAddress.getFile().delete()) {\n- // ignore\n- }\n- }\n- } catch (IOException e) {\n- // ignore\n- }\n- }\n- }\n- super.close();\n- }\n-\n- @Override\n- public synchronized void bind(SocketAddress addr) throws SocketException {\n- if (isClosed()) {\n- throw new SocketException(\"Socket is closed\");\n- }\n- if (isBound()) {\n- if (addr == AFUNIXSocketAddress.INTERNAL_DUMMY_BIND) { // NOPMD\n- return;\n- }\n- throw new SocketException(\"already bound\");\n- }\n- super.bind(AFUNIXSocketAddress.INTERNAL_DUMMY_BIND);\n- if (addr == null || WILDCARD_ADDRESS.equals(addr)) {\n- return;\n- }\n- AFUNIXSocketAddress epoint = AFUNIXSocketAddress.preprocessSocketAddress(addr, null);\n- try {\n- getAFImpl().bind(epoint);\n- } catch (SocketException e) {\n- getAFImpl().close();\n- throw e;\n- }\n- }\n-\n- @Override\n- public AFUNIXSocketAddress getLocalSocketAddress() {\n- if (isClosed()) {\n- return null;\n- }\n- if (!isBound()) {\n- return null;\n- }\n- try {\n- return AFUNIXSocketAddress.unwrap(getLocalAddress(), getLocalPort());\n- } catch (SocketException e) {\n- return null;\n- }\n- }\n-\n- /**\n- * Checks if this {@link AFUNIXDatagramSocket}'s bound filename should be removed upon\n- * {@link #close()}.\n- * \n- * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n- * namespace).\n- * \n- * @return {@code true} if an attempt is made to delete the socket file upon {@link #close()}.\n- */\n- public boolean isDeleteOnClose() {\n- return deleteOnClose.get();\n- }\n-\n- /**\n- * Enables/disables deleting this {@link AFUNIXDatagramSocket}'s bound filename upon\n- * {@link #close()}.\n- * \n- * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n- * namespace).\n- * \n- * @param b Enabled if {@code true}.\n- */\n- public void setDeleteOnClose(boolean b) {\n- deleteOnClose.set(b);\n- }\n-\n- AFUNIXDatagramSocketImpl getAFImpl() {\n- if (created.compareAndSet(false, true)) {\n- try {\n- getSoTimeout(); // trigger create via java.net.Socket\n- } catch (SocketException e) {\n- // ignore\n- }\n- }\n- return impl;\n- }\n-\n- @Override\n- public int getAncillaryReceiveBufferSize() {\n- return ancillaryDataSupport.getAncillaryReceiveBufferSize();\n- }\n-\n- @Override\n- public void setAncillaryReceiveBufferSize(int size) {\n- ancillaryDataSupport.setAncillaryReceiveBufferSize(size);\n- }\n-\n- @Override\n- public void ensureAncillaryReceiveBufferSize(int minSize) {\n- ancillaryDataSupport.ensureAncillaryReceiveBufferSize(minSize);\n+ public AFUNIXDatagramChannel getChannel() {\n+ return (AFUNIXDatagramChannel) super.getChannel();\n }\n \n @Override\n public FileDescriptor[] getReceivedFileDescriptors() throws IOException {\n- return ancillaryDataSupport.getReceivedFileDescriptors();\n+ return getAncillaryDataSupport().getReceivedFileDescriptors();\n }\n \n @Override\n public void clearReceivedFileDescriptors() {\n- ancillaryDataSupport.clearReceivedFileDescriptors();\n+ getAncillaryDataSupport().clearReceivedFileDescriptors();\n }\n \n @Override\n@@ -302,12 +75,12 @@ public final class AFUNIXDatagramSocket extends DatagramSocket implements AFUNIX\n if (fdescs != null && fdescs.length > 0 && !isConnected()) {\n throw new SocketException(\"Not connected\");\n }\n- ancillaryDataSupport.setOutboundFileDescriptors(fdescs);\n+ getAncillaryDataSupport().setOutboundFileDescriptors(fdescs);\n }\n \n @Override\n public boolean hasOutboundFileDescriptors() {\n- return ancillaryDataSupport.hasOutboundFileDescriptors();\n+ return getAncillaryDataSupport().hasOutboundFileDescriptors();\n }\n \n @Override\n@@ -315,22 +88,6 @@ public final class AFUNIXDatagramSocket extends DatagramSocket implements AFUNIX\n if (isClosed() || !isConnected()) {\n throw new SocketException(\"Not connected\");\n }\n- return impl.getPeerCredentials();\n- }\n-\n- @Override\n- public boolean isClosed() {\n- return super.isClosed() || getAFImpl().isClosed();\n- }\n-\n- @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n- @Override\n- public AFUNIXDatagramChannel getChannel() {\n- return channel;\n- }\n-\n- @Override\n- public FileDescriptor getFileDescriptor() throws IOException {\n- return getAFImpl().getFileDescriptor();\n+ return ((AFUNIXDatagramSocketImpl) getAFImpl()).getPeerCredentials();\n }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramSocketImpl.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramSocketImpl.java\nindex 13639acde..5c92eabd7 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramSocketImpl.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramSocketImpl.java\n@@ -19,287 +19,13 @@ package org.newsclub.net.unix;\n \n import java.io.FileDescriptor;\n import java.io.IOException;\n-import java.net.DatagramPacket;\n-import java.net.DatagramSocketImpl;\n-import java.net.InetAddress;\n-import java.net.NetworkInterface;\n-import java.net.SocketAddress;\n-import java.net.SocketException;\n-import java.nio.ByteBuffer;\n-import java.util.concurrent.atomic.AtomicBoolean;\n-import java.util.concurrent.atomic.AtomicInteger;\n-\n-final class AFUNIXDatagramSocketImpl extends DatagramSocketImpl {\n- private final AFUNIXSocketCore core;\n- final AncillaryDataSupport ancillaryDataSupport = new AncillaryDataSupport();\n- private final AtomicBoolean connected = new AtomicBoolean(false);\n- private final AtomicBoolean bound = new AtomicBoolean(false);\n-\n- private final AtomicInteger socketTimeout = new AtomicInteger(0);\n- private int remotePort = 0;\n \n+final class AFUNIXDatagramSocketImpl extends AFDatagramSocketImpl {\n AFUNIXDatagramSocketImpl(FileDescriptor fd) throws IOException {\n- super();\n- this.core = new AFUNIXSocketCore(this, fd, ancillaryDataSupport);\n- this.fd = core.fd;\n- }\n-\n- @Override\n- protected void create() throws SocketException {\n- if (isClosed()) {\n- throw new SocketException(\"Already closed\");\n- } else if (fd.valid()) {\n- return;\n- }\n- try {\n- NativeUnixSocket.createSocket(fd, NativeUnixSocket.SOCK_DGRAM);\n- } catch (SocketException e) {\n- throw e;\n- } catch (IOException e) {\n- throw (SocketException) new SocketException(e.getMessage()).initCause(e);\n- }\n- }\n-\n- @Override\n- protected void close() {\n- core.runCleaner();\n- }\n-\n- @Override\n- protected void connect(InetAddress address, int port) throws SocketException {\n- // not used; see connect(AFUNIXSocketAddress)\n- }\n-\n- void connect(AFUNIXSocketAddress socketAddress) throws IOException {\n- if (socketAddress == AFUNIXSocketAddress.INTERNAL_DUMMY_CONNECT) { // NOPMD\n- return;\n- }\n- NativeUnixSocket.connect(socketAddress.getBytes(), fd, -1);\n- this.remotePort = socketAddress.getPort();\n- }\n-\n- @Override\n- protected void disconnect() {\n- try {\n- NativeUnixSocket.disconnect(fd);\n- connected.set(false);\n- this.remotePort = 0;\n- } catch (IOException e) {\n- e.printStackTrace();\n- }\n- }\n-\n- AFUNIXSocketCore getCore() {\n- return core;\n- }\n-\n- @Override\n- protected FileDescriptor getFileDescriptor() {\n- return core.fd;\n- }\n-\n- boolean isClosed() {\n- return core.isClosed();\n- }\n-\n- @Override\n- protected void bind(int lport, InetAddress laddr) throws SocketException {\n- // not used; see bind(AFUNIXSocketAddress)\n- }\n-\n- void bind(AFUNIXSocketAddress socketAddress) throws SocketException {\n- if (socketAddress == AFUNIXSocketAddress.INTERNAL_DUMMY_BIND) { // NOPMD\n- return;\n- }\n- try {\n- NativeUnixSocket.bind(socketAddress.getBytes(), fd, 0);\n- this.localPort = socketAddress.getPort();\n- } catch (SocketException e) {\n- throw e;\n- } catch (IOException e) {\n- throw (SocketException) new SocketException(e.getMessage()).initCause(e);\n- }\n- }\n-\n- @Override\n- protected void receive(DatagramPacket p) throws IOException {\n- recv(p, 0);\n- }\n-\n- private void recv(DatagramPacket p, int options) throws IOException {\n- int len = p.getLength();\n- FileDescriptor fdesc = core.validFdOrException();\n-\n- ByteBuffer datagramPacketBuffer = core.getThreadLocalDirectByteBuffer(len);\n- len = Math.min(len, datagramPacketBuffer.capacity());\n-\n- ByteBuffer socketAddressBuffer = AFUNIXSocketAddress.SOCKETADDRESS_BUFFER_TL.get();\n- int count = NativeUnixSocket.receive(fdesc, datagramPacketBuffer, 0, len, socketAddressBuffer,\n- options, ancillaryDataSupport, socketTimeout.get());\n- if (count > len || count < 0) {\n- throw new IllegalStateException();\n- }\n- datagramPacketBuffer.limit(count);\n- datagramPacketBuffer.rewind();\n- datagramPacketBuffer.get(p.getData(), p.getOffset(), count);\n-\n- p.setLength(count);\n-\n- AFUNIXSocketAddress addr = AFUNIXSocketAddress.ofInternal(socketAddressBuffer);\n- p.setAddress(addr == null ? null : addr.getInetAddress());\n- p.setPort(remotePort);\n- }\n-\n- @Override\n- protected void send(DatagramPacket p) throws IOException {\n- InetAddress addr = p.getAddress();\n- ByteBuffer sendToBuf = null;\n- if (addr != null) {\n- byte[] addrBytes = AFUNIXInetAddress.unwrapAddress(addr); // NOTE port is not unchecked\n- if (addrBytes != null) {\n- sendToBuf = AFUNIXSocketAddress.SOCKETADDRESS_BUFFER_TL.get();\n- NativeUnixSocket.bytesToSockAddrUn(sendToBuf, addrBytes);\n- }\n- }\n- FileDescriptor fdesc = core.validFdOrException();\n-\n- int len = p.getLength();\n- ByteBuffer datagramPacketBuffer = core.getThreadLocalDirectByteBuffer(len);\n- datagramPacketBuffer.clear();\n- datagramPacketBuffer.put(p.getData(), p.getOffset(), p.getLength());\n- NativeUnixSocket.send(fdesc, datagramPacketBuffer, 0, len, sendToBuf,\n- NativeUnixSocket.OPT_NON_BLOCKING, ancillaryDataSupport);\n- }\n-\n- @Override\n- protected int peek(InetAddress i) throws IOException {\n- throw new SocketException(\"Unsupported operation\");\n- }\n-\n- @Override\n- protected int peekData(DatagramPacket p) throws IOException {\n- recv(p, NativeUnixSocket.OPT_PEEK);\n- return 0;\n- }\n-\n- @Override\n- protected byte getTTL() throws IOException {\n- return (byte) (getTimeToLive() & 0xFF);\n- }\n-\n- @Override\n- protected void setTTL(byte ttl) throws IOException {\n- // ignored\n- }\n-\n- @Override\n- protected int getTimeToLive() throws IOException {\n- return 0;\n- }\n-\n- @Override\n- protected void setTimeToLive(int ttl) throws IOException {\n- // ignored\n- }\n-\n- @Override\n- protected void join(InetAddress inetaddr) throws IOException {\n- throw new SocketException(\"Unsupported\");\n- }\n-\n- @Override\n- protected void leave(InetAddress inetaddr) throws IOException {\n- throw new SocketException(\"Unsupported\");\n- }\n-\n- @Override\n- protected void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOException {\n- throw new SocketException(\"Unsupported\");\n- }\n-\n- @Override\n- protected void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOException {\n- throw new SocketException(\"Unsupported\");\n- }\n-\n- @Override\n- public Object getOption(int optID) throws SocketException {\n- if (isClosed()) {\n- throw new SocketException(\"Socket is closed\");\n- }\n-\n- FileDescriptor fdesc = core.validFdOrException();\n- return AFUNIXSocketImpl.getOptionDefault(fdesc, optID, socketTimeout);\n- }\n-\n- @Override\n- public void setOption(int optID, Object value) throws SocketException {\n- if (isClosed()) {\n- throw new SocketException(\"Socket is closed\");\n- }\n-\n- FileDescriptor fdesc = core.validFdOrException();\n- AFUNIXSocketImpl.setOptionDefault(fdesc, optID, value, socketTimeout);\n+ super(AFUNIXSocketAddress.AF_UNIX, fd, AFSocketType.SOCK_DGRAM);\n }\n \n AFUNIXSocketCredentials getPeerCredentials() throws IOException {\n return NativeUnixSocket.peerCredentials(fd, new AFUNIXSocketCredentials());\n }\n-\n- AFUNIXSocketAddress receive(ByteBuffer dst) throws IOException {\n- return core.receive(dst);\n- }\n-\n- int send(ByteBuffer src, SocketAddress target) throws IOException {\n- return core.write(src, target, 0);\n- }\n-\n- int read(ByteBuffer dst, ByteBuffer socketAddressBuffer) throws IOException {\n- return core.read(dst, socketAddressBuffer, 0);\n- }\n-\n- int write(ByteBuffer src) throws IOException {\n- return core.write(src);\n- }\n-\n- boolean isConnected() {\n- if (connected.get()) {\n- return true;\n- }\n- if (isClosed()) {\n- return false;\n- }\n- if (core.isConnected(false)) {\n- connected.set(true);\n- return true;\n- }\n- return false;\n- }\n-\n- boolean isBound() {\n- if (bound.get()) {\n- return true;\n- }\n- if (isClosed()) {\n- return false;\n- }\n- if (core.isConnected(true)) {\n- bound.set(true);\n- return true;\n- }\n- return false;\n- }\n-\n- void updatePorts(int local, int remote) {\n- this.localPort = local;\n- this.remotePort = remote;\n- }\n-\n- AFUNIXSocketAddress getLocalSocketAddress() {\n- return AFUNIXSocketAddress.getSocketAddress(getFileDescriptor(), false, localPort);\n- }\n-\n- AFUNIXSocketAddress getRemoteSocketAddress() {\n- return AFUNIXSocketAddress.getSocketAddress(getFileDescriptor(), true, remotePort);\n- }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramUtil.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramUtil.java\ndeleted file mode 100644\nindex d6ac71b43..000000000\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXDatagramUtil.java\n+++ /dev/null\n@@ -1,58 +0,0 @@\n-/*\n- * junixsocket\n- *\n- * Copyright 2009-2021 Christian Kohlschütter\n- *\n- * Licensed under the Apache License, Version 2.0 (the \"License\");\n- * you may not use this file except in compliance with the License.\n- * You may obtain a copy of the License at\n- *\n- * http://www.apache.org/licenses/LICENSE-2.0\n- *\n- * Unless required by applicable law or agreed to in writing, software\n- * distributed under the License is distributed on an \"AS IS\" BASIS,\n- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- * See the License for the specific language governing permissions and\n- * limitations under the License.\n- */\n-package org.newsclub.net.unix;\n-\n-import java.net.DatagramPacket;\n-\n-import com.kohlschutter.annotations.compiletime.ExcludeFromCodeCoverageGeneratedReport;\n-\n-final class AFUNIXDatagramUtil {\n- @ExcludeFromCodeCoverageGeneratedReport\n- private AFUNIXDatagramUtil() {\n- throw new IllegalStateException(\"No instances\");\n- }\n-\n- public static DatagramPacket datagramWithCapacityAndPayload(byte[] payload) {\n- return new DatagramPacket(payload, payload.length);\n- }\n-\n- public static DatagramPacket datagramWithCapacityAndPayload(int capacity, byte[] payload) {\n- if (capacity < payload.length) {\n- throw new IllegalArgumentException(\"data exceeds capacity\");\n- } else if (capacity == payload.length) {\n- return new DatagramPacket(payload, payload.length);\n- }\n- byte[] buf = new byte[capacity];\n- System.arraycopy(payload, 0, buf, 0, payload.length);\n-\n- DatagramPacket dp = new DatagramPacket(buf, buf.length);\n- dp.setLength(payload.length);\n- return dp;\n- }\n-\n- public static void expandToCapacity(DatagramPacket dp) {\n- synchronized (dp) {\n- byte[] data = dp.getData();\n- dp.setLength(data.length - dp.getOffset());\n- }\n- }\n-\n- public static DatagramPacket datagramWithCapacity(int i) {\n- return new DatagramPacket(new byte[i], i);\n- }\n-}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXProtocolFamily.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXProtocolFamily.java\nindex 437151faf..8a88f28f4 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXProtocolFamily.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXProtocolFamily.java\n@@ -20,13 +20,13 @@ package org.newsclub.net.unix;\n import java.net.ProtocolFamily;\n \n /**\n- * Describes the protocol families supported by junixsocket.\n+ * Describes the protocol family supported by {@link AFUNIXSocketAddress} etc.\n * \n * @author Christian Kohlschütter\n */\n public enum AFUNIXProtocolFamily implements ProtocolFamily {\n /**\n- * Unix domain (Local) interprocess communication.\n+ * UNIX domain.\n */\n- UNIX\n+ UNIX;\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSelector.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSelector.java\ndeleted file mode 100644\nindex 8aa7cf6d0..000000000\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSelector.java\n+++ /dev/null\n@@ -1,274 +0,0 @@\n-/*\n- * junixsocket\n- *\n- * Copyright 2009-2021 Christian Kohlschütter\n- *\n- * Licensed under the Apache License, Version 2.0 (the \"License\");\n- * you may not use this file except in compliance with the License.\n- * You may obtain a copy of the License at\n- *\n- * http://www.apache.org/licenses/LICENSE-2.0\n- *\n- * Unless required by applicable law or agreed to in writing, software\n- * distributed under the License is distributed on an \"AS IS\" BASIS,\n- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- * See the License for the specific language governing permissions and\n- * limitations under the License.\n- */\n-package org.newsclub.net.unix;\n-\n-import java.io.FileDescriptor;\n-import java.io.IOException;\n-import java.net.SocketTimeoutException;\n-import java.nio.ByteBuffer;\n-import java.nio.channels.SelectionKey;\n-import java.nio.channels.Selector;\n-import java.nio.channels.spi.AbstractSelectableChannel;\n-import java.nio.channels.spi.AbstractSelector;\n-import java.nio.channels.spi.SelectorProvider;\n-import java.util.Collection;\n-import java.util.Collections;\n-import java.util.HashSet;\n-import java.util.Iterator;\n-import java.util.Set;\n-\n-final class AFUNIXSelector extends AbstractSelector {\n- private static AFUNIXPipe sharedSelectorPipe = null;\n- private static PollFd sharedSelectorPipePollFd;\n-\n- private static final ByteBuffer PIPE_MSG = ByteBuffer.allocate(1);\n- private static final ByteBuffer PIPE_MSG_RECEIVE_BUFFER = ByteBuffer.allocateDirect(256);\n-\n- private final Set keysRegistered = new HashSet<>();\n-\n- @SuppressWarnings(\"unchecked\")\n- private final Set keysView =\n- (Set) (Set) Collections.unmodifiableSet(keysRegistered);\n-\n- private PollFd pollFd = null;\n-\n- private final SelectionKeySet keysSelected = new SelectionKeySet();\n-\n- protected AFUNIXSelector(SelectorProvider provider) {\n- super(provider);\n- }\n-\n- protected AFUNIXPipe selectorPipe() throws IOException {\n- AFUNIXPipe selectorPipe;\n- synchronized (AFUNIXSelector.class) {\n- if (sharedSelectorPipe == null) {\n- sharedSelectorPipe = AFUNIXSelectorProvider.getInstance().openSelectablePipe();\n- sharedSelectorPipePollFd = new PollFd(sharedSelectorPipe.sourceFD());\n- }\n- selectorPipe = sharedSelectorPipe;\n- }\n- return selectorPipe;\n- }\n-\n- @Override\n- protected SelectionKey register(AbstractSelectableChannel ch, int ops, Object att) {\n- AFUNIXSelectionKey key = new AFUNIXSelectionKey(this, ch, ops, att);\n- pollFd = null;\n- keysRegistered.add(key);\n- return key;\n- }\n-\n- @Override\n- public Set keys() {\n- return keysView;\n- }\n-\n- @Override\n- public Set selectedKeys() {\n- return keysSelected;\n- }\n-\n- @Override\n- public int selectNow() throws IOException {\n- return select0(0);\n- }\n-\n- @Override\n- public int select(long timeout) throws IOException {\n- if (timeout > Integer.MAX_VALUE) {\n- timeout = Integer.MAX_VALUE;\n- } else if (timeout < 0) {\n- throw new IllegalArgumentException(\"Timeout must not be negative\");\n- }\n-\n- return select0((int) timeout);\n- }\n-\n- @Override\n- public int select() throws IOException {\n- try {\n- return select0(-1);\n- } catch (SocketTimeoutException e) {\n- return 0;\n- }\n- }\n-\n- private int select0(int timeout) throws IOException {\n- pollFd = initPollFd(pollFd);\n-\n- keysSelected.clear();\n-\n- int num;\n- begin();\n- try {\n- num = NativeUnixSocket.poll(pollFd, timeout);\n- } finally {\n- end();\n- }\n- if (num > 0) {\n- consumeAllBytesAfterPoll();\n- setOpsReady();\n- }\n- return keysSelected.size();\n- }\n-\n- private void consumeAllBytesAfterPoll() throws IOException {\n- if ((pollFd.rops[0] & SelectionKey.OP_READ) == 0) {\n- return;\n- }\n- synchronized (PIPE_MSG_RECEIVE_BUFFER) {\n- PIPE_MSG_RECEIVE_BUFFER.clear();\n- int maxReceive = PIPE_MSG_RECEIVE_BUFFER.remaining();\n- int bytesReceived = NativeUnixSocket.receive(pollFd.fds[0], PIPE_MSG_RECEIVE_BUFFER, 0,\n- maxReceive, null, NativeUnixSocket.OPT_NON_SOCKET, null, 0);\n-\n- if (bytesReceived == maxReceive) {\n- // consume all pending bytes\n- int read;\n- do {\n- if ((read = NativeUnixSocket.poll(sharedSelectorPipePollFd, 0)) > 0) {\n- PIPE_MSG_RECEIVE_BUFFER.clear();\n- read = NativeUnixSocket.receive(sharedSelectorPipePollFd.fds[0],\n- PIPE_MSG_RECEIVE_BUFFER, 0, maxReceive, null, NativeUnixSocket.OPT_NON_SOCKET, null,\n- 0);\n- }\n- } while (read == maxReceive);\n- }\n- }\n- }\n-\n- private void setOpsReady() {\n- for (int i = 1; i < pollFd.rops.length; i++) {\n- int rops = pollFd.rops[i];\n- if (rops == 0) {\n- continue;\n- }\n- AFUNIXSelectionKey key = pollFd.keys[i];\n- key.setOpsReady(rops);\n- keysSelected.add0(key);\n- }\n- }\n-\n- @SuppressWarnings(\"resource\")\n- private PollFd initPollFd(PollFd existingPollFd) throws IOException {\n- for (Iterator it = keysRegistered.iterator(); it.hasNext();) {\n- AFUNIXSelectionKey key = it.next();\n- if (!key.getAFCore().fd.valid()) {\n- key.cancelNoRemove();\n- it.remove();\n- existingPollFd = null;\n- }\n- }\n-\n- if (existingPollFd != null) {\n- return existingPollFd;\n- }\n-\n- int size = keysRegistered.size() + 1;\n- FileDescriptor[] fds = new FileDescriptor[size];\n- int[] ops = new int[size];\n-\n- AFUNIXSelectionKey[] keys = new AFUNIXSelectionKey[size];\n- fds[0] = selectorPipe().sourceFD();\n- ops[0] = SelectionKey.OP_READ;\n-\n- int i = 1;\n- for (AFUNIXSelectionKey key : keysRegistered) {\n- keys[i] = key;\n- fds[i] = key.getAFCore().fd;\n- ops[i] = key.interestOps();\n- }\n- return new PollFd(keys, fds, ops);\n- }\n-\n- @Override\n- protected void implCloseSelector() throws IOException {\n- wakeup();\n- for (AFUNIXSelectionKey key : keysRegistered) {\n- key.cancelNoRemove();\n- }\n- keysRegistered.clear();\n- }\n-\n- @Override\n- public Selector wakeup() {\n- try {\n- selectorPipe().sink().write(PIPE_MSG);\n- } catch (IOException e) {\n- // FIXME throw as runtimeexception?\n- e.printStackTrace();\n- }\n- return this;\n- }\n-\n- void remove(AFUNIXSelectionKey key) {\n- keysRegistered.remove(key);\n- pollFd = null;\n- }\n-\n- static final class PollFd {\n- // accessed from native code\n- final FileDescriptor[] fds;\n- // accessed from native code\n- final int[] ops;\n- // accessed from native code\n- final int[] rops;\n-\n- final AFUNIXSelectionKey[] keys;\n-\n- PollFd(FileDescriptor pipeSourceFd) {\n- this(pipeSourceFd, SelectionKey.OP_READ);\n- }\n-\n- PollFd(FileDescriptor pipeSourceFd, int op) {\n- this.fds = new FileDescriptor[] {pipeSourceFd};\n- this.ops = new int[] {op};\n- this.rops = new int[1];\n- this.keys = null;\n- }\n-\n- @SuppressWarnings(\"PMD.ArrayIsStoredDirectly\")\n- PollFd(AFUNIXSelectionKey[] keys, FileDescriptor[] fds, int[] ops) {\n- this.keys = keys;\n- if (fds.length != ops.length) {\n- throw new IllegalStateException();\n- }\n- this.fds = fds;\n- this.ops = ops;\n- this.rops = new int[ops.length];\n- }\n- }\n-\n- private static final class SelectionKeySet extends HashSet {\n- private static final long serialVersionUID = 1L;\n-\n- @Override\n- public boolean add(SelectionKey e) {\n- throw new UnsupportedOperationException();\n- }\n-\n- private void add0(SelectionKey e) {\n- super.add(e);\n- }\n-\n- @Override\n- public boolean addAll(Collection c) {\n- throw new UnsupportedOperationException();\n- }\n- }\n-}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSelectorProvider.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSelectorProvider.java\nindex 55db70276..b79bf52c8 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSelectorProvider.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSelectorProvider.java\n@@ -20,14 +20,67 @@ package org.newsclub.net.unix;\n import java.io.IOException;\n import java.net.ProtocolFamily;\n import java.net.SocketAddress;\n-import java.nio.channels.spi.AbstractSelector;\n-import java.nio.channels.spi.SelectorProvider;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n /**\n * Service-provider class for junixsocket selectors and selectable channels.\n */\n-public final class AFUNIXSelectorProvider extends SelectorProvider {\n+public final class AFUNIXSelectorProvider extends AFSelectorProvider {\n private static final AFUNIXSelectorProvider INSTANCE = new AFUNIXSelectorProvider();\n+ \n+ @SuppressWarnings(\"null\")\n+ static final AFAddressFamily<@NonNull AFUNIXSocketAddress> AF_UNIX = //\n+ AFAddressFamily.registerAddressFamilyImpl(\"un\", AFUNIXSocketAddress.AF_UNIX, //\n+\n+ new AFAddressFamilyConfig() {\n+ @Override\n+ public Class> socketClass() {\n+ return AFUNIXSocket.class;\n+ }\n+\n+ @Override\n+ public AFSocket.Constructor socketConstructor() {\n+ return AFUNIXSocket::new;\n+ }\n+\n+ @Override\n+ public Class> serverSocketClass() {\n+ return AFUNIXServerSocket.class;\n+ }\n+\n+ @Override\n+ public AFServerSocket.Constructor serverSocketConstructor() {\n+ return AFUNIXServerSocket::new;\n+ }\n+\n+ @Override\n+ public Class> socketChannelClass() {\n+ return AFUNIXSocketChannel.class;\n+ }\n+\n+ @Override\n+ public Class> serverSocketChannelClass() {\n+ return AFUNIXServerSocketChannel.class;\n+ }\n+\n+ @Override\n+ public Class> datagramSocketClass() {\n+ return AFUNIXDatagramSocket.class;\n+ }\n+\n+ @Override\n+ public AFDatagramSocket.Constructor datagramSocketConstructor() {\n+ return AFUNIXDatagramSocket::new;\n+ }\n+\n+ @Override\n+ public Class> datagramChannelClass() {\n+ return AFUNIXDatagramChannel.class;\n+ }\n+ });\n \n private AFUNIXSelectorProvider() {\n super();\n@@ -38,6 +91,7 @@ public final class AFUNIXSelectorProvider extends SelectorProvider {\n * \n * @return The instance.\n */\n+ @SuppressFBWarnings(\"MS_EXPOSE_REP\")\n public static AFUNIXSelectorProvider getInstance() {\n return INSTANCE;\n }\n@@ -51,77 +105,36 @@ public final class AFUNIXSelectorProvider extends SelectorProvider {\n return getInstance();\n }\n \n- /**\n- * Opens a socket pair of interconnected channels.\n- * \n- * @return The new channel pair.\n- * @throws IOException on error.\n- */\n- @SuppressWarnings(\"resource\")\n- public AFUNIXSocketPair openSocketChannelPair() throws IOException {\n- AFUNIXSocketChannel s1 = openSocketChannel();\n- AFUNIXSocketChannel s2 = openSocketChannel();\n-\n- NativeUnixSocket.socketPair(NativeUnixSocket.SOCK_STREAM, s1.getAFCore().fd, s2.getAFCore().fd);\n-\n- s1.socket().internalDummyConnect();\n- s2.socket().internalDummyConnect();\n-\n- return new AFUNIXSocketPair(s1, s2);\n- }\n-\n- /**\n- * Opens a socket pair of interconnected datagram channels.\n- * \n- * @return The new channel pair.\n- * @throws IOException on error.\n- */\n- @SuppressWarnings(\"resource\")\n- public AFUNIXSocketPair openDatagramChannelPair() throws IOException {\n- AFUNIXDatagramChannel s1 = openDatagramChannel(AFUNIXProtocolFamily.UNIX);\n- AFUNIXDatagramChannel s2 = openDatagramChannel(AFUNIXProtocolFamily.UNIX);\n-\n- NativeUnixSocket.socketPair(NativeUnixSocket.SOCK_STREAM, s1.getAFCore().fd, s2.getAFCore().fd);\n-\n- s1.socket().internalDummyBind();\n- s2.socket().internalDummyBind();\n- s1.socket().internalDummyConnect();\n- s2.socket().internalDummyConnect();\n-\n- return new AFUNIXSocketPair(s1, s2);\n+ @Override\n+ protected

AFSocketPair

newSocketPair(P s1, P s2) {\n+ return new AFUNIXSocketPair

(s1, s2);\n }\n \n+ @SuppressWarnings(\"unchecked\")\n @Override\n- public AFUNIXDatagramChannel openDatagramChannel() throws IOException {\n- return AFUNIXDatagramSocket.newInstance().getChannel();\n+ public AFUNIXSocketPair openSocketChannelPair() throws IOException {\n+ return (AFUNIXSocketPair) super.openSocketChannelPair();\n }\n \n+ @SuppressWarnings(\"unchecked\")\n @Override\n- public AFUNIXDatagramChannel openDatagramChannel(ProtocolFamily family) throws IOException {\n- if (!AFUNIXProtocolFamily.UNIX.name().equals(family.name())) {\n- throw new UnsupportedOperationException(\"Unsupported protocol family\");\n- }\n- return openDatagramChannel();\n+ public AFUNIXSocketPair openDatagramChannelPair() throws IOException {\n+ return (AFUNIXSocketPair) super.openDatagramChannelPair();\n }\n \n @Override\n- public AFUNIXPipe openPipe() throws IOException {\n- return new AFUNIXPipe(this, false);\n+ protected AFUNIXSocket newSocket() throws IOException {\n+ return AFUNIXSocket.newInstance();\n }\n \n- /**\n- * Opens a pipe with support for selectors.\n- * \n- * @return The new pipe\n- * @throws IOException on error.\n- */\n- public AFUNIXPipe openSelectablePipe() throws IOException {\n- return new AFUNIXPipe(this, true);\n+ @Override\n+ public AFUNIXDatagramChannel openDatagramChannel() throws IOException {\n+ return AFUNIXDatagramSocket.newInstance().getChannel();\n }\n \n @Override\n- public AbstractSelector openSelector() throws IOException {\n- return new AFUNIXSelector(this);\n+ public AFUNIXDatagramChannel openDatagramChannel(ProtocolFamily family) throws IOException {\n+ return (AFUNIXDatagramChannel) super.openDatagramChannel(family);\n }\n \n @Override\n@@ -129,30 +142,28 @@ public final class AFUNIXSelectorProvider extends SelectorProvider {\n return AFUNIXServerSocket.newInstance().getChannel();\n }\n \n- /**\n- * Opens a server-socket channel bound on the given {@link SocketAddress}.\n- *\n- * @param sa The socket address to bind on.\n- * @return The new channel\n- * @throws IOException on error.\n- */\n+ @Override\n public AFUNIXServerSocketChannel openServerSocketChannel(SocketAddress sa) throws IOException {\n return AFUNIXServerSocket.bindOn(AFUNIXSocketAddress.unwrap(sa)).getChannel();\n }\n \n @Override\n public AFUNIXSocketChannel openSocketChannel() throws IOException {\n- return AFUNIXSocket.newInstance().getChannel();\n+ return (AFUNIXSocketChannel) super.openSocketChannel();\n }\n \n- /**\n- * Opens a socket channel connected to the given {@link SocketAddress}.\n- * \n- * @param sa The socket address to connect to.\n- * @return The new channel\n- * @throws IOException on error.\n- */\n+ @Override\n public AFUNIXSocketChannel openSocketChannel(SocketAddress sa) throws IOException {\n return AFUNIXSocket.connectTo(AFUNIXSocketAddress.unwrap(sa)).getChannel();\n }\n+\n+ @Override\n+ protected ProtocolFamily protocolFamily() {\n+ return AFUNIXProtocolFamily.UNIX;\n+ }\n+\n+ @Override\n+ protected AFAddressFamily<@NonNull AFUNIXSocketAddress> addressFamily() {\n+ return AFUNIXSocketAddress.AF_UNIX;\n+ }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXServerSocket.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXServerSocket.java\nindex 7378d42fc..aa4c4a3c1 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXServerSocket.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXServerSocket.java\n@@ -17,87 +17,62 @@\n */\n package org.newsclub.net.unix;\n \n-import java.io.Closeable;\n import java.io.File;\n import java.io.FileDescriptor;\n import java.io.IOException;\n import java.net.ServerSocket;\n-import java.net.SocketAddress;\n import java.net.SocketException;\n import java.nio.file.Path;\n-import java.util.concurrent.atomic.AtomicBoolean;\n-\n-import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n /**\n * The server part of an AF_UNIX domain socket.\n * \n * @author Christian Kohlschütter\n */\n-public class AFUNIXServerSocket extends ServerSocket implements FileDescriptorAccess {\n- private final AFUNIXSocketImpl implementation;\n- private AFUNIXSocketAddress boundEndpoint;\n- private final Closeables closeables = new Closeables();\n- private final AtomicBoolean created = new AtomicBoolean(false);\n- private final AtomicBoolean deleteOnClose = new AtomicBoolean(true);\n- private final AFUNIXServerSocketChannel channel = new AFUNIXServerSocketChannel(this);\n-\n+public class AFUNIXServerSocket extends AFServerSocket {\n /**\n * Constructs a new, unconnected instance.\n * \n * @throws IOException if the operation fails.\n */\n protected AFUNIXServerSocket() throws IOException {\n- this((FileDescriptor) null);\n+ super();\n }\n \n+ /**\n+ * Constructs a new instance, optionally associated with the given file descriptor.\n+ * \n+ * @param fdObj The file descriptor, or {@code null}.\n+ * @throws IOException if the operation fails.\n+ */\n AFUNIXServerSocket(FileDescriptor fdObj) throws IOException {\n- super();\n- this.implementation = new AFUNIXSocketImpl(fdObj);\n- NativeUnixSocket.initServerImpl(this, implementation);\n+ super(fdObj);\n+ }\n \n- setReuseAddress(true);\n+ @Override\n+ protected AFUNIXServerSocketChannel newChannel() {\n+ return new AFUNIXServerSocketChannel(this);\n+ }\n+\n+ @Override\n+ public AFUNIXServerSocketChannel getChannel() {\n+ return (AFUNIXServerSocketChannel) super.getChannel();\n }\n \n /**\n * Returns a new, unbound AF_UNIX {@link ServerSocket}.\n * \n- * @return The new, unbound {@link AFUNIXServerSocket}.\n+ * @return The new, unbound {@link AFServerSocket}.\n * @throws IOException if the operation fails.\n */\n public static AFUNIXServerSocket newInstance() throws IOException {\n- return new AFUNIXServerSocket(null);\n+ return (AFUNIXServerSocket) AFServerSocket.newInstance(AFUNIXServerSocket::new);\n }\n \n static AFUNIXServerSocket newInstance(FileDescriptor fdObj, int localPort, int remotePort)\n throws IOException {\n- if (fdObj == null) {\n- return newInstance();\n- }\n-\n- int status = NativeUnixSocket.socketStatus(fdObj);\n- if (!fdObj.valid() || status == NativeUnixSocket.SOCKETSTATUS_INVALID) {\n- throw new SocketException(\"Not a valid socket\");\n- }\n- AFUNIXServerSocket socket = new AFUNIXServerSocket(fdObj);\n- socket.getAFImpl().updatePorts(localPort, remotePort);\n-\n- switch (status) {\n- case NativeUnixSocket.SOCKETSTATUS_CONNECTED:\n- throw new SocketException(\"Not a ServerSocket\");\n- case NativeUnixSocket.SOCKETSTATUS_BOUND:\n- socket.bind(AFUNIXSocketAddress.INTERNAL_DUMMY_BIND);\n-\n- socket.setBoundEndpoint(AFUNIXSocketAddress.getSocketAddress(fdObj, false, localPort));\n- break;\n- case NativeUnixSocket.SOCKETSTATUS_UNKNOWN:\n- break;\n- default:\n- throw new IllegalStateException(\"Invalid socketStatus response: \" + status);\n- }\n-\n- socket.getAFImpl().setSocketAddress(socket.getLocalSocketAddress());\n- return socket;\n+ return (AFUNIXServerSocket) AFServerSocket.newInstance(AFUNIXServerSocket::new, fdObj,\n+ localPort, remotePort);\n }\n \n /**\n@@ -105,31 +80,25 @@ public class AFUNIXServerSocket extends ServerSocket implements FileDescriptorAc\n * {@link AFUNIXSocketAddress}.\n * \n * @param addr The socket file to bind to.\n- * @return The new, bound {@link AFUNIXServerSocket}.\n+ * @return The new, bound {@link AFServerSocket}.\n * @throws IOException if the operation fails.\n */\n public static AFUNIXServerSocket bindOn(final AFUNIXSocketAddress addr) throws IOException {\n- AFUNIXServerSocket socket = newInstance();\n- socket.bind(addr);\n- return socket;\n+ return (AFUNIXServerSocket) AFServerSocket.bindOn(AFUNIXServerSocket::new, addr);\n }\n \n /**\n- * Returns a new AF_UNIX {@link ServerSocket} that is bound to the given\n- * {@link AFUNIXSocketAddress}.\n+ * Returns a new AF_UNIX {@link ServerSocket} that is bound to the given {@link AFSocketAddress}.\n * \n * @param addr The socket file to bind to.\n * @param deleteOnClose If {@code true}, the socket file (if the address points to a file) will be\n * deleted upon {@link #close}.\n- * @return The new, bound {@link AFUNIXServerSocket}.\n+ * @return The new, bound {@link AFServerSocket}.\n * @throws IOException if the operation fails.\n */\n public static AFUNIXServerSocket bindOn(final AFUNIXSocketAddress addr, boolean deleteOnClose)\n throws IOException {\n- AFUNIXServerSocket socket = newInstance();\n- socket.bind(addr);\n- socket.setDeleteOnClose(deleteOnClose);\n- return socket;\n+ return (AFUNIXServerSocket) AFServerSocket.bindOn(AFUNIXServerSocket::new, addr, deleteOnClose);\n }\n \n /**\n@@ -137,7 +106,7 @@ public class AFUNIXServerSocket extends ServerSocket implements FileDescriptorAc\n * \n * @param path The path to bind to.\n * @param deleteOnClose If {@code true}, the socket file will be deleted upon {@link #close}.\n- * @return The new, bound {@link AFUNIXServerSocket}.\n+ * @return The new, bound {@link AFServerSocket}.\n * @throws IOException if the operation fails.\n */\n public static AFUNIXServerSocket bindOn(final File path, boolean deleteOnClose)\n@@ -150,15 +119,13 @@ public class AFUNIXServerSocket extends ServerSocket implements FileDescriptorAc\n * \n * @param path The path to bind to.\n * @param deleteOnClose If {@code true}, the socket file will be deleted upon {@link #close}.\n- * @return The new, bound {@link AFUNIXServerSocket}.\n+ * @return The new, bound {@link AFServerSocket}.\n * @throws IOException if the operation fails.\n */\n public static AFUNIXServerSocket bindOn(final Path path, boolean deleteOnClose)\n throws IOException {\n- AFUNIXServerSocket socket = newInstance();\n- socket.setDeleteOnClose(deleteOnClose);\n- socket.bind(AFUNIXSocketAddress.of(path));\n- return socket;\n+ return (AFUNIXServerSocket) AFServerSocket.bindOn(AFUNIXServerSocket::new, AFUNIXSocketAddress\n+ .of(path), deleteOnClose);\n }\n \n /**\n@@ -166,222 +133,32 @@ public class AFUNIXServerSocket extends ServerSocket implements FileDescriptorAc\n * address, regardless of any socket address used in a call to bind.\n * \n * @param forceAddr The address to use.\n- * @return The new, yet unbound {@link AFUNIXServerSocket}.\n+ * @return The new, yet unbound {@link AFServerSocket}.\n * @throws IOException if an exception occurs.\n */\n public static AFUNIXServerSocket forceBindOn(final AFUNIXSocketAddress forceAddr)\n throws IOException {\n- return new AFUNIXServerSocket(null) {\n-\n- @Override\n- public void bind(SocketAddress ignored, int backlog) throws IOException {\n- super.bind(forceAddr, backlog);\n- }\n- };\n+ return (AFUNIXServerSocket) AFServerSocket.forceBindOn(AFUNIXServerSocket::new, forceAddr);\n }\n \n @Override\n- public void bind(SocketAddress endpoint, int backlog) throws IOException {\n- if (isClosed()) {\n- throw new SocketException(\"Socket is closed\");\n- }\n- if (isBound()) {\n- throw new SocketException(\"Already bound\");\n- }\n-\n- if (!(endpoint instanceof AFUNIXSocketAddress)) {\n- throw new IllegalArgumentException(\"Can only bind to endpoints of type \"\n- + AFUNIXSocketAddress.class.getName());\n- }\n-\n- getAFImpl().bind(endpoint, getReuseAddress() ? -1 : 0);\n- setBoundEndpoint((AFUNIXSocketAddress) endpoint);\n-\n- if (endpoint == AFUNIXSocketAddress.INTERNAL_DUMMY_BIND) { // NOPMD\n- return;\n- }\n-\n- implementation.listen(backlog);\n- }\n-\n- @Override\n- public boolean isBound() {\n- return boundEndpoint != null;\n- }\n-\n- @Override\n- public boolean isClosed() {\n- return super.isClosed() || (isBound() && !implementation.getFD().valid());\n- }\n-\n- @Override\n- public AFUNIXSocket accept() throws IOException {\n- AFUNIXSocket as = newSocketInstance();\n-\n- boolean success = implementation.accept0(as.getAFImpl(false));\n- if (isClosed()) {\n- // We may have connected to the socket to unblock it\n- throw new SocketException(\"Socket is closed\");\n- }\n- as.getAFImpl(true); // trigger create\n-\n- if (!success) {\n- // non-blocking socket, nothing to accept\n- return null;\n- }\n- as.connect(AFUNIXSocketAddress.INTERNAL_DUMMY_CONNECT);\n- as.getAFImpl().updatePorts(getAFImpl().getLocalPort1(), getAFImpl().getRemotePort());\n-\n- return as;\n+ protected AFUNIXSocketImpl newImpl(FileDescriptor fdObj) throws SocketException {\n+ return new AFUNIXSocketImpl(fdObj);\n }\n \n /**\n- * Returns a new {@link AFUNIXSocket} instance.\n+ * Returns a new {@link AFSocket} instance.\n * \n * @return The new instance.\n * @throws IOException on error.\n */\n+ @Override\n protected AFUNIXSocket newSocketInstance() throws IOException {\n return AFUNIXSocket.newInstance();\n }\n \n @Override\n- public String toString() {\n- return \"AFUNIXServerSocket[\" + (isBound() ? boundEndpoint.toString() : \"unbound\") + \"]\";\n- }\n-\n- @Override\n- public synchronized void close() throws IOException {\n- if (isClosed()) {\n- return;\n- }\n-\n- AFUNIXSocketAddress endpoint = boundEndpoint;\n-\n- IOException superException = null;\n- try {\n- super.close();\n- } catch (IOException e) {\n- superException = e;\n- }\n- if (implementation != null) {\n- try {\n- implementation.close();\n- } catch (IOException e) {\n- if (superException == null) {\n- superException = e;\n- } else {\n- superException.addSuppressed(e);\n- }\n- }\n- }\n-\n- IOException ex = null;\n- try {\n- closeables.close(superException);\n- } finally {\n- if (endpoint != null && endpoint.hasFilename() && isDeleteOnClose()) {\n- File f = endpoint.getFile();\n- if (!f.delete() && f.exists()) {\n- ex = new IOException(\"Could not delete socket file after close: \" + f);\n- }\n- }\n- }\n- if (ex != null) {\n- throw ex;\n- }\n- }\n-\n- /**\n- * Registers a {@link Closeable} that should be closed when this socket is closed.\n- * \n- * @param closeable The closeable.\n- */\n- public void addCloseable(Closeable closeable) {\n- closeables.add(closeable);\n- }\n-\n- /**\n- * Unregisters a previously registered {@link Closeable}.\n- * \n- * @param closeable The closeable.\n- */\n- public void removeCloseable(Closeable closeable) {\n- closeables.remove(closeable);\n- }\n-\n- /**\n- * Checks whether everything is setup to support AF_UNIX sockets.\n- * \n- * @return {@code true} if supported.\n- */\n- public static boolean isSupported() {\n- return NativeUnixSocket.isLoaded();\n- }\n-\n- @Override\n- @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n- public AFUNIXSocketAddress getLocalSocketAddress() {\n- return boundEndpoint;\n- }\n-\n- void setBoundEndpoint(AFUNIXSocketAddress addr) {\n- this.boundEndpoint = addr;\n- getAFImpl().updatePorts(addr.getPort(), -1);\n- }\n-\n- @Override\n- public int getLocalPort() {\n- if (boundEndpoint == null) {\n- return -1;\n- } else {\n- return getAFImpl().getLocalPort1();\n- }\n- }\n-\n- /**\n- * Checks if this {@link AFUNIXServerSocket}'s file should be removed upon {@link #close()}.\n- * \n- * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n- * namespace).\n- * \n- * @return {@code true} if an attempt is made to delete the socket file upon {@link #close()}.\n- */\n- public boolean isDeleteOnClose() {\n- return deleteOnClose.get();\n- }\n-\n- /**\n- * Enables/disables deleting this {@link AFUNIXServerSocket}'s file upon {@link #close()}.\n- * \n- * Deletion is not guaranteed, especially when not supported (e.g., addresses in the abstract\n- * namespace).\n- * \n- * @param b Enabled if {@code true}.\n- */\n- public void setDeleteOnClose(boolean b) {\n- deleteOnClose.set(b);\n- }\n-\n- AFUNIXSocketImpl getAFImpl() {\n- if (created.compareAndSet(false, true)) {\n- try {\n- getSoTimeout(); // trigger create via java.net.Socket\n- } catch (IOException e) {\n- // ignore\n- }\n- }\n- return implementation;\n- }\n-\n- @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n- @Override\n- public AFUNIXServerSocketChannel getChannel() {\n- return channel;\n- }\n-\n- @Override\n- public FileDescriptor getFileDescriptor() throws IOException {\n- return implementation.getFileDescriptor();\n+ public AFUNIXSocket accept() throws IOException {\n+ return (AFUNIXSocket) super.accept();\n }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXServerSocketChannel.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXServerSocketChannel.java\nindex e06aa1758..6cc5005d1 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXServerSocketChannel.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXServerSocketChannel.java\n@@ -17,27 +17,16 @@\n */\n package org.newsclub.net.unix;\n \n-import java.io.FileDescriptor;\n import java.io.IOException;\n-import java.net.SocketAddress;\n-import java.net.SocketOption;\n-import java.nio.channels.ServerSocketChannel;\n-import java.util.Set;\n-\n-import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n /**\n * A selectable channel for stream-oriented listening sockets.\n * \n * @author Christian Kohlschütter\n */\n-public final class AFUNIXServerSocketChannel extends ServerSocketChannel implements\n- FileDescriptorAccess {\n- private final AFUNIXServerSocket afSocket;\n-\n+public final class AFUNIXServerSocketChannel extends AFServerSocketChannel {\n AFUNIXServerSocketChannel(AFUNIXServerSocket socket) {\n- super(AFUNIXSelectorProvider.getInstance());\n- this.afSocket = socket;\n+ super(socket, AFUNIXSelectorProvider.getInstance());\n }\n \n /**\n@@ -47,75 +36,11 @@ public final class AFUNIXServerSocketChannel extends ServerSocketChannel impleme\n * @throws IOException on error.\n */\n public static AFUNIXServerSocketChannel open() throws IOException {\n- return AFUNIXSelectorProvider.provider().openServerSocketChannel();\n- }\n-\n- @SuppressWarnings(\"unchecked\")\n- @Override\n- public T getOption(SocketOption name) throws IOException {\n- Integer optionId = SocketOptionsMapper.resolve(name);\n- if (optionId == null) {\n- throw new UnsupportedOperationException(\"unsupported option\");\n- } else {\n- return (T) afSocket.getAFImpl().getOption(optionId.intValue());\n- }\n- }\n-\n- @Override\n- public AFUNIXServerSocketChannel setOption(SocketOption name, T value) throws IOException {\n- Integer optionId = SocketOptionsMapper.resolve(name);\n- if (optionId == null) {\n- throw new UnsupportedOperationException(\"unsupported option\");\n- } else {\n- afSocket.getAFImpl().setOption(optionId.intValue(), value);\n- }\n- return this;\n- }\n-\n- @Override\n- public Set> supportedOptions() {\n- return SocketOptionsMapper.SUPPORTED_SOCKET_OPTIONS;\n- }\n-\n- @Override\n- public AFUNIXServerSocketChannel bind(SocketAddress local, int backlog) throws IOException {\n- afSocket.bind(local, backlog);\n- return this;\n- }\n-\n- @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n- @Override\n- public AFUNIXServerSocket socket() {\n- return afSocket;\n+ return AFUNIXServerSocket.newInstance().getChannel();\n }\n \n @Override\n public AFUNIXSocketChannel accept() throws IOException {\n- AFUNIXSocket socket = afSocket.accept();\n- return socket == null ? null : socket.getChannel();\n- }\n-\n- @Override\n- public AFUNIXSocketAddress getLocalAddress() throws IOException {\n- return afSocket.getLocalSocketAddress();\n- }\n-\n- @Override\n- protected void implCloseSelectableChannel() throws IOException {\n- afSocket.close();\n- }\n-\n- @Override\n- protected void implConfigureBlocking(boolean block) throws IOException {\n- getAFCore().implConfigureBlocking(block);\n- }\n-\n- AFUNIXSocketCore getAFCore() {\n- return afSocket.getAFImpl().getCore();\n- }\n-\n- @Override\n- public FileDescriptor getFileDescriptor() throws IOException {\n- return afSocket.getFileDescriptor();\n+ return (AFUNIXSocketChannel) super.accept();\n }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocket.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocket.java\nindex 690a82af7..10f545022 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocket.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocket.java\n@@ -17,42 +17,47 @@\n */\n package org.newsclub.net.unix;\n \n-import java.io.Closeable;\n import java.io.FileDescriptor;\n import java.io.IOException;\n import java.net.Socket;\n-import java.net.SocketAddress;\n import java.net.SocketException;\n-import java.util.concurrent.atomic.AtomicBoolean;\n \n-import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+import org.eclipse.jdt.annotation.NonNull;\n \n /**\n * Implementation of an AF_UNIX domain socket.\n * \n * @author Christian Kohlschütter\n */\n-public final class AFUNIXSocket extends Socket implements AFUNIXSomeSocket, AFUNIXSocketExtensions {\n- @SuppressWarnings(\"PMD.MutableStaticState\")\n- static String loadedLibrary; // set by NativeLibraryLoader\n+public final class AFUNIXSocket extends AFSocket implements\n+ AFUNIXSocketExtensions {\n+ private static final Constructor CONSTRUCTOR_STRICT =\n+ new Constructor() {\n \n- private static Integer capabilities = null;\n+ @Override\n+ public @NonNull AFSocket newInstance(FileDescriptor fdObj,\n+ AFSocketFactory factory) throws SocketException {\n+ return new AFUNIXSocket(new AFUNIXSocketImpl(fdObj), factory); // NOPMD\n+ }\n+ };\n \n- private AFUNIXSocketImpl impl;\n-\n- private final AFUNIXSocketFactory socketFactory;\n- private final Closeables closeables = new Closeables();\n- private final AtomicBoolean created = new AtomicBoolean(false);\n- private final AFUNIXSocketChannel channel = new AFUNIXSocketChannel(this);\n+ private AFUNIXSocket(AFSocketImpl impl,\n+ AFSocketFactory factory) throws SocketException {\n+ super(impl, factory);\n+ }\n \n- private AFUNIXSocket(final AFUNIXSocketImpl impl, AFUNIXSocketFactory factory)\n+ AFUNIXSocket(FileDescriptor fd, AFSocketFactory factory)\n throws SocketException {\n- super(impl);\n- this.socketFactory = factory;\n+ this(new AFUNIXSocketImpl.Lenient(fd), factory);\n+ }\n+\n+ @Override\n+ protected AFUNIXSocketChannel newChannel() {\n+ return new AFUNIXSocketChannel(this);\n }\n \n /**\n- * Creates a new, unbound {@link AFUNIXSocket}.\n+ * Creates a new, unbound {@link AFSocket}.\n * \n * This \"default\" implementation is a bit \"lenient\" with respect to the specification.\n * \n@@ -63,54 +68,25 @@ public final class AFUNIXSocket extends Socket implements AFUNIXSomeSocket, AFUN\n * @throws IOException if the operation fails.\n */\n public static AFUNIXSocket newInstance() throws IOException {\n- return newInstance0(null, null);\n+ return (AFUNIXSocket) AFSocket.newInstance(AFUNIXSocket::new, (AFUNIXSocketFactory) null);\n+ }\n+\n+ static AFUNIXSocket newLenientInstance() throws IOException {\n+ return newInstance();\n }\n \n static AFUNIXSocket newInstance(FileDescriptor fdObj, int localPort, int remotePort)\n throws IOException {\n- if (!fdObj.valid()) {\n- throw new SocketException(\"Invalid file descriptor\");\n- }\n- int status = NativeUnixSocket.socketStatus(fdObj);\n- if (status == NativeUnixSocket.SOCKETSTATUS_INVALID) {\n- throw new SocketException(\"Not a valid socket\");\n- }\n-\n- AFUNIXSocket socket = newInstance0(fdObj, (AFUNIXSocketFactory) null);\n- socket.getAFImpl().updatePorts(localPort, remotePort);\n-\n- switch (status) {\n- case NativeUnixSocket.SOCKETSTATUS_CONNECTED:\n- socket.internalDummyConnect();\n- break;\n- case NativeUnixSocket.SOCKETSTATUS_BOUND:\n- socket.internalDummyBind();\n- break;\n- case NativeUnixSocket.SOCKETSTATUS_UNKNOWN:\n- break;\n- default:\n- throw new IllegalStateException(\"Invalid socketStatus response: \" + status);\n- }\n- socket.getAFImpl().setSocketAddress(socket.getLocalSocketAddress());\n-\n- return socket;\n+ return (AFUNIXSocket) AFSocket.newInstance(AFUNIXSocket::new, (AFUNIXSocketFactory) null, fdObj,\n+ localPort, remotePort);\n }\n \n static AFUNIXSocket newInstance(AFUNIXSocketFactory factory) throws SocketException {\n- return newInstance0(null, factory);\n- }\n-\n- private static AFUNIXSocket newInstance0(FileDescriptor fdObj, AFUNIXSocketFactory factory)\n- throws SocketException {\n- final AFUNIXSocketImpl impl = new AFUNIXSocketImpl.Lenient(fdObj);\n- AFUNIXSocket instance = new AFUNIXSocket(impl, factory);\n- instance.impl = impl;\n-\n- return instance;\n+ return (AFUNIXSocket) AFSocket.newInstance(AFUNIXSocket::new, factory);\n }\n \n /**\n- * Creates a new, unbound, \"strict\" {@link AFUNIXSocket}.\n+ * Creates a new, unbound, \"strict\" {@link AFSocket}.\n * \n * This call uses an implementation that tries to be closer to the specification than\n * {@link #newInstance()}, at least for some cases.\n@@ -119,154 +95,23 @@ public final class AFUNIXSocket extends Socket implements AFUNIXSomeSocket, AFUN\n * @throws IOException if the operation fails.\n */\n public static AFUNIXSocket newStrictInstance() throws IOException {\n- final AFUNIXSocketImpl impl = new AFUNIXSocketImpl();\n- AFUNIXSocket instance = new AFUNIXSocket(impl, null);\n- instance.impl = impl;\n- return instance;\n+ return (AFUNIXSocket) AFSocket.newInstance(CONSTRUCTOR_STRICT, (AFUNIXSocketFactory) null);\n }\n \n /**\n- * Creates a new {@link AFUNIXSocket} and connects it to the given {@link AFUNIXSocketAddress}.\n+ * Creates a new {@link AFSocket} and connects it to the given {@link AFUNIXSocketAddress}.\n * \n * @param addr The address to connect to.\n * @return A new, connected socket.\n * @throws IOException if the operation fails.\n */\n public static AFUNIXSocket connectTo(AFUNIXSocketAddress addr) throws IOException {\n- AFUNIXSocket socket = newInstance();\n- socket.connect(addr);\n- return socket;\n- }\n-\n- /**\n- * Not supported, since it's not necessary for client sockets.\n- * \n- * @see AFUNIXServerSocket\n- */\n- @Override\n- public void bind(SocketAddress bindpoint) throws IOException {\n- if (isClosed()) {\n- throw new SocketException(\"Socket is closed\");\n- }\n- if (isBound()) {\n- throw new SocketException(\"Already bound\");\n- }\n- AFUNIXSocketAddress.preprocessSocketAddress(bindpoint, socketFactory);\n- throw new SocketException(\"Use AFUNIXServerSocket#bind or #bindOn\");\n+ return (AFUNIXSocket) AFSocket.connectTo(AFUNIXSocket::new, addr);\n }\n \n @Override\n- public boolean isBound() {\n- return super.isBound() || impl.isBound();\n- }\n-\n- @Override\n- public boolean isConnected() {\n- return super.isConnected() || impl.isConnected();\n- }\n-\n- @Override\n- public void connect(SocketAddress endpoint) throws IOException {\n- connect(endpoint, 0);\n- }\n-\n- @Override\n- public void connect(SocketAddress endpoint, int timeout) throws IOException {\n- connect0(endpoint, timeout);\n- }\n-\n- boolean connect0(SocketAddress endpoint, int timeout) throws IOException {\n- if (endpoint == null) {\n- throw new IllegalArgumentException(\"connect: The address can't be null\");\n- }\n- if (timeout < 0) {\n- throw new IllegalArgumentException(\"connect: timeout can't be negative\");\n- }\n- if (isClosed()) {\n- throw new SocketException(\"Socket is closed\");\n- }\n-\n- AFUNIXSocketAddress address = AFUNIXSocketAddress.preprocessSocketAddress(endpoint,\n- socketFactory);\n-\n- if (!isBound()) {\n- internalDummyBind();\n- }\n-\n- boolean success = getAFImpl().connect0(address, timeout);\n- if (success) {\n- int port = address.getPort();\n- if (port > 0) {\n- getAFImpl().updatePorts(getLocalPort(), port);\n- }\n- }\n- internalDummyConnect();\n- return success;\n- }\n-\n- void internalDummyConnect() throws IOException {\n- if (!isConnected()) {\n- super.connect(AFUNIXSocketAddress.INTERNAL_DUMMY_CONNECT, 0);\n- }\n- }\n-\n- void internalDummyBind() throws IOException {\n- if (!isBound()) {\n- super.bind(AFUNIXSocketAddress.INTERNAL_DUMMY_BIND);\n- }\n- }\n-\n- @Override\n- public String toString() {\n- return getClass().getName() + \"@\" + Integer.toHexString(hashCode()) + toStringSuffix();\n- }\n-\n- String toStringSuffix() {\n- if (impl.getFD().valid()) {\n- return \"[local=\" + getLocalSocketAddress() + \";remote=\" + getRemoteSocketAddress() + \"]\";\n- } else {\n- return \"[invalid]\";\n- }\n- }\n-\n- /**\n- * Returns true iff {@link AFUNIXSocket}s are supported by the current Java VM.\n- * \n- * To support {@link AFUNIXSocket}s, a custom JNI library must be loaded that is supplied with\n- * junixsocket.\n- * \n- * @return {@code true} iff supported.\n- */\n- public static boolean isSupported() {\n- return NativeUnixSocket.isLoaded();\n- }\n-\n- /**\n- * Returns the version of the junixsocket library, as a string, for debugging purposes.\n- * \n- * NOTE: Do not rely on the format of the version identifier, use socket capabilities instead.\n- * \n- * @return String The version identfier, or {@code null} if it could not be determined.\n- * @see #supports(AFUNIXSocketCapability)\n- */\n- public static String getVersion() {\n- try {\n- return NativeLibraryLoader.getJunixsocketVersion();\n- } catch (IOException e) {\n- return null;\n- }\n- }\n-\n- /**\n- * Returns an identifier of the loaded native library, or {@code null} if the library hasn't been\n- * loaded yet.\n- * \n- * The identifier is useful mainly for debugging purposes.\n- * \n- * @return The identifier of the loaded junixsocket-native library, or {@code null}.\n- */\n- public static String getLoadedLibrary() {\n- return loadedLibrary;\n+ public AFUNIXSocketChannel getChannel() {\n+ return (AFUNIXSocketChannel) super.getChannel();\n }\n \n @Override\n@@ -274,37 +119,17 @@ public final class AFUNIXSocket extends Socket implements AFUNIXSomeSocket, AFUN\n if (isClosed() || !isConnected()) {\n throw new SocketException(\"Not connected\");\n }\n- return impl.getPeerCredentials();\n- }\n-\n- @Override\n- public boolean isClosed() {\n- return super.isClosed() || (isConnected() && !impl.getFD().valid());\n- }\n-\n- @Override\n- public int getAncillaryReceiveBufferSize() {\n- return impl.getAncillaryReceiveBufferSize();\n- }\n-\n- @Override\n- public void setAncillaryReceiveBufferSize(int size) {\n- impl.setAncillaryReceiveBufferSize(size);\n- }\n-\n- @Override\n- public void ensureAncillaryReceiveBufferSize(int minSize) {\n- impl.ensureAncillaryReceiveBufferSize(minSize);\n+ return ((AFUNIXSocketImpl) getAFImpl()).getPeerCredentials();\n }\n \n @Override\n public FileDescriptor[] getReceivedFileDescriptors() throws IOException {\n- return impl.getReceivedFileDescriptors();\n+ return ((AFUNIXSocketImpl) getAFImpl()).getReceivedFileDescriptors();\n }\n \n @Override\n public void clearReceivedFileDescriptors() {\n- impl.clearReceivedFileDescriptors();\n+ ((AFUNIXSocketImpl) getAFImpl()).clearReceivedFileDescriptors();\n }\n \n @Override\n@@ -312,63 +137,28 @@ public final class AFUNIXSocket extends Socket implements AFUNIXSomeSocket, AFUN\n if (fdescs != null && fdescs.length > 0 && !isConnected()) {\n throw new SocketException(\"Not connected\");\n }\n- impl.setOutboundFileDescriptors(fdescs);\n+ ((AFUNIXSocketImpl) getAFImpl()).setOutboundFileDescriptors(fdescs);\n }\n \n @Override\n public boolean hasOutboundFileDescriptors() {\n- return impl.hasOutboundFileDescriptors();\n- }\n-\n- private static synchronized int getCapabilities() {\n- if (capabilities == null) {\n- if (!isSupported()) {\n- capabilities = 0;\n- } else {\n- capabilities = NativeUnixSocket.capabilities();\n- }\n- }\n- return capabilities.intValue();\n+ return ((AFUNIXSocketImpl) getAFImpl()).hasOutboundFileDescriptors();\n }\n \n /**\n- * Checks if the current environment (system platform, native library, etc.) supports a given\n- * junixsocket capability.\n+ * Returns true iff {@link AFUNIXSocket}s are supported by the current Java VM.\n * \n- * @param capability The capability.\n- * @return true if supported.\n- */\n- public static boolean supports(AFUNIXSocketCapability capability) {\n- return (getCapabilities() & capability.getBitmask()) != 0;\n- }\n-\n- @Override\n- public synchronized void close() throws IOException {\n- IOException superException = null;\n- try {\n- super.close();\n- } catch (IOException e) {\n- superException = e;\n- }\n- closeables.close(superException);\n- }\n-\n- /**\n- * Registers a {@link Closeable} that should be closed when this socket is closed.\n+ * To support {@link AFSocket}s, a custom JNI library must be loaded that is supplied with\n+ * junixsocket, and the system must support AF_UNIX sockets.\n * \n- * @param closeable The closeable.\n- */\n- public void addCloseable(Closeable closeable) {\n- closeables.add(closeable);\n- }\n-\n- /**\n- * Unregisters a previously registered {@link Closeable}.\n+ * This call is equivalent to checking {@link AFSocket#isSupported()} and\n+ * {@link AFSocket#supports(AFSocketCapability)} with\n+ * {@link AFSocketCapability#CAPABILITY_UNIX_DOMAIN}.\n * \n- * @param closeable The closeable.\n+ * @return {@code true} iff supported.\n */\n- public void removeCloseable(Closeable closeable) {\n- closeables.remove(closeable);\n+ public static boolean isSupported() {\n+ return AFSocket.isSupported() && AFSocket.supports(AFSocketCapability.CAPABILITY_UNIX_DOMAIN);\n }\n \n /**\n@@ -384,52 +174,10 @@ public final class AFUNIXSocket extends Socket implements AFUNIXSomeSocket, AFUN\n System.out.flush();\n System.out.println(AFUNIXSocket.isSupported());\n \n- for (AFUNIXSocketCapability cap : AFUNIXSocketCapability.values()) {\n+ for (AFSocketCapability cap : AFSocketCapability.values()) {\n System.out.print(cap + \": \");\n System.out.flush();\n- System.out.println(AFUNIXSocket.supports(cap));\n- }\n- }\n-\n- AFUNIXSocketImpl getAFImpl() {\n- return getAFImpl(true);\n- }\n-\n- AFUNIXSocketImpl getAFImpl(boolean createSocket) {\n- if (createSocket && created.compareAndSet(false, true)) {\n- try {\n- getSoTimeout(); // trigger create via java.net.Socket\n- } catch (SocketException e) {\n- // ignore\n- }\n- }\n- return impl;\n- }\n-\n- @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n- @Override\n- public AFUNIXSocketChannel getChannel() {\n- return channel;\n- }\n-\n- @Override\n- public synchronized AFUNIXSocketAddress getRemoteSocketAddress() {\n- if (!isConnected()) {\n- return null;\n- }\n- return impl.getRemoteSocketAddress();\n- }\n-\n- @Override\n- public AFUNIXSocketAddress getLocalSocketAddress() {\n- if (isClosed()) {\n- return null;\n+ System.out.println(AFSocket.supports(cap));\n }\n- return impl.getLocalSocketAddress();\n- }\n-\n- @Override\n- public FileDescriptor getFileDescriptor() throws IOException {\n- return impl.getFileDescriptor();\n }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketAddress.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketAddress.java\nindex 34458ef42..29e01b9f2 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketAddress.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketAddress.java\n@@ -18,22 +18,25 @@\n package org.newsclub.net.unix;\n \n import java.io.File;\n-import java.io.FileDescriptor;\n import java.io.FileNotFoundException;\n import java.io.IOException;\n-import java.net.DatagramSocket;\n import java.net.InetAddress;\n import java.net.InetSocketAddress;\n import java.net.SocketAddress;\n import java.net.SocketException;\n+import java.net.URI;\n+import java.net.URISyntaxException;\n import java.nio.ByteBuffer;\n import java.nio.charset.Charset;\n import java.nio.charset.StandardCharsets;\n import java.nio.file.Path;\n-import java.util.HashMap;\n+import java.util.Arrays;\n+import java.util.HashSet;\n import java.util.Locale;\n-import java.util.Map;\n import java.util.Objects;\n+import java.util.Set;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n \n /**\n * Describes an {@link InetSocketAddress} that actually uses AF_UNIX sockets instead of AF_INET.\n@@ -44,123 +47,40 @@ import java.util.Objects;\n * @author Christian Kohlschütter\n */\n @SuppressWarnings(\"PMD.ShortMethodName\")\n-public final class AFUNIXSocketAddress extends InetSocketAddress {\n+public final class AFUNIXSocketAddress extends AFSocketAddress {\n private static final long serialVersionUID = 1L;\n \n- private static final int SOCKADDR_UN_LENGTH = NativeUnixSocket.sockAddrUnLength();\n- private static final Map ADDRESS_CACHE = new HashMap<>();\n private static final Charset ADDRESS_CHARSET = Charset.defaultCharset();\n \n- /**\n- * The native byte-level representation of this address.\n- */\n- private final byte[] bytes;\n-\n- /**\n- * An {@link InetAddress}-wrapped representation of this address. Only created upon demand.\n- */\n- private InetAddress inetAddress = null;\n-\n- static final ThreadLocal SOCKETADDRESS_BUFFER_TL = new ThreadLocal() {\n-\n- @Override\n- protected ByteBuffer initialValue() {\n- return AFUNIXSocketAddress.newSockAddrUnDirectBuffer();\n- }\n- };\n-\n- /**\n- * Just a marker for \"don't actually bind\" (checked with \"==\"). Used in combination with a\n- * superclass' bind method, which should trigger \"setBound()\", etc.\n- */\n- static final AFUNIXSocketAddress INTERNAL_DUMMY_BIND = new AFUNIXSocketAddress(0);\n- static final AFUNIXSocketAddress INTERNAL_DUMMY_CONNECT = new AFUNIXSocketAddress(1);\n- static final AFUNIXSocketAddress INTERNAL_DUMMY_DONT_CONNECT = new AFUNIXSocketAddress(2);\n-\n- /**\n- * Creates a new {@link AFUNIXSocketAddress} that points to the AF_UNIX socket specified by the\n- * given file.\n- * \n- * @param socketFile The socket to connect to.\n- * @throws SocketException if the operation fails.\n- * @deprecated Use {@link AFUNIXSocketAddress#of(File)} instead.\n- */\n- public AFUNIXSocketAddress(final File socketFile) throws SocketException {\n- this(socketFile, 0);\n- }\n+ @SuppressWarnings(\"null\")\n+ static final AFAddressFamily<@NonNull AFUNIXSocketAddress> AF_UNIX = AFAddressFamily\n+ .registerAddressFamily(\"un\", //\n+ AFUNIXSocketAddress.class, new AFSocketAddressConfig() {\n \n- /**\n- * Creates a new {@link AFUNIXSocketAddress} that points to the AF_UNIX socket specified by the\n- * given file, assigning the given port to it.\n- * \n- * @param socketFile The socket to connect to.\n- * @param port The port associated with this socket, or {@code 0} when no port should be assigned.\n- * @throws SocketException if the operation fails.\n- * @deprecated Use {@link AFUNIXSocketAddress#of(File, int)} instead.\n- */\n- public AFUNIXSocketAddress(final File socketFile, int port) throws SocketException {\n- this(socketFile.getPath().getBytes(ADDRESS_CHARSET), port);\n- }\n-\n- /**\n- * Creates a new {@link AFUNIXSocketAddress} that points to the AF_UNIX socket specified by the\n- * given byte sequence.\n- * \n- * NOTE: By specifying a byte array that starts with a zero byte, you indicate that the abstract\n- * namespace is to be used. This feature is not available on all target platforms.\n- * \n- * @param socketAddress The socket address (as bytes).\n- * @throws SocketException if the operation fails.\n- * @see AFUNIXSocketAddress#inAbstractNamespace(String)\n- * @deprecated Use {@link #of(byte[])} instead.\n- */\n- public AFUNIXSocketAddress(final byte[] socketAddress) throws SocketException {\n- this(socketAddress, 0);\n- }\n+ @Override\n+ public AFUNIXSocketAddress parseURI(URI u, int port) throws SocketException {\n+ return AFUNIXSocketAddress.of(u, port);\n+ }\n \n- /**\n- * Creates a new {@link AFUNIXSocketAddress} that points to the AF_UNIX socket specified by the\n- * given byte sequence, assigning the given port to it.\n- * \n- * NOTE: By specifying a byte array that starts with a zero byte, you indicate that the abstract\n- * namespace is to be used. This feature is not available on all target platforms.\n- *\n- * @param socketAddress The socket address (as bytes).\n- * @param port The port associated with this socket, or {@code 0} when no port should be assigned.\n- * @throws SocketException if the operation fails.\n- * @see AFUNIXSocketAddress#inAbstractNamespace(String,int)\n- * @deprecated Use {@link #of(byte[], int)} instead.\n- */\n- public AFUNIXSocketAddress(final byte[] socketAddress, int port) throws SocketException {\n- this(port, socketAddress);\n- }\n-\n- private AFUNIXSocketAddress(int port, final byte[] socketAddress) throws SocketException {\n- /*\n- * Initializing the superclass with an unresolved hostname helps us pass the #equals and\n- * #hashCode checks, which unfortunately are declared final in InetSocketAddress.\n- * \n- * Using a resolved address (with the address bit initialized) would be ideal, but resolved\n- * addresses can only be IPv4 or IPv6 (at least as of Java 16 and earlier).\n- */\n- super(AFUNIXInetAddress.createUnresolvedHostname(socketAddress), 0);\n- if (port < -1) {\n- throw new IllegalArgumentException(\"port out of range\");\n- }\n- if (port > 0) {\n- NativeUnixSocket.setPort1(this, port);\n- }\n+ @Override\n+ protected AFSocketAddressConstructor addressConstructor() {\n+ return AFUNIXSocketAddress::new;\n+ }\n \n- if (socketAddress.length == 0) {\n- throw new SocketException(\"Illegal address length: \" + socketAddress.length);\n- }\n+ @Override\n+ protected String selectorProviderClassname() {\n+ return AFUNIXSelectorProvider.class.getName();\n+ }\n \n- this.bytes = socketAddress.clone();\n- }\n+ @Override\n+ protected Set uriSchemes() {\n+ return new HashSet<>(Arrays.asList(\"unix\", \"http+unix\", \"https+unix\"));\n+ }\n+ });\n \n- private AFUNIXSocketAddress(int port) {\n- super(InetAddress.getLoopbackAddress(), port);\n- this.bytes = new byte[0];\n+ private AFUNIXSocketAddress(int port, final byte[] socketAddress, ByteBuffer nativeAddress)\n+ throws SocketException {\n+ super(port, socketAddress, nativeAddress, AF_UNIX);\n }\n \n /**\n@@ -219,33 +139,7 @@ public final class AFUNIXSocketAddress extends InetSocketAddress {\n */\n public static AFUNIXSocketAddress of(final byte[] socketAddress, int port)\n throws SocketException {\n- AFUNIXSocketAddress instance;\n-\n- if (port == -1) {\n- port = 0;\n- }\n- if (port != 0) {\n- return new AFUNIXSocketAddress(port, socketAddress);\n- }\n-\n- synchronized (AFUNIXSocketAddress.class) {\n- ByteBuffer direct = SOCKETADDRESS_BUFFER_TL.get();\n- NativeUnixSocket.bytesToSockAddrUn(direct, socketAddress);\n-\n- direct.rewind();\n- direct.limit(SOCKADDR_UN_LENGTH);\n-\n- instance = ADDRESS_CACHE.get(direct);\n- if (instance == null) {\n- instance = new AFUNIXSocketAddress(port, socketAddress);\n-\n- ByteBuffer key = newSockAddrUnKeyBuffer();\n- key.put(direct);\n- ADDRESS_CACHE.put(key, instance);\n- }\n- }\n-\n- return instance;\n+ return AFSocketAddress.resolveAddress(socketAddress, port, AF_UNIX);\n }\n \n /**\n@@ -273,6 +167,48 @@ public final class AFUNIXSocketAddress extends InetSocketAddress {\n return of(socketPath.toString().getBytes(ADDRESS_CHARSET), port);\n }\n \n+ /**\n+ * Returns an {@link AFUNIXSocketAddress} for the given URI, if possible.\n+ * \n+ * @param u The URI.\n+ * @return The address.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFUNIXSocketAddress of(URI u) throws SocketException {\n+ return of(u, -1);\n+ }\n+\n+ /**\n+ * Returns an {@link AFUNIXSocketAddress} for the given URI, if possible.\n+ * \n+ * @param u The URI.\n+ * @param overridePort The port to forcibly use, or {@code -1} for \"don't override\".\n+ * @return The address.\n+ * @throws SocketException if the operation fails.\n+ */\n+ public static AFUNIXSocketAddress of(URI u, int overridePort) throws SocketException {\n+ switch (u.getScheme()) {\n+ case \"file\":\n+ case \"unix\":\n+ String path = u.getPath();\n+ if (path == null || path.isEmpty()) {\n+ String auth = u.getAuthority();\n+ if (auth != null && !auth.isEmpty() && u.getRawSchemeSpecificPart().indexOf('@') == -1) {\n+ path = auth;\n+ } else {\n+ throw new SocketException(\"Cannot find UNIX socket path component from URI: \" + u);\n+ }\n+ }\n+ return of(new File(path), overridePort != -1 ? overridePort : u.getPort());\n+ case \"http+unix\":\n+ case \"https+unix\":\n+ HostAndPort hp = HostAndPort.parseFrom(u);\n+ return of(new File(hp.getHostname()), overridePort != -1 ? overridePort : hp.getPort());\n+ default:\n+ throw new SocketException(\"Invalid URI\");\n+ }\n+ }\n+\n /**\n * Returns an {@link AFUNIXSocketAddress} that points to a temporary, non-existent but accessible\n * path in the file system.\n@@ -318,8 +254,7 @@ public final class AFUNIXSocketAddress extends InetSocketAddress {\n * specified.\n */\n public static AFUNIXSocketAddress unwrap(InetAddress address, int port) throws SocketException {\n- Objects.requireNonNull(address);\n- return new AFUNIXSocketAddress(port, AFUNIXInetAddress.unwrapAddress(address));\n+ return AFSocketAddress.unwrap(address, port, AF_UNIX);\n }\n \n /**\n@@ -340,57 +275,18 @@ public final class AFUNIXSocketAddress extends InetSocketAddress {\n }\n \n /**\n- * Returns the plain bytes (as returned by {@link #getBytes()}) of an AF_UNIX socket address.\n+ * Returns an {@link AFUNIXSocketAddress} given a special {@link InetAddress} hostname that\n+ * encodes the byte sequence of an AF_UNIX socket address, like those returned by\n+ * {@link #wrapAddress()}.\n * \n- * @param address The address to unwrap.\n- * @return The address bytes (the length trimmed to the address's length).\n+ * @param hostname The \"special\" hostname, as provided by {@link InetAddress#getHostName()}.\n+ * @param port The port (use 0 for \"none\").\n+ * @return The {@link AFUNIXSocketAddress} instance.\n * @throws SocketException if the operation fails, for example when an unsupported address is\n * specified.\n */\n- static byte[] unwrapAddress(SocketAddress address) throws SocketException {\n- // FIXME: add support for UnixDomainSocketAddress\n- Objects.requireNonNull(address);\n- if (!isSupportedAddress(address)) {\n- throw new SocketException(\"Unsupported address\");\n- }\n- return ((AFUNIXSocketAddress) address).getBytes();\n- }\n-\n- static void unwrapAddressDirectBufferInternal(ByteBuffer socketAddressBuffer,\n- SocketAddress address) throws SocketException {\n- byte[] addr = unwrapAddress(address);\n- NativeUnixSocket.bytesToSockAddrUn(socketAddressBuffer, addr);\n- }\n-\n- static AFUNIXSocketAddress ofInternal(ByteBuffer socketAddressBuffer) throws SocketException {\n- synchronized (AFUNIXSocketAddress.class) {\n- AFUNIXSocketAddress address = ADDRESS_CACHE.get(socketAddressBuffer);\n- if (address != null) {\n- return address;\n- } else {\n- byte[] sockAddrUnToBytes = NativeUnixSocket.sockAddrUnToBytes(socketAddressBuffer);\n- if (sockAddrUnToBytes == null) {\n- return null;\n- } else {\n- return of(sockAddrUnToBytes);\n- }\n- }\n- }\n- }\n-\n- /**\n- * Returns a \"special\" {@link InetAddress} that contains information about this\n- * {@link AFUNIXSocketAddress}.\n- * \n- * IMPORTANT: This {@link InetAddress} does not properly compare (using\n- * {@link InetAddress#equals(Object)} and {@link InetAddress#hashCode()}). It should be used\n- * exclusively to circumvent existing APIs like {@link DatagramSocket} that only accept/return\n- * {@link InetAddress} and not arbitrary {@link SocketAddress} types.\n- * \n- * @return The \"special\" {@link InetAddress}.\n- */\n- public InetAddress wrapAddress() {\n- return AFUNIXInetAddress.wrapAddress(bytes);\n+ public static AFUNIXSocketAddress unwrap(String hostname, int port) throws SocketException {\n+ return AFSocketAddress.unwrap(hostname, port, AF_UNIX);\n }\n \n /**\n@@ -425,11 +321,7 @@ public final class AFUNIXSocketAddress extends InetSocketAddress {\n byte[] bytes = name.getBytes(ADDRESS_CHARSET);\n byte[] addr = new byte[bytes.length + 1];\n System.arraycopy(bytes, 0, addr, 1, bytes.length);\n- return new AFUNIXSocketAddress(addr, port);\n- }\n-\n- byte[] getBytes() {\n- return bytes; // NOPMD\n+ return AFUNIXSocketAddress.of(addr, port);\n }\n \n private static String prettyPrint(byte[] data) {\n@@ -454,7 +346,7 @@ public final class AFUNIXSocketAddress extends InetSocketAddress {\n public String toString() {\n int port = getPort();\n return getClass().getName() + \"[\" + (port == 0 ? \"\" : \"port=\" + port + \";\") + \"path=\"\n- + prettyPrint(bytes) + \"]\";\n+ + prettyPrint(getBytes()) + \"]\";\n }\n \n /**\n@@ -468,6 +360,7 @@ public final class AFUNIXSocketAddress extends InetSocketAddress {\n * @see #getPathAsBytes()\n */\n public String getPath() {\n+ byte[] bytes = getBytes();\n if (bytes.length == 0) {\n return \"\";\n } else if (bytes[0] != 0) {\n@@ -507,7 +400,7 @@ public final class AFUNIXSocketAddress extends InetSocketAddress {\n * @see #getPath()\n */\n public byte[] getPathAsBytes() {\n- return this.bytes.clone();\n+ return getBytes().clone();\n }\n \n /**\n@@ -516,61 +409,27 @@ public final class AFUNIXSocketAddress extends InetSocketAddress {\n * @return {@code true} if the address is in the abstract namespace.\n */\n public boolean isInAbstractNamespace() {\n+ byte[] bytes = getBytes();\n return bytes.length > 0 && bytes[0] == 0;\n }\n \n- /**\n- * Checks if the address can be resolved to a {@link File}.\n- * \n- * @return {@code true} if the address has a filename.\n- */\n+ @Override\n public boolean hasFilename() {\n+ byte[] bytes = getBytes();\n return bytes.length > 0 && bytes[0] != 0;\n }\n \n- /**\n- * Returns the {@link File} corresponding with this address, if possible.\n- * \n- * A {@link FileNotFoundException} is thrown if there is no filename associated with the address,\n- * which applies to addresses in the abstract namespace, for example.\n- * \n- * @return The filename.\n- * @throws FileNotFoundException if the address is not associated with a filename.\n- */\n+ @Override\n public File getFile() throws FileNotFoundException {\n if (isInAbstractNamespace()) {\n throw new FileNotFoundException(\"Socket is in abstract namespace\");\n- } else if (bytes.length == 0) {\n- throw new FileNotFoundException(\"No name\");\n- }\n- return new File(new String(bytes, ADDRESS_CHARSET));\n- }\n-\n- static AFUNIXSocketAddress preprocessSocketAddress(SocketAddress endpoint,\n- AFUNIXSocketFactory socketFactory) throws SocketException {\n- if (!(endpoint instanceof AFUNIXSocketAddress)) {\n- if (socketFactory != null) {\n- if (endpoint instanceof InetSocketAddress) {\n- InetSocketAddress isa = (InetSocketAddress) endpoint;\n-\n- String hostname = isa.getHostString();\n- if (socketFactory.isHostnameSupported(hostname)) {\n- try {\n- endpoint = socketFactory.addressFromHost(hostname, isa.getPort());\n- } catch (SocketException e) {\n- throw e;\n- }\n- }\n- }\n- }\n }\n+ byte[] bytes = getBytes();\n \n- if (!(endpoint instanceof AFUNIXSocketAddress)) {\n- throw new IllegalArgumentException(\"Can only connect to endpoints of type \"\n- + AFUNIXSocketAddress.class.getName() + \", got: \" + endpoint);\n+ if (bytes.length == 0) {\n+ throw new FileNotFoundException(\"No name\");\n }\n-\n- return (AFUNIXSocketAddress) endpoint;\n+ return new File(new String(bytes, ADDRESS_CHARSET));\n }\n \n /**\n@@ -582,7 +441,7 @@ public final class AFUNIXSocketAddress extends InetSocketAddress {\n * @see #unwrap(InetAddress, int)\n */\n public static boolean isSupportedAddress(InetAddress addr) {\n- return AFUNIXInetAddress.isSupportedAddress(addr);\n+ return AFInetAddress.isSupportedAddress(addr, AF_UNIX);\n }\n \n /**\n@@ -596,49 +455,51 @@ public final class AFUNIXSocketAddress extends InetSocketAddress {\n return (addr instanceof AFUNIXSocketAddress);\n }\n \n- static InetAddress getInetAddress(FileDescriptor fdesc, boolean peerName) {\n- if (!fdesc.valid()) {\n- return null;\n- }\n- byte[] addr = NativeUnixSocket.sockname(fdesc, peerName);\n- if (addr == null) {\n- return null;\n- }\n- return AFUNIXInetAddress.wrapAddress(addr);\n- }\n-\n- static AFUNIXSocketAddress getSocketAddress(FileDescriptor fdesc, boolean peerName) {\n- return getSocketAddress(fdesc, peerName, 0);\n+ /**\n+ * Returns the corresponding {@link AFAddressFamily}.\n+ * \n+ * @return The address family instance.\n+ */\n+ @SuppressWarnings(\"null\")\n+ public static AFAddressFamily addressFamily() {\n+ return AFUNIXSelectorProvider.getInstance().addressFamily();\n }\n \n- static AFUNIXSocketAddress getSocketAddress(FileDescriptor fdesc, boolean peerName, int port) {\n- if (!fdesc.valid()) {\n- return null;\n- }\n- byte[] addr = NativeUnixSocket.sockname(fdesc, peerName);\n- if (addr == null) {\n- return null;\n- }\n- try {\n- // FIXME we could infer the \"port\" from the path if the socket factory supports that\n- return AFUNIXSocketAddress.unwrap(AFUNIXInetAddress.wrapAddress(addr), port);\n- } catch (SocketException e) {\n- throw new IllegalStateException(e);\n+ @Override\n+ public URI toURI(String scheme, URI template) throws IOException {\n+ switch (scheme) {\n+ case \"unix\":\n+ case \"file\":\n+ try {\n+ if (getPort() > 0 && !\"file\".equals(scheme)) {\n+ return new URI(scheme, null, \"localhost\", getPort(), getPath(), null, (String) null);\n+ } else {\n+ return new URI(scheme, null, null, -1, getPath(), null, null);\n+ }\n+ } catch (URISyntaxException e) {\n+ throw new IOException(e);\n+ }\n+ case \"http+unix\":\n+ case \"https+unix\":\n+ HostAndPort hp = new HostAndPort(getPath(), getPort());\n+ return hp.toURI(scheme, template);\n+ default:\n+ return super.toURI(scheme, template);\n }\n }\n \n- static ByteBuffer newSockAddrUnDirectBuffer() {\n- return ByteBuffer.allocateDirect(SOCKADDR_UN_LENGTH);\n+ @Override\n+ public AFUNIXSocket newConnectedSocket() throws IOException {\n+ return (AFUNIXSocket) super.newConnectedSocket();\n }\n \n- static ByteBuffer newSockAddrUnKeyBuffer() {\n- return ByteBuffer.allocate(SOCKADDR_UN_LENGTH);\n+ @Override\n+ public AFUNIXServerSocket newBoundServerSocket() throws IOException {\n+ return (AFUNIXServerSocket) super.newBoundServerSocket();\n }\n \n- synchronized InetAddress getInetAddress() {\n- if (inetAddress == null) {\n- inetAddress = AFUNIXInetAddress.wrapAddress(bytes);\n- }\n- return inetAddress;\n+ @Override\n+ public AFUNIXServerSocket newForceBoundServerSocket() throws IOException {\n+ return (AFUNIXServerSocket) super.newForceBoundServerSocket();\n }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketCapability.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketCapability.java\nindex 579b96131..aaf45f555 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketCapability.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketCapability.java\n@@ -23,18 +23,23 @@ package org.newsclub.net.unix;\n * \n * You can check whether your environment supports a given capability by calling\n * {@link AFUNIXSocket#supports(AFUNIXSocketCapability)}.\n+ * \n+ * This enum is deprecated. Use {@link AFSocketCapability} instead.\n+ * \n+ * @see AFSocketCapability\n */\n+@Deprecated\n public enum AFUNIXSocketCapability {\n // see org_newsclub_net_unix_NativeUnixSocket.c in junixsocket-native\n \n /** Socket supports retrieving peer credentials. */\n- CAPABILITY_PEER_CREDENTIALS(0), //\n+ CAPABILITY_PEER_CREDENTIALS(0),\n \n /** Socket supports sending and receiving ancillary messages. */\n- CAPABILITY_ANCILLARY_MESSAGES(1), //\n+ CAPABILITY_ANCILLARY_MESSAGES(1),\n \n /** Socket supports passing file descriptors via ancillary messages. */\n- CAPABILITY_FILE_DESCRIPTORS(2), //\n+ CAPABILITY_FILE_DESCRIPTORS(2),\n \n /** Socket addressing supports the abstract namespace (Linux). */\n CAPABILITY_ABSTRACT_NAMESPACE(3),\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketChannel.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketChannel.java\nindex 1fb638b6f..0ce374ae9 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketChannel.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketChannel.java\n@@ -21,27 +21,16 @@ import java.io.FileDescriptor;\n import java.io.IOException;\n import java.net.SocketAddress;\n import java.net.SocketException;\n-import java.net.SocketOption;\n-import java.nio.ByteBuffer;\n-import java.nio.channels.SocketChannel;\n-import java.util.Set;\n-import java.util.concurrent.atomic.AtomicBoolean;\n-\n-import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n /**\n * A selectable channel for stream-oriented connecting sockets.\n * \n * @author Christian Kohlschütter\n */\n-public final class AFUNIXSocketChannel extends SocketChannel implements AFUNIXSomeSocket,\n+public final class AFUNIXSocketChannel extends AFSocketChannel implements\n AFUNIXSocketExtensions {\n- private final AFUNIXSocket afSocket;\n- private final AtomicBoolean connectPending = new AtomicBoolean(false);\n-\n AFUNIXSocketChannel(AFUNIXSocket socket) {\n- super(AFUNIXSelectorProvider.getInstance());\n- this.afSocket = socket;\n+ super(socket, AFUNIXSelectorProvider.getInstance());\n }\n \n /**\n@@ -51,7 +40,7 @@ public final class AFUNIXSocketChannel extends SocketChannel implements AFUNIXSo\n * @throws IOException on error.\n */\n public static AFUNIXSocketChannel open() throws IOException {\n- return AFUNIXSelectorProvider.provider().openSocketChannel();\n+ return (AFUNIXSocketChannel) AFSocketChannel.open(AFUNIXSocket::newLenientInstance);\n }\n \n /**\n@@ -62,168 +51,17 @@ public final class AFUNIXSocketChannel extends SocketChannel implements AFUNIXSo\n * @throws IOException on error.\n */\n public static AFUNIXSocketChannel open(SocketAddress remote) throws IOException {\n- @SuppressWarnings(\"resource\")\n- AFUNIXSocketChannel sc = open();\n- try {\n- sc.connect(remote);\n- } catch (Throwable x) { // NOPMD\n- try {\n- sc.close();\n- } catch (Throwable suppressed) { // NOPMD\n- x.addSuppressed(suppressed);\n- }\n- throw x;\n- }\n- assert sc.isConnected();\n- return sc;\n- }\n-\n- @SuppressWarnings(\"unchecked\")\n- @Override\n- public T getOption(SocketOption name) throws IOException {\n- Integer optionId = SocketOptionsMapper.resolve(name);\n- if (optionId == null) {\n- throw new UnsupportedOperationException(\"unsupported option\");\n- } else {\n- return (T) afSocket.getAFImpl().getOption(optionId.intValue());\n- }\n- }\n-\n- @Override\n- public AFUNIXSocketChannel setOption(SocketOption name, T value) throws IOException {\n- Integer optionId = SocketOptionsMapper.resolve(name);\n- if (optionId == null) {\n- throw new UnsupportedOperationException(\"unsupported option\");\n- } else {\n- afSocket.getAFImpl().setOption(optionId.intValue(), value);\n- }\n- return this;\n- }\n-\n- @Override\n- public Set> supportedOptions() {\n- return SocketOptionsMapper.SUPPORTED_SOCKET_OPTIONS;\n- }\n-\n- @Override\n- public AFUNIXSocketChannel bind(SocketAddress local) throws IOException {\n- afSocket.bind(local);\n- return this;\n- }\n-\n- @Override\n- public AFUNIXSocketChannel shutdownInput() throws IOException {\n- afSocket.getAFImpl().shutdownInput();\n- return this;\n- }\n-\n- @Override\n- public AFUNIXSocketChannel shutdownOutput() throws IOException {\n- afSocket.getAFImpl().shutdownOutput();\n- return this;\n- }\n-\n- @Override\n- @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n- public AFUNIXSocket socket() {\n- return afSocket;\n- }\n-\n- @Override\n- public boolean isConnected() {\n- boolean connected = afSocket.isConnected();\n- if (connected) {\n- connectPending.set(false);\n- }\n- return connected;\n- }\n-\n- @Override\n- public boolean isConnectionPending() {\n- return connectPending.get();\n- }\n-\n- @Override\n- public boolean connect(SocketAddress remote) throws IOException {\n- boolean connected = afSocket.connect0(remote, 0);\n- if (!connected) {\n- connectPending.set(true);\n- }\n- return connected;\n- }\n-\n- @Override\n- public boolean finishConnect() throws IOException {\n- if (isConnected()) {\n- return true;\n- } else if (!isConnectionPending()) {\n- return false;\n- }\n-\n- boolean connected = NativeUnixSocket.finishConnect(afSocket.getFileDescriptor())\n- || isConnected();\n- if (connected) {\n- connectPending.set(false);\n- }\n- return connected;\n- }\n-\n- @Override\n- public AFUNIXSocketAddress getRemoteAddress() throws IOException {\n- return afSocket.getRemoteSocketAddress();\n- }\n-\n- @Override\n- public int read(ByteBuffer dst) throws IOException {\n- return afSocket.getAFImpl().read(dst, null);\n- }\n-\n- @Override\n- public long read(ByteBuffer[] dsts, int offset, int length) throws IOException {\n- if (length == 0) {\n- return 0;\n- }\n- // FIXME support more than one buffer for scatter-gather access\n- return read(dsts[offset]);\n- }\n-\n- @Override\n- public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {\n- if (length == 0) {\n- return 0;\n- }\n- // FIXME support more than one buffer for scatter-gather access\n- return write(srcs[offset]);\n- }\n-\n- @Override\n- public int write(ByteBuffer src) throws IOException {\n- return afSocket.getAFImpl().write(src);\n- }\n-\n- @Override\n- public AFUNIXSocketAddress getLocalAddress() throws IOException {\n- return afSocket.getLocalSocketAddress();\n- }\n-\n- @Override\n- protected void implCloseSelectableChannel() throws IOException {\n- afSocket.close();\n- }\n-\n- @Override\n- protected void implConfigureBlocking(boolean block) throws IOException {\n- getAFCore().implConfigureBlocking(block);\n+ return (AFUNIXSocketChannel) AFSocketChannel.open(AFUNIXSocket::newLenientInstance, remote);\n }\n \n @Override\n public FileDescriptor[] getReceivedFileDescriptors() throws IOException {\n- return afSocket.getReceivedFileDescriptors();\n+ return ((AFUNIXSocketExtensions) getAFSocket()).getReceivedFileDescriptors();\n }\n \n @Override\n public void clearReceivedFileDescriptors() {\n- afSocket.clearReceivedFileDescriptors();\n+ ((AFUNIXSocketExtensions) getAFSocket()).clearReceivedFileDescriptors();\n }\n \n @Override\n@@ -231,46 +69,16 @@ public final class AFUNIXSocketChannel extends SocketChannel implements AFUNIXSo\n if (fdescs != null && fdescs.length > 0 && !isConnected()) {\n throw new SocketException(\"Not connected\");\n }\n- afSocket.setOutboundFileDescriptors(fdescs);\n+ ((AFUNIXSocketExtensions) getAFSocket()).setOutboundFileDescriptors(fdescs);\n }\n \n @Override\n public boolean hasOutboundFileDescriptors() {\n- return afSocket.hasOutboundFileDescriptors();\n+ return ((AFUNIXSocketExtensions) getAFSocket()).hasOutboundFileDescriptors();\n }\n \n @Override\n public AFUNIXSocketCredentials getPeerCredentials() throws IOException {\n- return afSocket.getPeerCredentials();\n- }\n-\n- @Override\n- public int getAncillaryReceiveBufferSize() {\n- return afSocket.getAncillaryReceiveBufferSize();\n+ return ((AFUNIXSocketExtensions) getAFSocket()).getPeerCredentials();\n }\n-\n- @Override\n- public void setAncillaryReceiveBufferSize(int size) {\n- afSocket.setAncillaryReceiveBufferSize(size);\n- }\n-\n- @Override\n- public void ensureAncillaryReceiveBufferSize(int minSize) {\n- afSocket.ensureAncillaryReceiveBufferSize(minSize);\n- }\n-\n- AFUNIXSocketCore getAFCore() {\n- return afSocket.getAFImpl().getCore();\n- }\n-\n- @Override\n- public FileDescriptor getFileDescriptor() throws IOException {\n- return afSocket.getFileDescriptor();\n- }\n-\n- @Override\n- public String toString() {\n- return super.toString() + afSocket.toStringSuffix();\n- }\n-\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketCore.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketCore.java\ndeleted file mode 100644\nindex e1988181b..000000000\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketCore.java\n+++ /dev/null\n@@ -1,85 +0,0 @@\n-/*\n- * junixsocket\n- *\n- * Copyright 2009-2021 Christian Kohlschütter\n- *\n- * Licensed under the Apache License, Version 2.0 (the \"License\");\n- * you may not use this file except in compliance with the License.\n- * You may obtain a copy of the License at\n- *\n- * http://www.apache.org/licenses/LICENSE-2.0\n- *\n- * Unless required by applicable law or agreed to in writing, software\n- * distributed under the License is distributed on an \"AS IS\" BASIS,\n- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- * See the License for the specific language governing permissions and\n- * limitations under the License.\n- */\n-package org.newsclub.net.unix;\n-\n-import java.io.FileDescriptor;\n-import java.io.IOException;\n-import java.nio.ByteBuffer;\n-import java.util.concurrent.atomic.AtomicLong;\n-\n-/**\n- * A shared core that is common for all AFUNIX sockets (datagrams, streams).\n- * \n- * @author Christian Kohlschütter\n- */\n-class AFUNIXSocketCore extends AFUNIXCore {\n- private static final int SHUT_RD_WR = 2;\n-\n- /**\n- * We keep track of the server's inode to detect when another server connects to our address.\n- */\n- protected final AtomicLong inode = new AtomicLong(-1);\n-\n- protected AFUNIXSocketAddress socketAddress;\n-\n- protected AFUNIXSocketCore(Object observed, FileDescriptor fd,\n- AncillaryDataSupport ancillaryDataSupport) {\n- super(observed, fd, ancillaryDataSupport);\n- }\n-\n- @Override\n- protected void doClose() throws IOException {\n- NativeUnixSocket.shutdown(fd, SHUT_RD_WR);\n- unblockAccepts();\n-\n- super.doClose();\n- }\n-\n- protected void unblockAccepts() {\n- }\n-\n- AFUNIXSocketAddress receive(ByteBuffer dst) throws IOException {\n- ByteBuffer socketAddressBuffer = AFUNIXSocketAddress.SOCKETADDRESS_BUFFER_TL.get();\n- int read = read(dst, socketAddressBuffer, 0);\n- if (read > 0) {\n- return AFUNIXSocketAddress.ofInternal(socketAddressBuffer);\n- } else {\n- return null;\n- }\n- }\n-\n- boolean isConnected(boolean boundOk) {\n- try {\n- if (fd.valid()) {\n- switch (NativeUnixSocket.socketStatus(fd)) {\n- case NativeUnixSocket.SOCKETSTATUS_CONNECTED:\n- return true;\n- case NativeUnixSocket.SOCKETSTATUS_BOUND:\n- if (boundOk) {\n- return true;\n- }\n- break;\n- default:\n- }\n- }\n- } catch (IOException e) {\n- throw new IllegalStateException(e);\n- }\n- return false;\n- }\n-}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketExtensions.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketExtensions.java\nindex 1db9cf074..2c3601dd4 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketExtensions.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketExtensions.java\n@@ -33,30 +33,7 @@ import java.io.InputStream;\n * \n * @author Christian Kohlschütter\n */\n-public interface AFUNIXSocketExtensions {\n- /**\n- * Returns the size of the receive buffer for ancillary messages (in bytes).\n- * \n- * @return The size.\n- */\n- int getAncillaryReceiveBufferSize();\n-\n- /**\n- * Sets the size of the receive buffer for ancillary messages (in bytes).\n- * \n- * To disable handling ancillary messages, set it to 0 (default).\n- * \n- * @param size The size.\n- */\n- void setAncillaryReceiveBufferSize(int size);\n-\n- /**\n- * Ensures a minimum ancillary receive buffer size.\n- * \n- * @param minSize The minimum size (in bytes).\n- */\n- void ensureAncillaryReceiveBufferSize(int minSize);\n-\n+public interface AFUNIXSocketExtensions extends AFSocketExtensions {\n /**\n * Retrieves an array of incoming {@link FileDescriptor}s that were sent as ancillary messages,\n * along with a call to {@link InputStream#read()}, etc.\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketFactory.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketFactory.java\nindex fea7edf0c..5667f5cfc 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketFactory.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketFactory.java\n@@ -19,7 +19,6 @@ package org.newsclub.net.unix;\n \n import java.io.File;\n import java.io.IOException;\n-import java.net.InetAddress;\n import java.net.Socket;\n import java.net.SocketException;\n import java.net.URLDecoder;\n@@ -33,48 +32,16 @@ import javax.net.SocketFactory;\n * Typically, the \"hostname\" is used as a reference to a socketFile on the file system. The actual\n * mapping is left to the implementor.\n * \n- * Three default implementations are provided.\n- * \n * @see AFUNIXSocketFactory.FactoryArg\n * @see AFUNIXSocketFactory.SystemProperty\n * @see AFUNIXSocketFactory.URIScheme\n */\n-public abstract class AFUNIXSocketFactory extends SocketFactory {\n- /**\n- * Translates a \"host\" string (and port) to an {@link AFUNIXSocketAddress}.\n- * \n- * @param host The hostname\n- * @param port The port, or 0.\n- * @return The {@link AFUNIXSocketAddress}\n- * @throws SocketException If there was a problem converting the hostname\n- * @throws NullPointerException If host was {@code null}.\n- */\n- protected abstract AFUNIXSocketAddress addressFromHost(String host, int port)\n- throws SocketException;\n-\n- /**\n- * Checks whether the given hostname is supported by this socket factory. If not, calls to\n- * createSocket will cause a {@link SocketException}.\n- * \n- * @param host The host to check.\n- * @return {@code true} if supported.\n- */\n- protected boolean isHostnameSupported(String host) {\n- return host != null;\n- }\n-\n+public abstract class AFUNIXSocketFactory extends AFSocketFactory {\n /**\n- * Checks whether the given {@link InetAddress} is supported by this socket factory. If not, calls\n- * to createSocket will cause a {@link SocketException}.\n- * \n- * By default, this only checks the hostname part of the address via\n- * {@link #isHostnameSupported(String)}.\n- * \n- * @param address The address to check.\n- * @return {@code true} if supported.\n+ * Creates a {@link AFUNIXSocketFactory}.\n */\n- protected boolean isInetAddressSupported(InetAddress address) {\n- return address != null && isHostnameSupported(address.getHostName());\n+ protected AFUNIXSocketFactory() {\n+ super();\n }\n \n @Override\n@@ -83,54 +50,8 @@ public abstract class AFUNIXSocketFactory extends SocketFactory {\n }\n \n @Override\n- public Socket createSocket(String host, int port) throws IOException {\n- if (!isHostnameSupported(host)) {\n- throw new SocketException(\"Unsupported hostname\");\n- }\n- if (port < 0) {\n- throw new IllegalArgumentException(\"Illegal port\");\n- }\n-\n- AFUNIXSocketAddress socketAddress = addressFromHost(host, port);\n- return AFUNIXSocket.connectTo(socketAddress);\n- }\n-\n- @Override\n- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)\n- throws IOException {\n- if (!isHostnameSupported(host)) {\n- throw new SocketException(\"Unsupported hostname\");\n- }\n- if (localPort < 0) {\n- throw new IllegalArgumentException(\"Illegal local port\");\n- }\n- // NOTE: we simply ignore localHost and localPort\n- return createSocket(host, port);\n- }\n-\n- @Override\n- public Socket createSocket(InetAddress address, int port) throws IOException {\n- if (!isInetAddressSupported(address)) {\n- throw new SocketException(\"Unsupported address\");\n- }\n- String hostname = address.getHostName();\n- if (!isHostnameSupported(hostname)) {\n- throw new SocketException(\"Unsupported hostname\");\n- }\n- return createSocket(hostname, port);\n- }\n-\n- @Override\n- public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)\n- throws IOException {\n- if (!isInetAddressSupported(address)) {\n- throw new SocketException(\"Unsupported address\");\n- }\n- if (localPort < 0) {\n- throw new IllegalArgumentException(\"Illegal local port\");\n- }\n- // NOTE: we simply ignore localAddress and localPort\n- return createSocket(address, port);\n+ protected AFUNIXSocket connectTo(AFUNIXSocketAddress addr) throws IOException {\n+ return AFUNIXSocket.connectTo(addr);\n }\n \n /**\n@@ -141,8 +62,15 @@ public abstract class AFUNIXSocketFactory extends SocketFactory {\n private abstract static class DefaultSocketHostnameSocketFactory extends AFUNIXSocketFactory {\n private static final String PROP_SOCKET_HOSTNAME = \"org.newsclub.net.unix.socket.hostname\";\n \n+ /**\n+ * Creates a {@link DefaultSocketHostnameSocketFactory}.\n+ */\n+ public DefaultSocketHostnameSocketFactory() {\n+ super();\n+ }\n+\n @Override\n- protected final boolean isHostnameSupported(String host) {\n+ public final boolean isHostnameSupported(String host) {\n return getDefaultSocketHostname().equals(host);\n }\n \n@@ -189,7 +117,7 @@ public abstract class AFUNIXSocketFactory extends SocketFactory {\n }\n \n @Override\n- protected AFUNIXSocketAddress addressFromHost(String host, int port) throws SocketException {\n+ public AFUNIXSocketAddress addressFromHost(String host, int port) throws SocketException {\n return AFUNIXSocketAddress.of(socketFile, port);\n }\n }\n@@ -208,8 +136,15 @@ public abstract class AFUNIXSocketFactory extends SocketFactory {\n public static final class SystemProperty extends DefaultSocketHostnameSocketFactory {\n private static final String PROP_SOCKET_DEFAULT = \"org.newsclub.net.unix.socket.default\";\n \n+ /**\n+ * Creates a {@link SystemProperty} socket factory.\n+ */\n+ public SystemProperty() {\n+ super();\n+ }\n+\n @Override\n- protected AFUNIXSocketAddress addressFromHost(String host, int port) throws SocketException {\n+ public AFUNIXSocketAddress addressFromHost(String host, int port) throws SocketException {\n String path = System.getProperty(PROP_SOCKET_DEFAULT);\n if (path == null || path.isEmpty()) {\n throw new IllegalStateException(\"Property not configured: \" + PROP_SOCKET_DEFAULT);\n@@ -237,6 +172,13 @@ public abstract class AFUNIXSocketFactory extends SocketFactory {\n private static final String FILE_SCHEME_PREFIX_ENCODED = \"file%\";\n private static final String FILE_SCHEME_LOCALHOST = \"localhost\";\n \n+ /**\n+ * Creates a {@link URIScheme} socket factory.\n+ */\n+ public URIScheme() {\n+ super();\n+ }\n+\n private static String stripBrackets(String host) {\n if (host.startsWith(\"[\")) {\n if (host.endsWith(\"]\")) {\n@@ -249,13 +191,13 @@ public abstract class AFUNIXSocketFactory extends SocketFactory {\n }\n \n @Override\n- protected boolean isHostnameSupported(String host) {\n+ public boolean isHostnameSupported(String host) {\n host = stripBrackets(host);\n return host.startsWith(FILE_SCHEME_PREFIX) || host.startsWith(FILE_SCHEME_PREFIX_ENCODED);\n }\n \n @Override\n- protected AFUNIXSocketAddress addressFromHost(String host, int port) throws SocketException {\n+ public AFUNIXSocketAddress addressFromHost(String host, int port) throws SocketException {\n host = stripBrackets(host);\n if (host.startsWith(FILE_SCHEME_PREFIX_ENCODED)) {\n try {\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketImpl.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketImpl.java\nindex b623d73c7..804bc8e32 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketImpl.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketImpl.java\n@@ -19,658 +19,12 @@ package org.newsclub.net.unix;\n \n import java.io.FileDescriptor;\n import java.io.IOException;\n-import java.io.InputStream;\n-import java.io.InterruptedIOException;\n-import java.io.OutputStream;\n-import java.net.InetAddress;\n import java.net.Socket;\n-import java.net.SocketAddress;\n import java.net.SocketException;\n-import java.net.SocketImpl;\n-import java.net.SocketOptions;\n-import java.nio.ByteBuffer;\n-import java.util.concurrent.atomic.AtomicBoolean;\n-import java.util.concurrent.atomic.AtomicInteger;\n-\n-/**\n- * The Java-part of the {@link AFUNIXSocket} implementation.\n- * \n- * @author Christian Kohlschütter\n- */\n-@SuppressWarnings({\"PMD.CyclomaticComplexity\"})\n-class AFUNIXSocketImpl extends SocketImplShim {\n- private static final int SHUT_RD = 0;\n- private static final int SHUT_WR = 1;\n- private static final int SHUT_RD_WR = 2;\n-\n- private final AFUNIXSocketStreamCore core;\n- final AncillaryDataSupport ancillaryDataSupport = new AncillaryDataSupport();\n-\n- private final AtomicBoolean bound = new AtomicBoolean(false);\n- private Boolean createType = null;\n- private final AtomicBoolean connected = new AtomicBoolean(false);\n-\n- private volatile boolean closedInputStream = false;\n- private volatile boolean closedOutputStream = false;\n-\n- private final AFUNIXInputStream in = newInputStream();\n- private final AFUNIXOutputStream out = newOutputStream();\n-\n- private boolean reuseAddr = true;\n-\n- private final AtomicInteger socketTimeout = new AtomicInteger(0);\n-\n- /**\n- * When the {@link AFUNIXSocketImpl} becomes unreachable (but not yet closed), we must ensure that\n- * the underlying socket and all related file descriptors are closed.\n- *\n- * @author Christian Kohlschütter\n- */\n- private static class AFUNIXSocketStreamCore extends AFUNIXSocketCore {\n- private final AtomicInteger pendingAccepts = new AtomicInteger(0);\n-\n- AFUNIXSocketStreamCore(AFUNIXSocketImpl observed, FileDescriptor fd,\n- AncillaryDataSupport ancillaryDataSupport) {\n- super(observed, fd, ancillaryDataSupport);\n- }\n-\n- private void incPendingAccepts() throws SocketException {\n- if (pendingAccepts.incrementAndGet() >= Integer.MAX_VALUE) {\n- throw new SocketException(\"Too many pending accepts\");\n- }\n- }\n-\n- private void decPendingAccepts() throws SocketException {\n- pendingAccepts.decrementAndGet();\n- }\n-\n- /**\n- * Unblock other threads that are currently waiting on accept, simply by connecting to the\n- * socket.\n- */\n- @Override\n- protected void unblockAccepts() {\n- if (socketAddress == null || socketAddress.getBytes() == null || inode.get() < 0) {\n- return;\n- }\n-\n- while (pendingAccepts.get() > 0) {\n- try {\n- FileDescriptor tmpFd = new FileDescriptor();\n-\n- try {\n- NativeUnixSocket.createSocket(tmpFd, NativeUnixSocket.SOCK_STREAM);\n- NativeUnixSocket.connect(socketAddress.getBytes(), tmpFd, inode.get());\n- } catch (IOException e) {\n- // there's nothing more we can do to unlock these accepts\n- // (e.g., SocketException: No such file or directory)\n- return;\n- }\n- try {\n- NativeUnixSocket.shutdown(tmpFd, SHUT_RD_WR);\n- } catch (Exception e) {\n- // ignore\n- }\n- try {\n- NativeUnixSocket.close(tmpFd);\n- } catch (Exception e) {\n- // ignore\n- }\n- } catch (Exception e) {\n- // ignore\n- }\n- }\n- }\n- }\n-\n- protected AFUNIXSocketImpl() throws SocketException {\n- this((FileDescriptor) null);\n- }\n \n+class AFUNIXSocketImpl extends AFSocketImpl {\n protected AFUNIXSocketImpl(FileDescriptor fdObj) throws SocketException {\n- super();\n- this.address = InetAddress.getLoopbackAddress();\n- this.core = new AFUNIXSocketStreamCore(this, fdObj, ancillaryDataSupport);\n- this.fd = core.fd;\n- }\n-\n- protected AFUNIXInputStream newInputStream() {\n- return new AFUNIXInputStream();\n- }\n-\n- protected AFUNIXOutputStream newOutputStream() {\n- return new AFUNIXOutputStream();\n- }\n-\n- FileDescriptor getFD() {\n- return fd;\n- }\n-\n- boolean isConnected() {\n- if (connected.get()) {\n- return true;\n- }\n- if (isClosed()) {\n- return false;\n- }\n- if (core.isConnected(false)) {\n- connected.set(true);\n- return true;\n- }\n- return false;\n- }\n-\n- boolean isBound() {\n- if (bound.get()) {\n- return true;\n- }\n- if (isClosed()) {\n- return false;\n- }\n- if (core.isConnected(true)) {\n- bound.set(true);\n- return true;\n- }\n- return false;\n- }\n-\n- AFUNIXSocketCore getCore() {\n- return core;\n- }\n-\n- private boolean isClosed() {\n- return core.isClosed();\n- }\n-\n- @Override\n- protected void accept(SocketImpl socket) throws IOException {\n- accept0(socket);\n- }\n-\n- protected boolean accept0(SocketImpl socket) throws IOException {\n- FileDescriptor fdesc = core.validFdOrException();\n- if (isClosed()) {\n- throw new SocketException(\"Socket is closed\");\n- } else if (!isBound()) {\n- throw new SocketException(\"Socket is not bound\");\n- }\n-\n- AFUNIXSocketAddress socketAddress = core.socketAddress;\n-\n- final AFUNIXSocketImpl si = (AFUNIXSocketImpl) socket;\n- try {\n- core.incPendingAccepts();\n- if (!NativeUnixSocket.accept(socketAddress.getBytes(), fdesc, si.fd, core.inode.get(),\n- socketTimeout.get())) {\n- return false;\n- }\n-\n- if (!isBound() || isClosed()) {\n- try {\n- NativeUnixSocket.shutdown(si.fd, SHUT_RD_WR);\n- } catch (Exception e) {\n- // ignore\n- }\n- try {\n- NativeUnixSocket.close(si.fd);\n- } catch (Exception e) {\n- // ignore\n- }\n- throw new SocketException(\"Socket is closed\");\n- }\n- } finally {\n- core.decPendingAccepts();\n- }\n- si.setSocketAddress(socketAddress);\n- si.connected.set(true);\n-\n- return true;\n- }\n-\n- void setSocketAddress(AFUNIXSocketAddress socketAddress) {\n- if (socketAddress == null) {\n- this.core.socketAddress = null;\n- this.address = null;\n- this.localport = -1;\n- } else {\n- this.core.socketAddress = socketAddress;\n- this.address = socketAddress.getAddress();\n- if (this.localport <= 0) {\n- this.localport = socketAddress.getPort();\n- }\n- }\n- }\n-\n- @Override\n- protected int available() throws IOException {\n- FileDescriptor fdesc = core.validFdOrException();\n- return NativeUnixSocket.available(fdesc);\n- }\n-\n- protected void bind(SocketAddress addr, int options) throws IOException {\n- if (addr == null) {\n- throw new IllegalArgumentException(\"Cannot bind to null address\");\n- }\n- if (!(addr instanceof AFUNIXSocketAddress)) {\n- throw new SocketException(\"Cannot bind to this type of address: \" + addr.getClass());\n- }\n-\n- bound.set(true);\n-\n- if (addr == AFUNIXSocketAddress.INTERNAL_DUMMY_BIND) { // NOPMD\n- core.inode.set(0);\n- return;\n- }\n-\n- AFUNIXSocketAddress socketAddress = (AFUNIXSocketAddress) addr;\n-\n- this.setSocketAddress(socketAddress);\n- core.inode.set(NativeUnixSocket.bind(socketAddress.getBytes(), fd, options));\n- core.validFdOrException();\n- }\n-\n- @Override\n- @SuppressWarnings(\"hiding\")\n- protected void bind(InetAddress host, int port) throws IOException {\n- // ignored\n- }\n-\n- private void checkClose() throws IOException {\n- if (closedInputStream && closedOutputStream) {\n- close();\n- }\n- }\n-\n- @Override\n- protected final void close() throws IOException {\n- core.runCleaner();\n- }\n-\n- @Override\n- @SuppressWarnings(\"hiding\")\n- protected void connect(String host, int port) throws IOException {\n- throw new SocketException(\"Cannot bind to this type of address: \" + InetAddress.class);\n- }\n-\n- @Override\n- @SuppressWarnings(\"hiding\")\n- protected void connect(InetAddress address, int port) throws IOException {\n- throw new SocketException(\"Cannot bind to this type of address: \" + InetAddress.class);\n- }\n-\n- @Override\n- protected void connect(SocketAddress addr, int connectTimeout) throws IOException {\n- connect0(addr, connectTimeout);\n- }\n-\n- boolean connect0(SocketAddress addr, int connectTimeout) throws IOException {\n- if (!(addr instanceof AFUNIXSocketAddress)) {\n- throw new SocketException(\"Cannot bind to this type of address: \" + addr.getClass());\n- }\n- if (addr == AFUNIXSocketAddress.INTERNAL_DUMMY_CONNECT) { // NOPMD\n- this.connected.set(true);\n- return true;\n- } else if (addr == AFUNIXSocketAddress.INTERNAL_DUMMY_CONNECT) { // NOPMD)\n- return false;\n- }\n- AFUNIXSocketAddress socketAddress = (AFUNIXSocketAddress) addr;\n- boolean success = NativeUnixSocket.connect(socketAddress.getBytes(), fd, -1);\n- if (success) {\n- setSocketAddress(socketAddress);\n- this.connected.set(true);\n- }\n- core.validFdOrException();\n- return success;\n- }\n-\n- @Override\n- protected void create(boolean stream) throws IOException {\n- if (isClosed()) {\n- throw new SocketException(\"Already closed\");\n- }\n- if (fd.valid()) {\n- if (createType != null) {\n- if (createType.booleanValue() != stream) {\n- throw new IllegalStateException(\"Already created with different mode\");\n- }\n- } else {\n- createType = stream;\n- }\n- return;\n- }\n- createType = stream;\n- NativeUnixSocket.createSocket(fd, stream ? NativeUnixSocket.SOCK_STREAM\n- : NativeUnixSocket.SOCK_DGRAM);\n- }\n-\n- @Override\n- protected InputStream getInputStream() throws IOException {\n- if (!isConnected() && !isBound()) {\n- throw new IOException(\"Not connected/not bound\");\n- }\n- core.validFdOrException();\n- return in;\n- }\n-\n- @Override\n- protected OutputStream getOutputStream() throws IOException {\n- if (!isClosed() && !isBound()) {\n- throw new IOException(\"Not connected/not bound\");\n- }\n- core.validFdOrException();\n- return out;\n- }\n-\n- @Override\n- protected void listen(int backlog) throws IOException {\n- FileDescriptor fdesc = core.validFdOrException();\n- if (backlog <= 0) {\n- backlog = 50;\n- }\n- NativeUnixSocket.listen(fdesc, backlog);\n- }\n-\n- @Override\n- protected boolean supportsUrgentData() {\n- // We don't really support it\n- return false;\n- }\n-\n- @Override\n- protected void sendUrgentData(int data) throws IOException {\n- throw new UnsupportedOperationException();\n- }\n-\n- private final class AFUNIXInputStream extends InputStream {\n- private volatile boolean streamClosed = false;\n- private boolean eofReached = false;\n-\n- @Override\n- public int read(byte[] buf, int off, int len) throws IOException {\n- if (streamClosed) {\n- throw new IOException(\"This InputStream has already been closed.\");\n- }\n- FileDescriptor fdesc = core.validFdOrException();\n- if (len == 0) {\n- return 0;\n- } else if (off < 0 || len < 0 || (len > buf.length - off)) {\n- throw new IndexOutOfBoundsException();\n- }\n-\n- return NativeUnixSocket.read(fdesc, buf, off, len, ancillaryDataSupport, socketTimeout.get());\n- }\n-\n- @Override\n- public int read() throws IOException {\n- FileDescriptor fdesc = core.validFdOrException();\n-\n- if (eofReached) {\n- return -1;\n- }\n- int byteRead = NativeUnixSocket.read(fdesc, null, 0, 1, ancillaryDataSupport, socketTimeout\n- .get());\n- if (byteRead < 0) {\n- eofReached = true;\n- return -1;\n- } else {\n- return byteRead;\n- }\n- }\n-\n- @Override\n- public synchronized void close() throws IOException {\n- streamClosed = true;\n- FileDescriptor fdesc = core.validFd();\n- if (fdesc != null) {\n- NativeUnixSocket.shutdown(fdesc, SHUT_RD);\n- }\n-\n- closedInputStream = true;\n- checkClose();\n- }\n-\n- @Override\n- public int available() throws IOException {\n- if (streamClosed) {\n- throw new IOException(\"This InputStream has already been closed.\");\n- }\n-\n- return AFUNIXSocketImpl.this.available();\n- }\n- }\n-\n- private static boolean checkWriteInterruptedException(int bytesTransferred)\n- throws InterruptedIOException {\n- if (Thread.interrupted()) {\n- InterruptedIOException ex = new InterruptedIOException(\"Thread interrupted during write\");\n- ex.bytesTransferred = bytesTransferred;\n- Thread.currentThread().interrupt();\n- throw ex;\n- }\n- return true;\n- }\n-\n- private final class AFUNIXOutputStream extends OutputStream {\n- private volatile boolean streamClosed = false;\n-\n- @Override\n- public void write(int oneByte) throws IOException {\n- FileDescriptor fdesc = core.validFdOrException();\n-\n- int written;\n- do {\n- written = NativeUnixSocket.write(fdesc, null, oneByte, 1, ancillaryDataSupport);\n- if (written != 0) {\n- break;\n- }\n- } while (checkWriteInterruptedException(0));\n- }\n-\n- @Override\n- public void write(byte[] buf, int off, int len) throws IOException {\n- if (streamClosed) {\n- throw new SocketException(\"This OutputStream has already been closed.\");\n- }\n- if (len < 0 || off < 0 || len > buf.length - off) {\n- throw new IndexOutOfBoundsException();\n- }\n- FileDescriptor fdesc = core.validFdOrException();\n- if (len == 0) {\n- return;\n- }\n-\n- int writtenTotal = 0;\n-\n- do {\n- final int written = NativeUnixSocket.write(fdesc, buf, off, len, ancillaryDataSupport);\n- if (written < 0) {\n- throw new IOException(\"Unspecific error while writing\");\n- }\n-\n- len -= written;\n- off += written;\n- writtenTotal += written;\n- } while (len > 0 && checkWriteInterruptedException(writtenTotal));\n- }\n-\n- @Override\n- public synchronized void close() throws IOException {\n- if (streamClosed) {\n- return;\n- }\n- streamClosed = true;\n- FileDescriptor fdesc = core.validFd();\n- if (fdesc != null) {\n- NativeUnixSocket.shutdown(fdesc, SHUT_WR);\n- }\n- closedOutputStream = true;\n- checkClose();\n- }\n- }\n-\n- @Override\n- public String toString() {\n- return super.toString() + \"[fd=\" + fd + \"; addr=\" + this.core.socketAddress + \"; connected=\"\n- + connected + \"; bound=\" + bound + \"]\";\n- }\n-\n- private static int expectInteger(Object value) throws SocketException {\n- if (value == null) {\n- throw (SocketException) new SocketException(\"Value must not be null\").initCause(\n- new NullPointerException());\n- }\n- try {\n- return (Integer) value;\n- } catch (final ClassCastException e) {\n- throw (SocketException) new SocketException(\"Unsupported value: \" + value).initCause(e);\n- }\n- }\n-\n- private static int expectBoolean(Object value) throws SocketException {\n- if (value == null) {\n- throw (SocketException) new SocketException(\"Value must not be null\").initCause(\n- new NullPointerException());\n- }\n- try {\n- return ((Boolean) value).booleanValue() ? 1 : 0;\n- } catch (final ClassCastException e) {\n- throw (SocketException) new SocketException(\"Unsupported value: \" + value).initCause(e);\n- }\n- }\n-\n- @Override\n- public Object getOption(int optID) throws SocketException {\n- if (isClosed()) {\n- throw new SocketException(\"Socket is closed\");\n- }\n- if (optID == SocketOptions.SO_REUSEADDR) {\n- return reuseAddr;\n- }\n-\n- FileDescriptor fdesc = core.validFdOrException();\n- return getOptionDefault(fdesc, optID, socketTimeout);\n- }\n-\n- static Object getOptionDefault(FileDescriptor fdesc, int optID, AtomicInteger acceptTimeout)\n- throws SocketException {\n- try {\n- switch (optID) {\n- case SocketOptions.SO_KEEPALIVE:\n- try {\n- return NativeUnixSocket.getSocketOptionInt(fdesc, optID) != 0 ? true : false;\n- } catch (SocketException e) {\n- // ignore\n- return false;\n- }\n- case SocketOptions.TCP_NODELAY:\n- return NativeUnixSocket.getSocketOptionInt(fdesc, optID) != 0 ? true : false;\n- case SocketOptions.SO_TIMEOUT:\n- return Math.max((acceptTimeout == null ? 0 : acceptTimeout.get()), Math.max(\n- NativeUnixSocket.getSocketOptionInt(fdesc, 0x1005), NativeUnixSocket\n- .getSocketOptionInt(fdesc, 0x1006)));\n- case SocketOptions.SO_LINGER:\n- case SocketOptions.SO_RCVBUF:\n- case SocketOptions.SO_SNDBUF:\n- return NativeUnixSocket.getSocketOptionInt(fdesc, optID);\n- case SocketOptions.IP_TOS:\n- return 0;\n- case SocketOptions.SO_BINDADDR:\n- return AFUNIXSocketAddress.getInetAddress(fdesc, false);\n- case SocketOptions.SO_REUSEADDR:\n- return false;\n- default:\n- throw new SocketException(\"Unsupported option: \" + optID);\n- }\n- } catch (final SocketException e) {\n- throw e;\n- } catch (final Exception e) {\n- throw (SocketException) new SocketException(\"Could not get option\").initCause(e);\n- }\n- }\n-\n- @Override\n- public void setOption(int optID, Object value) throws SocketException {\n- if (isClosed()) {\n- throw new SocketException(\"Socket is closed\");\n- }\n- if (optID == SocketOptions.SO_REUSEADDR) {\n- reuseAddr = expectBoolean(value) == 0 ? false : true;\n- return;\n- }\n-\n- FileDescriptor fdesc = core.validFdOrException();\n- setOptionDefault(fdesc, optID, value, socketTimeout);\n- }\n-\n- static void setOptionDefault(FileDescriptor fdesc, int optID, Object value,\n- AtomicInteger acceptTimeout) throws SocketException {\n- try {\n- switch (optID) {\n- case SocketOptions.SO_LINGER:\n-\n- if (value instanceof Boolean) {\n- final boolean b = (Boolean) value;\n- if (b) {\n- throw new SocketException(\"Only accepting Boolean.FALSE here\");\n- }\n- NativeUnixSocket.setSocketOptionInt(fdesc, optID, -1);\n- return;\n- }\n- NativeUnixSocket.setSocketOptionInt(fdesc, optID, expectInteger(value));\n- return;\n- case SocketOptions.SO_TIMEOUT: {\n- int timeout = expectInteger(value);\n- NativeUnixSocket.setSocketOptionInt(fdesc, 0x1005, timeout);\n- NativeUnixSocket.setSocketOptionInt(fdesc, 0x1006, timeout);\n- if (acceptTimeout != null) {\n- acceptTimeout.set(timeout);\n- }\n- return;\n- }\n- case SocketOptions.SO_RCVBUF:\n- case SocketOptions.SO_SNDBUF:\n- NativeUnixSocket.setSocketOptionInt(fdesc, optID, expectInteger(value));\n- return;\n- case SocketOptions.SO_KEEPALIVE:\n- try {\n- NativeUnixSocket.setSocketOptionInt(fdesc, optID, expectBoolean(value));\n- } catch (SocketException e) {\n- // ignore\n- }\n- return;\n- case SocketOptions.TCP_NODELAY:\n- NativeUnixSocket.setSocketOptionInt(fdesc, optID, expectBoolean(value));\n- return;\n- case SocketOptions.IP_TOS:\n- // ignore\n- return;\n- case SocketOptions.SO_REUSEADDR:\n- // ignore\n- return;\n- default:\n- throw new SocketException(\"Unsupported option: \" + optID);\n- }\n- } catch (final SocketException e) {\n- throw e;\n- } catch (final Exception e) {\n- throw (SocketException) new SocketException(\"Error while setting option\").initCause(e);\n- }\n- }\n-\n- @Override\n- protected void shutdownInput() throws IOException {\n- FileDescriptor fdesc = core.validFd();\n- if (fdesc != null) {\n- NativeUnixSocket.shutdown(fdesc, SHUT_RD);\n- }\n- }\n-\n- @Override\n- protected void shutdownOutput() throws IOException {\n- FileDescriptor fdesc = core.validFd();\n- if (fdesc != null) {\n- NativeUnixSocket.shutdown(fdesc, SHUT_WR);\n- }\n+ super(AFUNIXSocketAddress.AF_UNIX, fdObj);\n }\n \n /**\n@@ -686,31 +40,12 @@ class AFUNIXSocketImpl extends SocketImplShim {\n \n @Override\n public void setOption(int optID, Object value) throws SocketException {\n- try {\n- super.setOption(optID, value);\n- } catch (SocketException e) {\n- switch (optID) {\n- case SocketOptions.TCP_NODELAY:\n- return;\n- default:\n- throw e;\n- }\n- }\n+ super.setOptionLenient(optID, value);\n }\n \n @Override\n public Object getOption(int optID) throws SocketException {\n- try {\n- return super.getOption(optID);\n- } catch (SocketException e) {\n- switch (optID) {\n- case SocketOptions.TCP_NODELAY:\n- case SocketOptions.SO_KEEPALIVE:\n- return false;\n- default:\n- throw e;\n- }\n- }\n+ return super.getOptionLenient(optID);\n }\n }\n \n@@ -737,70 +72,4 @@ class AFUNIXSocketImpl extends SocketImplShim {\n final boolean hasOutboundFileDescriptors() {\n return ancillaryDataSupport.hasOutboundFileDescriptors();\n }\n-\n- int getAncillaryReceiveBufferSize() {\n- return ancillaryDataSupport.getAncillaryReceiveBufferSize();\n- }\n-\n- void setAncillaryReceiveBufferSize(int size) {\n- ancillaryDataSupport.setAncillaryReceiveBufferSize(size);\n- }\n-\n- void ensureAncillaryReceiveBufferSize(int minSize) {\n- ancillaryDataSupport.ensureAncillaryReceiveBufferSize(minSize);\n- }\n-\n- SocketAddress receive(ByteBuffer dst) throws IOException {\n- return core.receive(dst);\n- }\n-\n- int send(ByteBuffer src, SocketAddress target) throws IOException {\n- return core.write(src, target, 0);\n- }\n-\n- int read(ByteBuffer dst, ByteBuffer socketAddressBuffer) throws IOException {\n- return core.read(dst, socketAddressBuffer, 0);\n- }\n-\n- int write(ByteBuffer src) throws IOException {\n- return core.write(src);\n- }\n-\n- @Override\n- protected FileDescriptor getFileDescriptor() {\n- return core.fd;\n- }\n-\n- void updatePorts(int local, int remote) {\n- this.localport = local;\n- if (remote >= 0) {\n- this.port = remote;\n- }\n- }\n-\n- AFUNIXSocketAddress getLocalSocketAddress() {\n- return AFUNIXSocketAddress.getSocketAddress(getFileDescriptor(), false, localport);\n- }\n-\n- AFUNIXSocketAddress getRemoteSocketAddress() {\n- return AFUNIXSocketAddress.getSocketAddress(getFileDescriptor(), true, port);\n- }\n-\n- int getLocalPort1() {\n- return localport;\n- }\n-\n- int getRemotePort() {\n- return port;\n- }\n-\n- @Override\n- protected InetAddress getInetAddress() {\n- AFUNIXSocketAddress rsa = getRemoteSocketAddress();\n- if (rsa == null) {\n- return InetAddress.getLoopbackAddress();\n- } else {\n- return rsa.getInetAddress();\n- }\n- }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketPair.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketPair.java\nindex d586d7afb..f096d7f76 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketPair.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFUNIXSocketPair.java\n@@ -25,13 +25,9 @@ import java.io.IOException;\n * @param The socket type.\n * @author Christian Kohlschütter\n */\n-public final class AFUNIXSocketPair {\n- private final T socket1;\n- private final T socket2;\n-\n+public final class AFUNIXSocketPair extends AFSocketPair {\n AFUNIXSocketPair(T socket1, T socket2) {\n- this.socket1 = socket1;\n- this.socket2 = socket2;\n+ super(socket1, socket2);\n }\n \n /**\n@@ -53,22 +49,4 @@ public final class AFUNIXSocketPair {\n public static AFUNIXSocketPair openDatagram() throws IOException {\n return AFUNIXSelectorProvider.provider().openDatagramChannelPair();\n }\n-\n- /**\n- * Returns the first socket of the pair.\n- * \n- * @return The first socket.\n- */\n- public T getSocket1() {\n- return socket1;\n- }\n-\n- /**\n- * Returns the second socket of the pair.\n- * \n- * @return The second socket.\n- */\n- public T getSocket2() {\n- return socket2;\n- }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AncillaryDataSupport.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AncillaryDataSupport.java\nindex e64373904..a31a8df59 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AncillaryDataSupport.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AncillaryDataSupport.java\n@@ -30,23 +30,59 @@ import java.util.Map;\n \n import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n-class AncillaryDataSupport implements Closeable {\n+final class AncillaryDataSupport implements Closeable {\n private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0);\n private static final FileDescriptor[] NO_FILE_DESCRIPTORS = new FileDescriptor[0];\n \n- protected final Map openReceivedFileDescriptors = Collections\n+ private static final int MIN_ANCBUF_LEN = NativeUnixSocket.isLoaded() ? NativeUnixSocket\n+ .ancillaryBufMinLen() : 0;\n+\n+ private final Map openReceivedFileDescriptors = Collections\n .synchronizedMap(new HashMap());\n \n private final List receivedFileDescriptors = Collections.synchronizedList(\n new LinkedList());\n \n // referenced from native code\n- protected ByteBuffer ancillaryReceiveBuffer = EMPTY_BUFFER;\n+ private ByteBuffer ancillaryReceiveBuffer = EMPTY_BUFFER;\n \n // referenced from native code\n @SuppressFBWarnings(\"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD\")\n int[] pendingFileDescriptors = null;\n \n+ private int[] tipcErrorInfo = null;\n+\n+ private int[] tipcDestName = null;\n+\n+ // referenced from native code\n+ void setTipcErrorInfo(int errorCode, int dataLength) {\n+ if (errorCode == 0 && dataLength == 0) {\n+ tipcErrorInfo = null;\n+ } else {\n+ tipcErrorInfo = new int[] {errorCode, dataLength};\n+ }\n+ }\n+\n+ int[] getTIPCErrorInfo() {\n+ int[] info = tipcErrorInfo;\n+ tipcErrorInfo = null;\n+ return info;\n+ }\n+\n+ void setTipcDestName(int a, int b, int c) {\n+ if (a == 0 && b == 0 && c == 0) {\n+ this.tipcDestName = null;\n+ } else {\n+ this.tipcDestName = new int[] {a, b, c};\n+ }\n+ }\n+\n+ int[] getTIPCDestName() {\n+ int[] addr = tipcDestName;\n+ tipcDestName = null;\n+ return addr;\n+ }\n+\n int getAncillaryReceiveBufferSize() {\n return ancillaryReceiveBuffer.capacity();\n }\n@@ -57,7 +93,7 @@ class AncillaryDataSupport implements Closeable {\n } else if (size <= 0) {\n this.ancillaryReceiveBuffer = EMPTY_BUFFER;\n } else {\n- setAncillaryReceiveBufferSize0(Math.max(256, size));\n+ setAncillaryReceiveBufferSize0(Math.max(256, Math.min(MIN_ANCBUF_LEN, size)));\n }\n }\n \n@@ -65,7 +101,7 @@ class AncillaryDataSupport implements Closeable {\n this.ancillaryReceiveBuffer = ByteBuffer.allocateDirect(size);\n }\n \n- public final void ensureAncillaryReceiveBufferSize(int minSize) {\n+ public void ensureAncillaryReceiveBufferSize(int minSize) {\n if (minSize <= 0) {\n return;\n }\n@@ -101,7 +137,7 @@ class AncillaryDataSupport implements Closeable {\n this.receivedFileDescriptors.add(descriptors);\n }\n \n- final void clearReceivedFileDescriptors() {\n+ void clearReceivedFileDescriptors() {\n receivedFileDescriptors.clear();\n }\n \ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/CloseablePair.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/CloseablePair.java\nnew file mode 100644\nindex 000000000..63e7010e7\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/CloseablePair.java\n@@ -0,0 +1,88 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.Closeable;\n+import java.io.IOException;\n+import java.util.Objects;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+\n+/**\n+ * A pair of two closeable items.\n+ * \n+ * @param The type of the items.\n+ * @author Christian Kohlschütter\n+ */\n+public class CloseablePair implements Closeable {\n+ private final @NonNull T first;\n+ private final @NonNull T second;\n+ private final Closeable alsoClose;\n+\n+ /**\n+ * Creates a pair of two items.\n+ * \n+ * @param a The first item.\n+ * @param b The second item.\n+ */\n+ public CloseablePair(T a, T b) {\n+ this(a, b, null);\n+ }\n+\n+ /**\n+ * Creates a pair of two items.\n+ * \n+ * @param a The first item.\n+ * @param b The second item.\n+ * @param alsoClose Some closeable that is also closed upon {@link #close()}, or {@code null}.\n+ */\n+ public CloseablePair(T a, T b, Closeable alsoClose) {\n+ Objects.requireNonNull(a);\n+ Objects.requireNonNull(b);\n+ this.first = a;\n+ this.second = b;\n+ this.alsoClose = alsoClose;\n+ }\n+\n+ @Override\n+ public final void close() throws IOException {\n+ first.close();\n+ second.close();\n+ if (alsoClose != null) {\n+ alsoClose.close();\n+ }\n+ }\n+\n+ /**\n+ * Returns the pair's first item.\n+ * \n+ * @return The first item.\n+ */\n+ public final @NonNull T getFirst() {\n+ return first;\n+ }\n+\n+ /**\n+ * Returns the pair's second item.\n+ * \n+ * @return The second item.\n+ */\n+ public final @NonNull T getSecond() {\n+ return second;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/DatagramSocketImplShim.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/DatagramSocketImplShim.java\nnew file mode 100644\nindex 000000000..2f5d2077d\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/DatagramSocketImplShim.java\n@@ -0,0 +1,67 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.IOException;\n+import java.net.DatagramSocketImpl;\n+import java.net.SocketOption;\n+import java.util.Set;\n+\n+/**\n+ * A shim that is filled with Java version-specific overrides. This variant is for Java 9 and above.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+abstract class DatagramSocketImplShim extends DatagramSocketImpl {\n+ protected DatagramSocketImplShim() {\n+ super();\n+ }\n+\n+ @Override\n+ protected void setOption(SocketOption name, T value) throws IOException {\n+ if (name instanceof AFSocketOption) {\n+ ((AFDatagramSocketImpl) this).getCore().setOption((AFSocketOption) name, value);\n+ return;\n+ }\n+ Integer optionId = SocketOptionsMapper.resolve(name);\n+ if (optionId == null) {\n+ super.setOption(name, value);\n+ } else {\n+ setOption(optionId, value);\n+ }\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ @Override\n+ protected T getOption(SocketOption name) throws IOException {\n+ if (name instanceof AFSocketOption) {\n+ return ((AFDatagramSocketImpl) this).getCore().getOption((AFSocketOption) name);\n+ }\n+ Integer optionId = SocketOptionsMapper.resolve(name);\n+ if (optionId == null) {\n+ return super.getOption(name);\n+ } else {\n+ return (T) getOption(optionId);\n+ }\n+ }\n+\n+ @Override\n+ protected Set> supportedOptions() {\n+ return SocketOptionsMapper.SUPPORTED_SOCKET_OPTIONS;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/FileDescriptorCast.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/FileDescriptorCast.java\nindex 58885bcd0..2e0c882c3 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/FileDescriptorCast.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/FileDescriptorCast.java\n@@ -22,6 +22,7 @@ import java.io.FileInputStream;\n import java.io.FileOutputStream;\n import java.io.IOException;\n import java.io.InputStream;\n+import java.lang.ProcessBuilder.Redirect;\n import java.net.Socket;\n import java.nio.channels.FileChannel;\n import java.nio.channels.ReadableByteChannel;\n@@ -31,6 +32,7 @@ import java.util.HashMap;\n import java.util.Map;\n import java.util.Objects;\n import java.util.Set;\n+import java.util.function.Function;\n \n import org.eclipse.jdt.annotation.NonNull;\n \n@@ -39,10 +41,10 @@ import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n /**\n * Provides object-oriented access to file descriptors via {@link InputStream}, {@link Socket},\n * etc., depending on the file descriptor type.\n- * \n+ *

\n * Typical usage:\n- * \n- * \n+ *

\n+ *
\n  * FileDescriptor fd;\n  * \n  * // succeeds if fd refers to an AF_UNIX stream socket\n@@ -54,22 +56,33 @@ import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n  * // always succeeds\n  * InputStream in = FileDescriptorCast.using(fd).as(InputStream.class); \n  * OutputStream in = FileDescriptorCast.using(fd).as(OutputStream.class); \n- * \n- * \n+ * 
\n+ *

\n * IMPORTANT: On some platforms (e.g., Solaris, Illumos) you may need to re-apply a read timeout\n * (e.g., using {@link Socket#setSoTimeout(int)}) after obtaining the socket.\n+ *

\n+ *

\n+ * Note that you may also lose Java port information for {@link AFSocketAddress} implementations\n+ * that do not encode this information directly (such as {@link AFUNIXSocketAddress} and\n+ * {@link AFTIPCSocketAddress}).\n+ *

\n * \n * @author Christian Kohlschütter\n */\n public final class FileDescriptorCast implements FileDescriptorAccess {\n+ private static final Map, CastingProviderMap> PRIMARY_TYPE_PROVIDERS_MAP = Collections\n+ .synchronizedMap(new HashMap<>());\n+\n private final FileDescriptor fdObj;\n \n private int localPort = 0;\n private int remotePort = 0;\n \n+ private static final Function FD_IS_PROVIDER = System\n+ .getProperty(\"osv.version\") != null ? LenientFileInputStream::new : FileInputStream::new;\n+\n private static final CastingProviderMap GLOBAL_PROVIDERS_FINAL = new CastingProviderMap() {\n \n- @SuppressWarnings(\"null\")\n @Override\n protected void addProviders() {\n // FileDescriptor and Object cannot be overridden\n@@ -84,7 +97,6 @@ public final class FileDescriptorCast implements FileDescriptorAccess {\n };\n \n private static final CastingProviderMap GLOBAL_PROVIDERS = new CastingProviderMap() {\n- @SuppressWarnings(\"null\")\n @Override\n protected void addProviders() {\n addProvider(WritableByteChannel.class, new CastingProvider() {\n@@ -100,7 +112,7 @@ public final class FileDescriptorCast implements FileDescriptorAccess {\n @Override\n public ReadableByteChannel provideAs(FileDescriptorCast fdc,\n Class desiredType) throws IOException {\n- return new FileInputStream(fdc.getFileDescriptor()).getChannel();\n+ return FD_IS_PROVIDER.apply(fdc.getFileDescriptor()).getChannel();\n }\n });\n \n@@ -123,15 +135,27 @@ public final class FileDescriptorCast implements FileDescriptorAccess {\n @Override\n public FileInputStream provideAs(FileDescriptorCast fdc,\n Class desiredType) throws IOException {\n- return new FileInputStream(fdc.getFileDescriptor());\n+ return FD_IS_PROVIDER.apply(fdc.getFileDescriptor());\n }\n });\n+\n+ if (AFSocket.supports(AFSocketCapability.CAPABILITY_FD_AS_REDIRECT)) {\n+ addProvider(Redirect.class, new CastingProvider() {\n+ @Override\n+ public Redirect provideAs(FileDescriptorCast fdc, Class desiredType)\n+ throws IOException {\n+\n+ Redirect red = NativeUnixSocket.initRedirect(fdc.getFileDescriptor());\n+ if (red == null) {\n+ throw new ClassCastException(\"Cannot access file descriptor as \" + desiredType);\n+ }\n+ return red;\n+ }\n+ });\n+ }\n }\n };\n \n- private static final Map, CastingProviderMap> PRIMARY_TYPE_PROVIDERS_MAP =\n- new HashMap<>();\n-\n private final CastingProviderMap cpm;\n \n private FileDescriptorCast(FileDescriptor fdObj, CastingProviderMap cpm) {\n@@ -139,84 +163,63 @@ public final class FileDescriptorCast implements FileDescriptorAccess {\n this.cpm = Objects.requireNonNull(cpm);\n }\n \n- static {\n- registerCastingProviders(AFUNIXSocket.class, new CastingProviderMap() {\n+ private static void registerCastingProviders(Class primaryType, CastingProviderMap cpm) {\n+ Objects.requireNonNull(primaryType);\n+ CastingProviderMap prev;\n+ if ((prev = PRIMARY_TYPE_PROVIDERS_MAP.put(primaryType, cpm)) != null) {\n+ PRIMARY_TYPE_PROVIDERS_MAP.put(primaryType, prev);\n+ throw new IllegalStateException(\"Already registered: \" + primaryType);\n+ }\n+ }\n+\n+ static
void registerCastingProviders(\n+ AFAddressFamilyConfig config) {\n+ Class> socketClass = config.socketClass();\n+ Class> datagramSocketClass = config.datagramSocketClass();\n+\n+ registerCastingProviders(socketClass, new CastingProviderMap() {\n \n @SuppressWarnings(\"null\")\n @Override\n protected void addProviders() {\n addProviders(GLOBAL_PROVIDERS);\n \n- final CastingProvider cpSocket = new CastingProvider() {\n- @Override\n- public AFUNIXSocket provideAs(FileDescriptorCast fdc,\n- Class desiredType) throws IOException {\n- return AFUNIXSocket.newInstance(fdc.getFileDescriptor(), fdc.localPort, fdc.remotePort);\n- }\n- };\n- final CastingProvider cpServerSocket =\n- new CastingProvider() {\n- @Override\n- public AFUNIXServerSocket provideAs(FileDescriptorCast fdc,\n- Class desiredType) throws IOException {\n- return AFUNIXServerSocket.newInstance(fdc.getFileDescriptor(), fdc.localPort,\n- fdc.remotePort);\n- }\n- };\n-\n- addProvider(AFUNIXSocketChannel.class, new CastingProvider() {\n- @Override\n- public AFUNIXSocketChannel provideAs(FileDescriptorCast fdc,\n- Class desiredType) throws IOException {\n- return cpSocket.provideAs(fdc, AFUNIXSocket.class).getChannel();\n- }\n- });\n- addProvider(AFUNIXServerSocketChannel.class,\n- new CastingProvider() {\n- @Override\n- public AFUNIXServerSocketChannel provideAs(FileDescriptorCast fdc,\n- Class desiredType) throws IOException {\n- return cpServerSocket.provideAs(fdc, AFUNIXServerSocket.class).getChannel();\n- }\n- });\n- addProvider(AFUNIXSocket.class, cpSocket);\n- addProvider(AFUNIXServerSocket.class, cpServerSocket);\n+ final CastingProvider> cpSocket = (fdc, desiredType) -> AFSocket.newInstance(\n+ config.socketConstructor(), (AFSocketFactory) null, fdc.getFileDescriptor(),\n+ fdc.localPort, fdc.remotePort);\n+ final CastingProvider> cpServerSocket = (fdc,\n+ desiredType) -> AFServerSocket.newInstance(config.serverSocketConstructor(), fdc\n+ .getFileDescriptor(), fdc.localPort, fdc.remotePort);\n+\n+ addProvider(socketClass, cpSocket);\n+ addProvider(config.serverSocketClass(), cpServerSocket);\n+\n+ addProvider(config.socketChannelClass(), (fdc, desiredType) -> cpSocket.provideAs(fdc,\n+ AFSocket.class).getChannel());\n+ addProvider(config.serverSocketChannelClass(), (fdc, desiredType) -> cpServerSocket\n+ .provideAs(fdc, AFServerSocket.class).getChannel());\n }\n });\n \n- registerCastingProviders(AFUNIXDatagramSocket.class, new CastingProviderMap() {\n+ registerCastingProviders(datagramSocketClass, new CastingProviderMap() {\n \n @SuppressWarnings(\"null\")\n @Override\n protected void addProviders() {\n addProviders(GLOBAL_PROVIDERS);\n \n- final CastingProvider cpDatagramSocket =\n- new CastingProvider() {\n- @Override\n- public AFUNIXDatagramSocket provideAs(FileDescriptorCast fdc,\n- Class desiredType) throws IOException {\n- return AFUNIXDatagramSocket.newInstance(fdc.getFileDescriptor(), fdc.localPort,\n- fdc.remotePort);\n- }\n- };\n-\n- addProvider(AFUNIXDatagramChannel.class, new CastingProvider() {\n- @Override\n- public AFUNIXDatagramChannel provideAs(FileDescriptorCast fdc,\n- Class desiredType) throws IOException {\n- return cpDatagramSocket.provideAs(fdc, AFUNIXDatagramSocket.class).getChannel();\n- }\n- });\n- addProvider(AFUNIXDatagramSocket.class, cpDatagramSocket);\n+ final CastingProvider> cpDatagramSocket = (fdc,\n+ desiredType) -> AFDatagramSocket.newInstance(config.datagramSocketConstructor(), fdc\n+ .getFileDescriptor(), fdc.localPort, fdc.remotePort);\n+\n+ addProvider(datagramSocketClass, cpDatagramSocket);\n+\n+ addProvider(config.datagramChannelClass(), (fdc, desiredType) -> cpDatagramSocket.provideAs(\n+ fdc, AFDatagramSocket.class).getChannel());\n }\n });\n }\n \n- private static void registerCastingProviders(Class primaryType, CastingProviderMap cpm) {\n- PRIMARY_TYPE_PROVIDERS_MAP.put(primaryType, cpm);\n- }\n-\n private abstract static class CastingProviderMap {\n private final Map, CastingProvider> providers = new HashMap<>();\n private final Set> classes = Collections.unmodifiableSet(providers.keySet());\n@@ -229,7 +232,7 @@ public final class FileDescriptorCast implements FileDescriptorAccess {\n \n protected abstract void addProviders();\n \n- protected final void addProvider(Class type, CastingProvider cp) {\n+ protected final void addProvider(Class type, CastingProvider cp) {\n Objects.requireNonNull(type);\n \n addProvider0(type, cp);\n@@ -260,6 +263,7 @@ public final class FileDescriptorCast implements FileDescriptorAccess {\n }\n }\n \n+ @FunctionalInterface\n private interface CastingProvider {\n T provideAs(FileDescriptorCast fdc, Class desiredType) throws IOException;\n }\n@@ -276,15 +280,22 @@ public final class FileDescriptorCast implements FileDescriptorAccess {\n if (!fdObj.valid()) {\n throw new IOException(\"Not a valid file descriptor\");\n }\n- Class primaryType = NativeUnixSocket.primaryType(fdObj);\n+ Class primaryType = NativeUnixSocket.isLoaded() ? NativeUnixSocket.primaryType(fdObj) : null;\n if (primaryType == null) {\n- throw new IOException(\"Unsupported file descriptor\");\n+ primaryType = FileDescriptor.class;\n }\n \n+ triggerInit();\n+\n CastingProviderMap map = PRIMARY_TYPE_PROVIDERS_MAP.get(primaryType);\n return new FileDescriptorCast(fdObj, map == null ? GLOBAL_PROVIDERS : map);\n }\n \n+ private static void triggerInit() {\n+ AFUNIXSocketAddress.addressFamily().getClass(); // trigger registration\n+ AFTIPCSocketAddress.addressFamily().getClass(); // trigger registration\n+ }\n+\n /**\n * Registers the given port number as the \"local port\" for this file descriptor.\n * \n@@ -371,4 +382,24 @@ public final class FileDescriptorCast implements FileDescriptorAccess {\n public FileDescriptor getFileDescriptor() {\n return fdObj;\n }\n+\n+ private static final class LenientFileInputStream extends FileInputStream {\n+ private LenientFileInputStream(FileDescriptor fdObj) {\n+ super(fdObj);\n+ }\n+\n+ @Override\n+ public int available() throws IOException {\n+ try {\n+ return super.available();\n+ } catch (IOException e) {\n+ String msg = e.getMessage();\n+ if (\"Invalid seek\".equals(msg)) {\n+ // OSv may not like FileInputStream#availabe() on pipe fds.\n+ return 0;\n+ }\n+ throw e;\n+ }\n+ }\n+ }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/HostAndPort.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/HostAndPort.java\nnew file mode 100644\nindex 000000000..21bcf52b0\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/HostAndPort.java\n@@ -0,0 +1,217 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.UnsupportedEncodingException;\n+import java.net.SocketException;\n+import java.net.URI;\n+import java.net.URLDecoder;\n+import java.net.URLEncoder;\n+import java.util.Objects;\n+import java.util.regex.Matcher;\n+import java.util.regex.Pattern;\n+\n+/**\n+ * Hostname and port.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public final class HostAndPort {\n+ private static final Pattern PAT_HOST_AND_PORT = Pattern.compile(\n+ \"^//((?[^/\\\\@]*)\\\\@)?(?[^/\\\\:]+)(?:\\\\:(?[0-9]+))?\");\n+ private final String hostname;\n+ private final int port;\n+\n+ /**\n+ * Creates a new hostname and port combination.\n+ * \n+ * @param hostname The hostname.\n+ * @param port The port, or {@code -1} for \"no port\".\n+ */\n+ public HostAndPort(String hostname, int port) {\n+ this.hostname = hostname;\n+ this.port = port;\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ final int prime = 31;\n+ int result = 1;\n+ result = prime * result + ((getHostname() == null) ? 0 : getHostname().hashCode());\n+ result = prime * result + getPort();\n+ return result;\n+ }\n+\n+ @Override\n+ public boolean equals(Object obj) {\n+ if (this == obj) {\n+ return true;\n+ }\n+ if (!(obj instanceof HostAndPort)) {\n+ return false;\n+ }\n+ HostAndPort other = (HostAndPort) obj;\n+ if (getHostname() == null) {\n+ if (other.getHostname() != null) {\n+ return false;\n+ }\n+ } else if (!getHostname().equals(other.getHostname())) {\n+ return false;\n+ }\n+\n+ return getPort() == other.getPort();\n+ }\n+\n+ @Override\n+ public String toString() {\n+ if (getPort() == -1) {\n+ return getHostname();\n+ } else {\n+ return getHostname() + \":\" + getPort();\n+ }\n+ }\n+\n+ /**\n+ * Tries to extract hostname and port information from the given URI.\n+ * \n+ * @param u The URI to extract from.\n+ * @return The parsed {@link HostAndPort} instance.\n+ * @throws SocketException on error.\n+ */\n+ public static HostAndPort parseFrom(URI u) throws SocketException {\n+ String host = u.getHost();\n+ if (host != null) {\n+ return new HostAndPort(host, u.getPort());\n+ }\n+ String raw = u.getRawSchemeSpecificPart();\n+ Matcher m = PAT_HOST_AND_PORT.matcher(raw);\n+ if (!m.find()) {\n+ throw new SocketException(\"Cannot parse URI: \" + u);\n+ }\n+ try {\n+ host = URLDecoder.decode(m.group(\"host\"), \"UTF-8\");\n+ } catch (UnsupportedEncodingException e) {\n+ throw new IllegalStateException(e);\n+ }\n+\n+ String portStr = m.group(\"port\");\n+ int port;\n+ if (portStr == null) {\n+ port = -1;\n+ } else {\n+ port = Integer.parseInt(portStr);\n+ }\n+\n+ return new HostAndPort(host, port);\n+ }\n+\n+ private static String urlEncode(String s) {\n+ try {\n+ return URLEncoder.encode(s, \"UTF-8\");\n+ } catch (UnsupportedEncodingException e) {\n+ throw new IllegalStateException(e);\n+ }\n+ }\n+\n+ /**\n+ * Returns the hostname.\n+ * \n+ * @return The hostname.\n+ */\n+ public String getHostname() {\n+ return hostname;\n+ }\n+\n+ /**\n+ * Returns the port, or {@code -1} for \"no port specified\".\n+ * \n+ * @return The port.\n+ */\n+ public int getPort() {\n+ return port;\n+ }\n+\n+ /**\n+ * Returns a URI with this hostname and port.\n+ * \n+ * @param scheme The scheme to use.\n+ * @return The URI.\n+ */\n+ public URI toURI(String scheme) {\n+ return toURI(scheme, null, null, null, null);\n+ }\n+\n+ /**\n+ * Returns a URI with this hostname and port, potentially reusing other URI parameters from the\n+ * given template URI (authority, path, query, fragment).\n+ * \n+ * @param scheme The scheme to use.\n+ * @param template The template. or {@code null}.\n+ * @return The URI.\n+ */\n+ public URI toURI(String scheme, URI template) {\n+ if (template == null) {\n+ return toURI(scheme, null, null, null, null);\n+ }\n+\n+ String rawAuthority = template.getRawAuthority();\n+ int at = rawAuthority.indexOf('@');\n+ if (at >= 0) {\n+ rawAuthority = rawAuthority.substring(0, at);\n+ } else if (rawAuthority.length() > 0 && template.getHost() == null) {\n+ // encoded hostname was parsed as authority\n+ rawAuthority = null;\n+ } else if (rawAuthority.length() > 0 && template.getAuthority().equals(template.getHost())) {\n+ // hostname was duplicated as authority\n+ rawAuthority = null;\n+ } else if (rawAuthority.length() > 0 && template.getAuthority().equals(template.getHost() + \":\"\n+ + template.getPort())) {\n+ // hostname:port was duplicated as authority\n+ rawAuthority = null;\n+ }\n+\n+ return toURI(scheme, rawAuthority, template.getRawPath(), template.getRawQuery(), template\n+ .getRawFragment());\n+ }\n+\n+ /**\n+ * Returns a URI with this hostname and port, potentially using other URI parameters from the\n+ * given set of parameters.\n+ * \n+ * @param scheme The scheme to use.\n+ * @param rawAuthority The raw authority field, or {@code null}.\n+ * @param rawPath The raw path field, or {@code null}.\n+ * @param rawQuery The raw query field, or {@code null}.\n+ * @param rawFragment The raw fragment field, or {@code null}.\n+ * @return The URI.\n+ */\n+ public URI toURI(String scheme, String rawAuthority, String rawPath, String rawQuery,\n+ String rawFragment) {\n+ Objects.requireNonNull(scheme);\n+ if (rawPath != null && !rawPath.isEmpty()) {\n+ if (!rawPath.startsWith(\"/\")) {\n+ throw new IllegalArgumentException(\"Path must be absolute: \" + rawPath);\n+ }\n+ }\n+\n+ return URI.create(scheme + \"://\" + (rawAuthority == null ? \"\" : rawAuthority + \"@\") + urlEncode(\n+ getHostname()).replace(\"%2C\", \",\") + (port <= 0 ? \"\" : (\":\" + port)) + (rawPath == null ? \"\"\n+ : rawPath) + (rawQuery == null ? \"\" : \"?\" + rawQuery) + (rawFragment == null ? \"\" : \"#\"\n+ + rawFragment));\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/NamedInteger.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/NamedInteger.java\nnew file mode 100644\nindex 000000000..d686398be\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/NamedInteger.java\n@@ -0,0 +1,170 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.Serializable;\n+import java.util.HashSet;\n+import java.util.Objects;\n+import java.util.Set;\n+\n+import org.eclipse.jdt.annotation.NonNullByDefault;\n+import org.eclipse.jdt.annotation.Nullable;\n+\n+/**\n+ * A \"named integer\", usually used for constants.\n+ * \n+ * See the concrete implementations for usage.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+@NonNullByDefault\n+public class NamedInteger implements Serializable {\n+ private static final long serialVersionUID = 1L;\n+\n+ /**\n+ * The name.\n+ */\n+ private final String name; // NOPMD\n+\n+ /**\n+ * The ID value.\n+ */\n+ private final int id;\n+\n+ /**\n+ * Marks a subclass that provides a method {@code \"public static T ofValue(int v)\"} that allows\n+ * casting an integer to this type via reflection.\n+ */\n+ public interface HasOfValue {\n+ /* static ofValue(int v); */\n+ }\n+\n+ /**\n+ * Creates a new {@link NamedInteger} instance, without actually naming it. A name of \"UNDEFINED\"\n+ * is used.\n+ * \n+ * @param id The value.\n+ */\n+ protected NamedInteger(int id) {\n+ this(\"UNDEFINED\", id);\n+ }\n+\n+ /**\n+ * Creates a new {@link NamedInteger} instance.\n+ * \n+ * @param name The name.\n+ * @param id The value.\n+ */\n+ protected NamedInteger(String name, int id) {\n+ this.name = name;\n+ this.id = id;\n+ }\n+\n+ /**\n+ * Returns the name.\n+ * \n+ * @return The name.\n+ */\n+ public final String name() {\n+ return name;\n+ }\n+\n+ /**\n+ * Returns the value.\n+ * \n+ * @return The value.\n+ */\n+ public final int value() {\n+ return id;\n+ }\n+\n+ @Override\n+ public final String toString() {\n+ return name() + \"(\" + id + \")\";\n+ }\n+\n+ @Override\n+ public final int hashCode() {\n+ return Objects.hash(id);\n+ }\n+\n+ @Override\n+ public final boolean equals(@Nullable Object obj) {\n+ if (this == obj) {\n+ return true;\n+ } else if (obj == null) {\n+ return false;\n+ } else if (getClass() != obj.getClass()) {\n+ return false;\n+ }\n+ NamedInteger other = (NamedInteger) obj;\n+ return id == other.value();\n+ }\n+\n+ /**\n+ * Ensures that the {@code VALUES} array is configured correctly.\n+ * \n+ * @param The instance type.\n+ * @param values The {@code VALUES} array.\n+ * @return The verified {@code VALUES} array.\n+ */\n+ protected static final T[] init(T[] values) {\n+ Set seenValues = new HashSet<>();\n+ for (T val : values) {\n+ if (!seenValues.add(val.value())) {\n+ throw new IllegalStateException(\"Duplicate value: \" + val.value());\n+ }\n+ }\n+ return values;\n+ }\n+\n+ /**\n+ * Constructor for \"undefined\" values.\n+ * \n+ * @param The instance type.\n+ */\n+ @FunctionalInterface\n+ protected interface UndefinedValueConstructor {\n+ /**\n+ * Creates a new \"undefined\" value instance.\n+ * \n+ * @param id The value.\n+ * @return The instance.\n+ */\n+ T newInstance(int id);\n+ }\n+\n+ /**\n+ * Returns an instance given an integer value.\n+ * \n+ * @param The instance type.\n+ * @param values The {@code VALUES} array.\n+ * @param constr The constructor for undefined values.\n+ * @param v The value.\n+ * @return The instance.\n+ */\n+ protected static final T ofValue(T[] values,\n+ UndefinedValueConstructor constr, int v) {\n+ for (T e : values) {\n+ if (e.value() == v) {\n+ return e;\n+ }\n+ }\n+ return constr.newInstance(v);\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/NamedIntegerBitmask.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/NamedIntegerBitmask.java\nnew file mode 100644\nindex 000000000..cf197e123\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/NamedIntegerBitmask.java\n@@ -0,0 +1,206 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.Serializable;\n+import java.lang.reflect.Array;\n+import java.util.ArrayList;\n+import java.util.List;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.NonNullByDefault;\n+import org.eclipse.jdt.annotation.Nullable;\n+\n+/**\n+ * Describes a 32-bit bitmask that supports named flags.\n+ * \n+ * @param The subclass's type itself.\n+ * @author Christian Kohlschütter\n+ */\n+@NonNullByDefault\n+public abstract class NamedIntegerBitmask> implements\n+ Serializable {\n+ private static final long serialVersionUID = 1L;\n+\n+ /**\n+ * Name of the flag/flag set.\n+ */\n+ private final String name; // NOPMD.AvoidFieldNameMatchingMethodName\n+\n+ /**\n+ * Flag value.\n+ */\n+ private final int flags;\n+\n+ /**\n+ * Creates a new named flag.\n+ * \n+ * @param name The name of the flag / flag set.\n+ * @param flags The flag value.\n+ */\n+ protected NamedIntegerBitmask(@Nullable String name, int flags) {\n+ this.name = name == null ? \"UNDEFINED\" : name;\n+ this.flags = flags;\n+ }\n+\n+ /**\n+ * Returns the name of the flag / flag set.\n+ * \n+ * @return The name.\n+ */\n+ public final String name() {\n+ return name;\n+ }\n+\n+ /**\n+ * Returns the value of the flag / flag set.\n+ * \n+ * @return The value.\n+ */\n+ public final int value() {\n+ return flags;\n+ }\n+\n+ /**\n+ * Checks if the given flag is set.\n+ * \n+ * @param flag The flag to check.\n+ * @return {@code true} iff set.\n+ */\n+ public final boolean hasFlag(T flag) {\n+ int v = flag.value();\n+ return (this.flags & v) == v;\n+ }\n+\n+ @Override\n+ public final String toString() {\n+ return getClass().getName() + \"(\" + name() + \":\" + value() + \")\";\n+ }\n+\n+ /**\n+ * Combines two flags / flag sets (use this to implement\n+ * {@link #combineWith(NamedIntegerBitmask)}).\n+ * \n+ * @param allFlags The array of all defined flags, expected \"none\".\n+ * @param flagsNone The \"none\" flag set.\n+ * @param constr The constructor.\n+ * @param other The other flag / flag set to merge.\n+ * @return An instance combining both.\n+ */\n+ @SuppressWarnings(\"PMD.ShortMethodName\")\n+ protected final T combineWith(T[] allFlags, T flagsNone, Constructor constr, T other) {\n+ return resolve(allFlags, flagsNone, constr, value() | other.value());\n+ }\n+\n+ /**\n+ * Combines two flags / flag sets.\n+ * \n+ * @param other The other flag / flag set.\n+ * @return An instance combining both.\n+ */\n+ @SuppressWarnings(\"PMD.ShortMethodName\")\n+ public abstract T combineWith(T other);\n+\n+ /**\n+ * Creates a new instance.\n+ * \n+ * @param This type.\n+ */\n+ @FunctionalInterface\n+ protected interface Constructor> {\n+ /**\n+ * Creates a new instance.\n+ * \n+ * @param name The name.\n+ * @param flags The flag value.\n+ * @return The instance.\n+ */\n+ T newInstance(@Nullable String name, int flags);\n+ }\n+\n+ /**\n+ * Returns a {@link NamedIntegerBitmask} instance given a flag value.\n+ * \n+ * @param The subclass's type itself.\n+ * @param allFlags The array of all defined flags, expected \"none\".\n+ * @param flagsNone The \"none\" flag set.\n+ * @param constr The constructor.\n+ * @param v The flag value.\n+ * @return An instance representing the flag value.\n+ */\n+ @SuppressWarnings({\"null\", \"unchecked\"})\n+ protected static final > T resolve(T[] allFlags, T flagsNone,\n+ Constructor constr, int v) {\n+ if (v == 0) {\n+ return flagsNone;\n+ }\n+\n+ List flags = new ArrayList<>();\n+ for (T flag : allFlags) {\n+ int val = flag.value();\n+ if (val == v) {\n+ return flag;\n+ }\n+ if ((v & val) == val) {\n+ flags.add(flag);\n+ }\n+ }\n+\n+ return resolve(allFlags, flagsNone, constr, flags.toArray((T[]) Array.newInstance(flagsNone\n+ .getClass(), flags.size())));\n+ }\n+\n+ /**\n+ * Returns a {@link NamedIntegerBitmask} instance given a series of flags.\n+ * \n+ * @param The subclass's type itself.\n+ * @param allFlags The array of all defined flags, expected \"none\".\n+ * @param flagsNone The \"none\" flag set.\n+ * @param constr The constructor.\n+ * @param setFlags The flags to set, potentially empty.\n+ * @return An instance representing the flag values.\n+ */\n+ protected static final > T resolve(T[] allFlags, T flagsNone,\n+ Constructor constr, @NonNull T[] setFlags) {\n+ int flags = 0;\n+ int numFlagsSet = 0;\n+ @Nullable\n+ T lastFlagSet = null;\n+ if (setFlags != null) {\n+ for (T flag : setFlags) {\n+ flags |= flag.value();\n+ lastFlagSet = flag;\n+ numFlagsSet++;\n+ }\n+ }\n+ if (flags == 0) {\n+ return flagsNone;\n+ } else if (numFlagsSet == 1 && lastFlagSet != null) {\n+ return lastFlagSet;\n+ }\n+\n+ StringBuilder sb = new StringBuilder();\n+ for (T flag : setFlags) {\n+ sb.append(flag.name());\n+ sb.append(',');\n+ }\n+ sb.setLength(sb.length() - 1);\n+\n+ return constr.newInstance(sb.toString(), flags);\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeLibraryLoader.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeLibraryLoader.java\nindex 010525955..a83b46dc4 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeLibraryLoader.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeLibraryLoader.java\n@@ -25,6 +25,7 @@ import java.io.IOException;\n import java.io.InputStream;\n import java.io.OutputStream;\n import java.util.ArrayList;\n+import java.util.Collections;\n import java.util.List;\n import java.util.Objects;\n import java.util.Properties;\n@@ -33,13 +34,14 @@ import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n @SuppressFBWarnings(\"RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE\")\n final class NativeLibraryLoader implements Closeable {\n+ private static final String PROP_LIBRARY_DISABLE = \"org.newsclub.net.unix.library.disable\";\n private static final String PROP_LIBRARY_OVERRIDE = \"org.newsclub.net.unix.library.override\";\n- private static final String PROP_LIBRARY_OVERRIDE_FALSE =\n+ private static final String PROP_LIBRARY_OVERRIDE_FORCE =\n \"org.newsclub.net.unix.library.override.force\";\n private static final String PROP_LIBRARY_TMPDIR = \"org.newsclub.net.unix.library.tmpdir\";\n \n private static final File TEMP_DIR;\n- private static final String ARCHITECTURE_AND_OS = architectureAndOS();\n+ private static final List ARCHITECTURE_AND_OS = architectureAndOS();\n private static final String LIBRARY_NAME = \"junixsocket-native\";\n \n private static boolean loaded = false;\n@@ -52,6 +54,15 @@ final class NativeLibraryLoader implements Closeable {\n NativeLibraryLoader() {\n }\n \n+ /**\n+ * Returns the temporary directory where the native library is extracted to; debugging only.\n+ * \n+ * @return The temporary directory.\n+ */\n+ static File tempDir() {\n+ return TEMP_DIR;\n+ }\n+\n private List tryProviderClass(String providerClassname, String artifactName)\n throws IOException, ClassNotFoundException {\n Class providerClass = Class.forName(providerClassname);\n@@ -64,7 +75,7 @@ final class NativeLibraryLoader implements Closeable {\n \n public static String getJunixsocketVersion() throws IOException {\n // NOTE: This can't easily be tested from within the junixsocket-common Maven build\n- return getArtifactVersion(AFUNIXSocket.class, \"junixsocket-common\");\n+ return getArtifactVersion(AFSocket.class, \"junixsocket-common\");\n }\n \n private static String getArtifactVersion(Class providerClass, String... artifactNames)\n@@ -95,6 +106,7 @@ final class NativeLibraryLoader implements Closeable {\n this.libraryNameAndVersion = libraryNameAndVersion;\n }\n \n+ @SuppressFBWarnings(\"THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION\")\n abstract String load() throws Exception;\n \n @Override\n@@ -112,6 +124,7 @@ final class NativeLibraryLoader implements Closeable {\n }\n \n @Override\n+ @SuppressFBWarnings(\"THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION\")\n String load() throws Exception, LinkageError {\n if (libraryNameAndVersion != null) {\n System.loadLibrary(libraryNameAndVersion);\n@@ -187,10 +200,16 @@ final class NativeLibraryLoader implements Closeable {\n }\n \n private synchronized void setLoaded(String library) {\n+ setLoaded0(library);\n+ }\n+\n+ @SuppressFBWarnings(\"THROWS_METHOD_THROWS_RUNTIMEEXCEPTION\")\n+ private static synchronized void setLoaded0(String library) {\n if (!loaded) {\n loaded = true;\n- AFUNIXSocket.loadedLibrary = library;\n+ AFSocket.loadedLibrary = library;\n try {\n+ NativeUnixSocket.initPre();\n NativeUnixSocket.init();\n } catch (RuntimeException e) {\n throw e;\n@@ -202,13 +221,20 @@ final class NativeLibraryLoader implements Closeable {\n \n private Throwable loadLibraryOverride() {\n String libraryOverride = System.getProperty(PROP_LIBRARY_OVERRIDE, \"\");\n+ String libraryOverrideForce = System.getProperty(PROP_LIBRARY_OVERRIDE_FORCE, \"false\");\n+ \n+ if (libraryOverride.isEmpty() && libraryOverrideForce.startsWith(\"/\")) {\n+ libraryOverride = libraryOverrideForce;\n+ libraryOverrideForce = \"true\";\n+ }\n+ \n if (!libraryOverride.isEmpty()) {\n try {\n System.load(libraryOverride);\n setLoaded(libraryOverride);\n return null;\n } catch (Exception | LinkageError e) {\n- if (Boolean.valueOf(System.getProperty(PROP_LIBRARY_OVERRIDE_FALSE, \"false\"))) {\n+ if (Boolean.valueOf(libraryOverrideForce)) {\n throw e;\n }\n return e;\n@@ -229,6 +255,7 @@ final class NativeLibraryLoader implements Closeable {\n }\n \n // NOPMD\n+ @SuppressWarnings(\"null\")\n public synchronized void loadLibrary() {\n synchronized (loadLibrarySyncMonitor()) { // NOPMD We want to lock this class' classloader.\n if (loaded) {\n@@ -236,6 +263,18 @@ final class NativeLibraryLoader implements Closeable {\n return;\n }\n \n+ // set -Dorg.newsclub.net.unix.library.override.force=provided to assume that\n+ // we already have loaded the library via System.load, etc.\n+ if (\"provided\".equals(System.getProperty(PROP_LIBRARY_OVERRIDE_FORCE, \"\"))) {\n+ setLoaded(\"provided\");\n+ return;\n+ }\n+\n+ if (Boolean.valueOf(System.getProperty(PROP_LIBRARY_DISABLE, \"false\"))) {\n+ throw initCantLoadLibraryError(Collections.singletonList(new UnsupportedOperationException(\n+ \"junixsocket disabled by System.property \" + PROP_LIBRARY_DISABLE)));\n+ }\n+\n List suppressedThrowables = new ArrayList<>();\n Throwable ex = loadLibraryOverride();\n if (ex == null) {\n@@ -280,8 +319,10 @@ final class NativeLibraryLoader implements Closeable {\n }\n \n UnsatisfiedLinkError e = new UnsatisfiedLinkError(message);\n- for (Throwable suppressed : suppressedThrowables) {\n- e.addSuppressed(suppressed);\n+ if (suppressedThrowables != null) {\n+ for (Throwable suppressed : suppressedThrowables) {\n+ e.addSuppressed(suppressed);\n+ }\n }\n throw e;\n }\n@@ -310,36 +351,53 @@ final class NativeLibraryLoader implements Closeable {\n return candidates;\n }\n \n- private static String architectureAndOS() {\n- return System.getProperty(\"os.arch\") + \"-\" + System.getProperty(\"os.name\").replaceAll(\" \", \"\");\n+ private static List architectureAndOS() {\n+ String arch = System.getProperty(\"os.arch\", \"UnknownArch\").replaceAll(\"[ /\\\\\\\\'\\\";:\\\\$]\", \"\");\n+ String osName = System.getProperty(\"os.name\", \"UnknownOS\").replaceAll(\"[ /\\\\\\\\'\\\";:\\\\$]\", \"\");\n+\n+ List list = new ArrayList<>();\n+ list.add(arch + \"-\" + osName);\n+ if (osName.startsWith(\"Windows\") && !\"Windows10\".equals(osName)) {\n+ list.add(arch + \"-\" + \"Windows10\");\n+ }\n+\n+ return list;\n }\n \n private List findLibraryCandidates(String artifactName,\n String libraryNameAndVersion, Class providerClass) {\n String mappedName = System.mapLibraryName(libraryNameAndVersion);\n \n- List list = new ArrayList<>();\n- for (String compiler : new String[] {\n- \"gpp\", \"g++\", \"linker\", \"clang\", \"gcc\", \"cc\", \"CC\", \"icpc\", \"icc\", \"xlC\", \"xlC_r\", \"msvc\",\n- \"icl\", \"ecpc\", \"ecc\"}) {\n- String path = \"/lib/\" + ARCHITECTURE_AND_OS + \"-\" + compiler + \"/jni/\" + mappedName;\n-\n- InputStream in;\n+ String[] prefixes = mappedName.startsWith(\"lib\") ? new String[] {\"\"} : new String[] {\"\", \"lib\"};\n \n- in = providerClass.getResourceAsStream(path);\n- if (in != null) {\n- list.add(new ClasspathLibraryCandidate(artifactName, libraryNameAndVersion, path, in));\n- }\n+ List list = new ArrayList<>();\n+ for (String archOs : ARCHITECTURE_AND_OS) {\n+ for (String compiler : new String[] {\"clang\", \"gcc\"\n+ // \"gpp\", \"g++\", \"linker\", \"clang\", \"gcc\", \"cc\", \"CC\", \"icpc\", \"icc\", \"xlC\", \"xlC_r\",\n+ // \"msvc\",\n+ // \"icl\", \"ecpc\", \"ecc\"\n+ }) {\n+ for (String prefix : prefixes) {\n+ String path = \"/lib/\" + archOs + \"-\" + compiler + \"/jni/\" + prefix + mappedName;\n+\n+ InputStream in;\n+\n+ in = providerClass.getResourceAsStream(path);\n+ if (in != null) {\n+ list.add(new ClasspathLibraryCandidate(artifactName, libraryNameAndVersion, path, in));\n+ }\n \n- // NOTE: we have to try .nodeps version _after_ trying the properly linked one.\n- // While the former may throw an UnsatisfiedLinkError, this one may just terminate the VM\n- // with a \"symbol lookup error\"\n- String nodepsPath = nodepsPath(path);\n- if (nodepsPath != null) {\n- in = providerClass.getResourceAsStream(nodepsPath);\n- if (in != null) {\n- list.add(new ClasspathLibraryCandidate(artifactName, libraryNameAndVersion, nodepsPath,\n- in));\n+ // NOTE: we have to try .nodeps version _after_ trying the properly linked one.\n+ // While the former may throw an UnsatisfiedLinkError, this one may just terminate the VM\n+ // with a \"symbol lookup error\"\n+ String nodepsPath = nodepsPath(path);\n+ if (nodepsPath != null) {\n+ in = providerClass.getResourceAsStream(nodepsPath);\n+ if (in != null) {\n+ list.add(new ClasspathLibraryCandidate(artifactName, libraryNameAndVersion,\n+ nodepsPath, in));\n+ }\n+ }\n }\n }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeUnixSocket.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeUnixSocket.java\nindex 2b6eaf74e..b85a90815 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeUnixSocket.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/NativeUnixSocket.java\n@@ -20,14 +20,19 @@ package org.newsclub.net.unix;\n import java.io.Closeable;\n import java.io.FileDescriptor;\n import java.io.IOException;\n+import java.lang.ProcessBuilder.Redirect;\n import java.net.ServerSocket;\n import java.net.Socket;\n+import java.net.SocketAddress;\n import java.net.SocketException;\n import java.nio.ByteBuffer;\n+import java.nio.channels.SelectionKey;\n+import java.nio.channels.spi.AbstractSelectableChannel;\n \n-import org.newsclub.net.unix.AFUNIXSelector.PollFd;\n+import org.newsclub.net.unix.AFSelector.PollFd;\n \n import com.kohlschutter.annotations.compiletime.ExcludeFromCodeCoverageGeneratedReport;\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n /**\n * JNI connector to native JNI C code.\n@@ -37,20 +42,34 @@ import com.kohlschutter.annotations.compiletime.ExcludeFromCodeCoverageGenerated\n final class NativeUnixSocket {\n private static boolean loaded;\n \n+ static final int DOMAIN_UNIX = 1;\n+ static final int DOMAIN_TIPC = 30;\n+\n static final int SOCK_STREAM = 1;\n static final int SOCK_DGRAM = 2;\n+ static final int SOCK_RDM = 4;\n static final int SOCK_SEQPACKET = 5;\n \n static final int OPT_LOOKUP_SENDER = 1;\n static final int OPT_PEEK = 2;\n static final int OPT_NON_BLOCKING = 4;\n+\n+ /**\n+ * Indicator that the handle isn't referring to a socket but some other file descriptor.\n+ */\n static final int OPT_NON_SOCKET = 8;\n \n+ static final int OPT_DGRAM_MODE = 16;\n+\n+ static final int BIND_OPT_REUSE = 1;\n+\n static final int SOCKETSTATUS_INVALID = -1;\n static final int SOCKETSTATUS_UNKNOWN = 0;\n static final int SOCKETSTATUS_BOUND = 1;\n static final int SOCKETSTATUS_CONNECTED = 2;\n \n+ private static Throwable initError = null;\n+\n @ExcludeFromCodeCoverageGeneratedReport\n private NativeUnixSocket() {\n throw new UnsupportedOperationException(\"No instances\");\n@@ -59,33 +78,74 @@ final class NativeUnixSocket {\n static {\n try (NativeLibraryLoader nll = new NativeLibraryLoader()) {\n nll.loadLibrary();\n+ loaded = true;\n+ } catch (RuntimeException | Error e) {\n+ initError = e;\n+ e.printStackTrace(); // keep\n }\n- loaded = true;\n+\n+ AFAddressFamily.registerAddressFamily(\"un\", NativeUnixSocket.DOMAIN_UNIX,\n+ \"org.newsclub.net.unix.AFUNIXSocketAddress\");\n+ AFAddressFamily.registerAddressFamily(\"tipc\", NativeUnixSocket.DOMAIN_TIPC,\n+ \"org.newsclub.net.unix.AFTIPCSocketAddress\");\n }\n \n static boolean isLoaded() {\n return loaded;\n }\n \n- static void checkSupported() {\n+ static void ensureSupported() throws UnsupportedOperationException {\n+ if (!isLoaded()) {\n+ throw unsupportedException();\n+ }\n+ }\n+\n+ static UnsupportedOperationException unsupportedException() {\n+ if (!isLoaded()) {\n+ return (UnsupportedOperationException) new UnsupportedOperationException(\n+ \"junixsocket is not supported on this platform\").initCause(initError);\n+ } else {\n+ return null;\n+ }\n+ }\n+\n+ static Throwable retrieveInitError() {\n+ return initError;\n }\n \n+ static void initPre() {\n+ // in some environments, JNI FindClass won't find these classes unless we resolve them first\n+ tryResolveClass(AbstractSelectableChannel.class.getName());\n+ tryResolveClass(\"java.lang.ProcessBuilder$RedirectPipeImpl\");\n+ }\n+\n+ private static void tryResolveClass(String className) {\n+ try {\n+ Class.forName(className);\n+ } catch (Exception e) {\n+ // ignore\n+ }\n+ }\n+\n+ @SuppressFBWarnings(\"THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION\")\n static native void init() throws Exception;\n \n+ @SuppressFBWarnings(\"THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION\")\n static native void destroy() throws Exception;\n \n static native int capabilities();\n \n- static native byte[] sockname(FileDescriptor fd, boolean peer);\n+ static native byte[] sockname(int domain, FileDescriptor fd, boolean peer);\n \n- static native long bind(byte[] socketAddr, FileDescriptor fd, int options) throws IOException;\n+ static native long bind(ByteBuffer sockaddr, int sockaddrLen, FileDescriptor fd, int options)\n+ throws IOException;\n \n static native void listen(FileDescriptor fd, int backlog) throws IOException;\n \n- static native boolean accept(byte[] socketAddr, FileDescriptor fdServer, FileDescriptor fd,\n- long inode, int timeout) throws IOException;\n+ static native boolean accept(ByteBuffer sockaddr, int sockaddrLen, FileDescriptor fdServer,\n+ FileDescriptor fd, long inode, int timeout) throws IOException;\n \n- static native boolean connect(byte[] socketAddr, FileDescriptor fd, long inode)\n+ static native boolean connect(ByteBuffer sockaddr, int sockaddrLen, FileDescriptor fd, long inode)\n throws IOException;\n \n static native boolean finishConnect(FileDescriptor fd) throws IOException;\n@@ -97,32 +157,34 @@ final class NativeUnixSocket {\n static native Class primaryType(FileDescriptor fd) throws IOException;\n \n /**\n- * Reads data from an {@link AFUNIXSocketImpl}.\n+ * Reads data from an {@link AFSocketImpl}.\n * \n * @param fd The corresponding file descriptor.\n * @param buf The buffer to read into, or {@code null} if a single byte should be read.\n * @param off The buffer offset.\n * @param len The maximum number of bytes to read. Must be 1 if {@code buf} is {@code null}.\n+ * @param options Options.\n * @param ancillaryDataSupport The ancillary data support instance, or {@code null}.\n * @return The number of bytes read, -1 if nothing could be read, or the byte itself iff\n * {@code buf} was {@code null}.\n * @throws IOException upon error.\n */\n- static native int read(FileDescriptor fd, byte[] buf, int off, int len,\n+ static native int read(FileDescriptor fd, byte[] buf, int off, int len, int options,\n AncillaryDataSupport ancillaryDataSupport, int timeoutMillis) throws IOException;\n \n /**\n- * Writes data to an {@link AFUNIXSocketImpl}.\n+ * Writes data to an {@link AFSocketImpl}.\n * \n * @param fd The corresponding file descriptor.\n * @param buf The buffer to write from, or {@code null} if a single byte should be written.\n * @param off The buffer offset, or the byte to write if {@code buf} is {@code null}.\n * @param len The number of bytes to write. Must be 1 if {@code buf} is {@code null}.\n+ * @param options Options.\n * @param ancillaryDataSupport The ancillary data support instance, or {@code null}.\n * @return The number of bytes written (which could be 0).\n * @throws IOException upon error.\n */\n- static native int write(FileDescriptor fd, byte[] buf, int off, int len,\n+ static native int write(FileDescriptor fd, byte[] buf, int off, int len, int options,\n AncillaryDataSupport ancillaryDataSupport) throws IOException;\n \n static native int receive(FileDescriptor fd, ByteBuffer directBuffer, int offset, int length,\n@@ -130,8 +192,8 @@ final class NativeUnixSocket {\n int timeoutMillis) throws IOException;\n \n static native int send(FileDescriptor fd, ByteBuffer directBuffer, int offset, int length,\n- ByteBuffer directSocketAddress, int options, AncillaryDataSupport ancillaryDataSupport)\n- throws IOException;\n+ ByteBuffer directSocketAddress, int addrLen, int options,\n+ AncillaryDataSupport ancillaryDataSupport) throws IOException;\n \n static native void close(FileDescriptor fd) throws IOException;\n \n@@ -142,17 +204,23 @@ final class NativeUnixSocket {\n static native void setSocketOptionInt(FileDescriptor fd, int optionId, int value)\n throws IOException;\n \n- static native int available(FileDescriptor fd) throws IOException;\n+ static native T getSocketOption(FileDescriptor fd, int level, int optionName,\n+ Class valueType) throws IOException;\n+\n+ static native void setSocketOption(FileDescriptor fd, int level, int optionName, Object value)\n+ throws IOException;\n+\n+ static native int available(FileDescriptor fd, ByteBuffer buf) throws IOException;\n \n static native AFUNIXSocketCredentials peerCredentials(FileDescriptor fd,\n AFUNIXSocketCredentials creds) throws IOException;\n \n- static native void initServerImpl(ServerSocket serverSocket, AFUNIXSocketImpl impl)\n+ static native void initServerImpl(ServerSocket serverSocket, AFSocketImpl impl)\n throws IOException;\n \n- static native void createSocket(FileDescriptor fdesc, int type) throws IOException;\n+ static native void createSocket(FileDescriptor fdesc, int domain, int type) throws IOException;\n \n- static native void setPort(AFUNIXSocketAddress addr, int port);\n+ static native void setPort(SocketAddress addr, int port);\n \n static native void initFD(FileDescriptor fdesc, int fd) throws IOException;\n \n@@ -165,13 +233,16 @@ final class NativeUnixSocket {\n \n static native int maxAddressLength();\n \n- static native int sockAddrUnLength();\n+ static native int sockAddrLength(int domain);\n \n- static native byte[] sockAddrUnToBytes(ByteBuffer sockAddrDirect);\n+ static native int ancillaryBufMinLen();\n \n- static native void bytesToSockAddrUn(ByteBuffer sockAddrDirectBuf, byte[] address);\n+ static native byte[] sockAddrToBytes(int domain, ByteBuffer sockAddrDirect);\n \n- static void setPort1(AFUNIXSocketAddress addr, int port) throws SocketException {\n+ static native int bytesToSockAddr(int domain, ByteBuffer sockAddrDirectBuf, byte[] address);\n+\n+ @SuppressFBWarnings(\"THROWS_METHOD_THROWS_RUNTIMEEXCEPTION\")\n+ static void setPort1(SocketAddress addr, int port) throws SocketException {\n if (port < 0) {\n throw new IllegalArgumentException(\"port out of range:\" + port);\n }\n@@ -190,9 +261,23 @@ final class NativeUnixSocket {\n static native boolean initPipe(FileDescriptor source, FileDescriptor sink, boolean selectable)\n throws IOException;\n \n- static native int poll(PollFd pollFd, int timeout);\n+ static native int poll(PollFd pollFd, int timeout) throws IOException;\n \n static native void configureBlocking(FileDescriptor fd, boolean blocking) throws IOException;\n \n- static native void socketPair(int type, FileDescriptor fd, FileDescriptor fd2);\n+ static native void socketPair(int domain, int type, FileDescriptor fd, FileDescriptor fd2);\n+\n+ static native Redirect initRedirect(FileDescriptor fd);\n+\n+ static native void deregisterSelectionKey(AbstractSelectableChannel chann, SelectionKey key);\n+\n+ static native byte[] tipcGetNodeId(int peer) throws IOException;\n+\n+ static native byte[] tipcGetLinkName(int peer, int bearerId) throws IOException;\n+\n+ static native int sockAddrNativeDataOffset();\n+\n+ static native int sockAddrNativeFamilyOffset();\n+\n+ static native int sockTypeToNative(int type) throws IOException;\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/RAFChannelProvider.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/RAFChannelProvider.java\nindex 9acb6dde0..729f9b5f1 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/RAFChannelProvider.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/RAFChannelProvider.java\n@@ -54,6 +54,9 @@ final class RAFChannelProvider extends RandomAccessFile implements FileDescripto\n }\n }\n tempPath.deleteOnExit();\n+\n+ NativeUnixSocket.ensureSupported();\n+\n this.fdObj = fdObj;\n \n FileDescriptor rafFdObj = getFD();\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/SentinelSocketAddress.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/SentinelSocketAddress.java\nnew file mode 100644\nindex 000000000..6fa708234\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/SentinelSocketAddress.java\n@@ -0,0 +1,40 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.File;\n+import java.io.FileNotFoundException;\n+\n+final class SentinelSocketAddress extends AFSocketAddress {\n+ private static final long serialVersionUID = 1L;\n+\n+ @SuppressWarnings(\"null\")\n+ SentinelSocketAddress(int port) {\n+ super(SentinelSocketAddress.class, port);\n+ }\n+\n+ @Override\n+ public boolean hasFilename() {\n+ return false;\n+ }\n+\n+ @Override\n+ public File getFile() throws FileNotFoundException {\n+ throw new FileNotFoundException();\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/SocketAddressFilter.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/SocketAddressFilter.java\nnew file mode 100644\nindex 000000000..298e7811c\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/SocketAddressFilter.java\n@@ -0,0 +1,40 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.IOException;\n+import java.net.SocketAddress;\n+\n+/**\n+ * A filter that takes a {@link SocketAddress}, and potentially changes it, or throws an exception\n+ * if certain criteria are met.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+@FunctionalInterface\n+public interface SocketAddressFilter {\n+\n+ /**\n+ * Applies the filter on the given address.\n+ * \n+ * @param address The address.\n+ * @return The address itself or a changed address.\n+ * @throws IOException on error or if a certain error condition is desired.\n+ */\n+ SocketAddress apply(SocketAddress address) throws IOException;\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/SocketClosedException.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/SocketClosedException.java\nnew file mode 100644\nindex 000000000..e8992cd6b\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/SocketClosedException.java\n@@ -0,0 +1,32 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.net.SocketException;\n+\n+final class SocketClosedException extends SocketException {\n+ private static final long serialVersionUID = 1L;\n+\n+ public SocketClosedException() {\n+ super();\n+ }\n+\n+ public SocketClosedException(String msg) {\n+ super(msg);\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/SocketImplShim.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/SocketImplShim.java\nindex 787d03850..fd11f163a 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/SocketImplShim.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/SocketImplShim.java\n@@ -17,10 +17,7 @@\n */\n package org.newsclub.net.unix;\n \n-import java.io.IOException;\n import java.net.SocketImpl;\n-import java.net.SocketOption;\n-import java.util.Set;\n \n /**\n * A shim that is filled with Java version-specific overrides. This variant is for Java 9 and above.\n@@ -28,34 +25,7 @@ import java.util.Set;\n * @author Christian Kohlschütter\n */\n abstract class SocketImplShim extends SocketImpl {\n-\n protected SocketImplShim() {\n super();\n }\n-\n- @Override\n- protected void setOption(SocketOption name, T value) throws IOException {\n- Integer optionId = SocketOptionsMapper.resolve(name);\n- if (optionId == null) {\n- super.setOption(name, value);\n- } else {\n- setOption(optionId, value);\n- }\n- }\n-\n- @SuppressWarnings(\"unchecked\")\n- @Override\n- protected T getOption(SocketOption name) throws IOException {\n- Integer optionId = SocketOptionsMapper.resolve(name);\n- if (optionId == null) {\n- return super.getOption(name);\n- } else {\n- return (T) getOption(optionId);\n- }\n- }\n-\n- @Override\n- protected Set> supportedOptions() {\n- return SocketOptionsMapper.SUPPORTED_SOCKET_OPTIONS;\n- }\n }\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/domain/package-info.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/domain/package-info.java\nnew file mode 100644\nindex 000000000..886bf116b\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/domain/package-info.java\n@@ -0,0 +1,4 @@\n+/**\n+ * Test-only code (see src/test/java).\n+ */\n+package org.newsclub.net.unix.domain;\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/java/package-info.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/java/package-info.java\nnew file mode 100644\nindex 000000000..b588d954d\n--- /dev/null\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/java/package-info.java\n@@ -0,0 +1,4 @@\n+/**\n+ * Test-only code (see src/test/java).\n+ */\n+package org.newsclub.net.unix.java;\ndiff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/package-info.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/package-info.java\nindex 80b50caf3..b148e1a16 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/package-info.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/package-info.java\n@@ -1,4 +1,4 @@\n /**\n- * The actual AF_UNIX Socket implementation.\n+ * The junixsocket base implementation, including support for AF_UNIX sockets.\n */\n package org.newsclub.net.unix;\ndiff --git a/junixsocket-common/src/main/java8/org/newsclub/net/unix/AFInputStream.java b/junixsocket-common/src/main/java8/org/newsclub/net/unix/AFInputStream.java\nnew file mode 100644\nindex 000000000..bd11450b5\n--- /dev/null\n+++ b/junixsocket-common/src/main/java8/org/newsclub/net/unix/AFInputStream.java\n@@ -0,0 +1,29 @@\n+package org.newsclub.net.unix;\n+\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.io.OutputStream;\n+import java.util.Objects;\n+\n+public abstract class AFInputStream extends InputStream implements FileDescriptorAccess {\n+ private static final int DEFAULT_BUFFER_SIZE = 8192;\n+\n+ AFInputStream() {\n+ super();\n+ }\n+\n+ /**\n+ * Backport Java 9 functionality\n+ */\n+ public long transferTo(OutputStream out) throws IOException {\n+ Objects.requireNonNull(out, \"out\");\n+ long transferred = 0;\n+ byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];\n+ int read;\n+ while ((read = this.read(buffer, 0, DEFAULT_BUFFER_SIZE)) >= 0) {\n+ out.write(buffer, 0, read);\n+ transferred += read;\n+ }\n+ return transferred;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java8/org/newsclub/net/unix/AFOutputStream.java b/junixsocket-common/src/main/java8/org/newsclub/net/unix/AFOutputStream.java\nnew file mode 100644\nindex 000000000..4523aa88f\n--- /dev/null\n+++ b/junixsocket-common/src/main/java8/org/newsclub/net/unix/AFOutputStream.java\n@@ -0,0 +1,43 @@\n+package org.newsclub.net.unix;\n+\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.io.OutputStream;\n+import java.util.Objects;\n+\n+public abstract class AFOutputStream extends OutputStream implements FileDescriptorAccess {\n+ private static final int DEFAULT_BUFFER_SIZE = 8192;\n+\n+ AFOutputStream() {\n+ super();\n+ }\n+\n+ /**\n+ * Reads all bytes from the given input stream and writes the bytes to this output stream in the\n+ * order that they are read. On return, this input stream will be at end of stream. This method\n+ * does not close either stream.\n+ * \n+ * This method effectively is the reverse notation of\n+ * {@link InputStream#transferTo(OutputStream)}, which may or may not be optimized for\n+ * {@link AFSocket}s.\n+ * \n+ * @param in The {@link InputStream} to transfer from.\n+ * @return The number of bytes transferred.\n+ * @throws IOException on error.\n+ */\n+ public long transferFrom(InputStream in) throws IOException {\n+ Objects.requireNonNull(in, \"in\");\n+ if (in instanceof AFInputStream) {\n+ return ((AFInputStream) in).transferTo(this);\n+ }\n+\n+ long transferred = 0;\n+ byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];\n+ int read;\n+ while ((read = in.read(buffer, 0, DEFAULT_BUFFER_SIZE)) >= 0) {\n+ this.write(buffer, 0, read);\n+ transferred += read;\n+ }\n+ return transferred;\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java8/org/newsclub/net/unix/DatagramSocketImplShim.java b/junixsocket-common/src/main/java8/org/newsclub/net/unix/DatagramSocketImplShim.java\nnew file mode 100644\nindex 000000000..3bdb3ac43\n--- /dev/null\n+++ b/junixsocket-common/src/main/java8/org/newsclub/net/unix/DatagramSocketImplShim.java\n@@ -0,0 +1,24 @@\n+package org.newsclub.net.unix;\n+\n+import java.net.DatagramSocketImpl;\n+\n+/**\n+ * A shim that is filled with Java version-specific overrides. This variant is for Java 7 and 8.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+abstract class DatagramSocketImplShim extends DatagramSocketImpl {\n+ protected DatagramSocketImplShim() {\n+ super();\n+ }\n+\n+ @SuppressWarnings(\"all\")\n+ @Override\n+ protected final void finalize() {\n+ try {\n+ close();\n+ } catch (Exception e) {\n+ // nothing that can be done here\n+ }\n+ }\n+}\ndiff --git a/junixsocket-common/src/main/java8/org/newsclub/net/unix/SocketImplShim.java b/junixsocket-common/src/main/java8/org/newsclub/net/unix/SocketImplShim.java\nindex 8f80a77fc..d5e3d8963 100644\n--- a/junixsocket-common/src/main/java8/org/newsclub/net/unix/SocketImplShim.java\n+++ b/junixsocket-common/src/main/java8/org/newsclub/net/unix/SocketImplShim.java\n@@ -1,6 +1,10 @@\n package org.newsclub.net.unix;\n \n+import java.io.IOException;\n import java.net.SocketImpl;\n+import java.net.SocketOption;\n+import java.util.Collections;\n+import java.util.Set;\n \n /**\n * A shim that is filled with Java version-specific overrides. This variant is for Java 7 and 8.\n@@ -21,4 +25,16 @@ abstract class SocketImplShim extends SocketImpl {\n // nothing that can be done here\n }\n }\n+\n+ protected void setOption(SocketOption name, T value) throws IOException {\n+ throw new IOException(\"Unsupported option\");\n+ }\n+\n+ protected T getOption(SocketOption name) throws IOException {\n+ throw new IOException(\"Unsupported option\");\n+ }\n+\n+ protected Set> supportedOptions() {\n+ return Collections.emptySet();\n+ }\n }\ndiff --git a/junixsocket-core/pom.xml b/junixsocket-core/pom.xml\nindex 3228baffa..2c5a2972b 100644\n--- a/junixsocket-core/pom.xml\n+++ b/junixsocket-core/pom.xml\n@@ -9,7 +9,7 @@\n \n com.kohlschutter.junixsocket\n junixsocket-parent\n- 2.4.1-SNAPSHOT\n+ 2.5.0-SNAPSHOT\n ../pom.xml\n \n junixsocket-core\ndiff --git a/junixsocket-demo/pom.xml b/junixsocket-demo/pom.xml\nindex 6a9946bd9..94a9c053b 100644\n--- a/junixsocket-demo/pom.xml\n+++ b/junixsocket-demo/pom.xml\n@@ -8,7 +8,7 @@\n \n com.kohlschutter.junixsocket\n junixsocket-parent\n- 2.4.1-SNAPSHOT\n+ 2.5.0-SNAPSHOT\n ../pom.xml\n \n junixsocket-demo\n@@ -28,6 +28,11 @@\n ${project.version}\n pom\n
\n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-tipc\n+ ${project.version}\n+ \n \n com.kohlschutter.junixsocket\n junixsocket-mysql\n@@ -46,7 +51,7 @@\n \n mysql\n mysql-connector-java\n- 8.0.27\n+ 8.0.28\n \n \n \n- 2.4.1-SNAPSHOT\n+ 2.5.0-SNAPSHOT\n ../pom.xml\n \n junixsocket-native-common\n@@ -59,6 +59,8 @@\n \n **/*.dylib\n **/*.so\n+ **/*.a\n+ **/*.srvpgm\n **/*.dll\n META-INF/**/pom.properties\n \n@@ -211,6 +213,24 @@\n runtime\n true\n \n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-native\n+ ${project.version}\n+ nar\n+ ppc64-AIX-gcc-jni\n+ runtime\n+ true\n+ \n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-native\n+ ${project.version}\n+ nar\n+ ppc64-OS400-gcc-jni\n+ runtime\n+ true\n+ \n \n com.kohlschutter.junixsocket\n junixsocket-native\n@@ -238,6 +258,15 @@\n runtime\n true\n \n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-native\n+ ${project.version}\n+ nar\n+ aarch64-Windows10-clang-llvm-jni\n+ runtime\n+ true\n+ \n \n com.kohlschutter.junixsocket\n junixsocket-native\ndiff --git a/junixsocket-native-cross/pom.xml b/junixsocket-native-cross/pom.xml\nindex 2aa35e7dc..e04b92648 100644\n--- a/junixsocket-native-cross/pom.xml\n+++ b/junixsocket-native-cross/pom.xml\n@@ -9,7 +9,7 @@\n com.kohlschutter.junixsocket\n junixsocket-parent\n \n- 2.4.1-SNAPSHOT\n+ 2.5.0-SNAPSHOT\n ../pom.xml\n \n junixsocket-native-cross\n@@ -164,6 +164,37 @@\n \n \n \n+ \n+ crosscompile-aarch64-Windows10-clang\n+ \n+ run\n+ \n+ \n+ ${junixsocket.cross.disabled}\n+ true\n+ true\n+ \n+ clean\n+ install\n+ \n+ ${project.basedir}/../\n+ \n+ junixsocket-native\n+ \n+ \n+ llvm\n+ \n+ \n+ aarch64-Windows10-clang\n+ true\n+ ${project.build.directory}/junixsocket-native-aarch64-Windows10-clang-llvm\n+ aarch64-w64-mingw32\n+ dll\n+ aarch64-Windows10-clang-llvm-jni\n+ ${ignorant}\n+ \n+ \n+ \n \n crosscompile-x86_64-MacOSX-clang\n \n@@ -476,6 +507,69 @@\n \n \n \n+ \n+ crosscompile-ppc64-AIX-clang\n+ \n+ run\n+ \n+ \n+ ${junixsocket.cross.disabled}\n+ true\n+ true\n+ \n+ clean\n+ install\n+ \n+ ${project.basedir}/../\n+ \n+ junixsocket-native\n+ \n+ \n+ llvm\n+ \n+ \n+ ppc64-AIX-clang\n+ true\n+ ${project.build.directory}/junixsocket-native-ppc64-AIX-clang-llvm\n+ powerpc-ibm-aix7.2.0.0\n+ a\n+ ppc64-AIX-clang-llvm-jni\n+ ${ignorant}\n+ \n+ \n+ \n+ \n+ crosscompile-ppc64-OS400-clang\n+ \n+ run\n+ \n+ \n+ ${junixsocket.cross.disabled}\n+ true\n+ true\n+ \n+ clean\n+ install\n+ \n+ ${project.basedir}/../\n+ \n+ junixsocket-native\n+ \n+ \n+ llvm\n+ \n+ \n+ ppc64-OS400-clang\n+ true\n+ ${project.build.directory}/junixsocket-native-ppc64-OS400-clang-llvm\n+ powerpc-ibm-os400\n+ srvpgm\n+ lib\n+ ppc64-OS400-clang-llvm-jni\n+ ${ignorant}\n+ \n+ \n+ \n \n crosscompile-s390x-Linux-clang\n \n@@ -619,6 +713,22 @@\n false\n \n \n+ \n+ install-aarch64-Windows10-clang\n+ ${junixsocket.cross.install-phase}\n+ \n+ install-file\n+ \n+ \n+ ${project.build.directory}/junixsocket-native-aarch64-Windows10-clang-llvm/junixsocket-native-${project.version}-aarch64-Windows10-clang-jni.nar\n+ ${project.groupId}\n+ junixsocket-native\n+ ${project.version}\n+ nar\n+ aarch64-Windows10-clang-llvm-jni\n+ false\n+ \n+ \n \n install-x86_64-MacOSX-clang\n ${junixsocket.cross.install-phase}\n@@ -781,6 +891,38 @@\n false\n \n \n+ \n+ install-ppc64-AIX-clang\n+ ${junixsocket.cross.install-phase}\n+ \n+ install-file\n+ \n+ \n+ ${project.build.directory}/junixsocket-native-ppc64-AIX-clang-llvm/junixsocket-native-${project.version}-ppc64-AIX-clang-jni.nar\n+ ${project.groupId}\n+ junixsocket-native\n+ ${project.version}\n+ nar\n+ ppc64-AIX-gcc-jni\n+ false\n+ \n+ \n+ \n+ install-ppc64-OS400-clang\n+ ${junixsocket.cross.install-phase}\n+ \n+ install-file\n+ \n+ \n+ ${project.build.directory}/junixsocket-native-ppc64-OS400-clang-llvm/junixsocket-native-${project.version}-ppc64-OS400-clang-jni.nar\n+ ${project.groupId}\n+ junixsocket-native\n+ ${project.version}\n+ nar\n+ ppc64-OS400-gcc-jni\n+ false\n+ \n+ \n \n install-s390x-Linux-clang\n ${junixsocket.cross.install-phase}\ndiff --git a/junixsocket-native-custom/pom.xml b/junixsocket-native-custom/pom.xml\nindex 1e4b87e9a..80e5b883e 100644\n--- a/junixsocket-native-custom/pom.xml\n+++ b/junixsocket-native-custom/pom.xml\n@@ -9,7 +9,7 @@\n com.kohlschutter.junixsocket\n junixsocket-parent\n \n- 2.4.1-SNAPSHOT\n+ 2.5.0-SNAPSHOT\n ../pom.xml\n \n junixsocket-native-custom\ndiff --git a/junixsocket-native/crossclang/Xcode-Support/crossclang.sdk/SDKSettings.plist b/junixsocket-native/crossclang/Xcode-Support/crossclang.sdk/SDKSettings.plist\nindex 07cfd9637e92d21e6b592b2405aa5d72dbaa126d..c44fded3b84719c83f3619a44d069f743a3c317e 100644\nGIT binary patch\ndelta 150\nzcmX@Wcbsp6Du<1*t-XVB^pX|%F&OL)Qi?xikmbHO(GV5B_!>kWkf3XR(\njNwOKSS+d!&Ij}jg1+WFN\nzySQ?@xeE)~X?u7IdwEZu%({=!Z*maZI@eUzLe>h_YSup16|DPM@34Ml<6{$H(`7SZ\ndvt+Yovt{#U^JU9q00SmQ2+a@xrJ)pC0{|VGAAtY>\n\ndiff --git a/junixsocket-native/crossclang/Xcode-Support/install b/junixsocket-native/crossclang/Xcode-Support/install\nindex 67adc2beb..0ab351797 100755\n--- a/junixsocket-native/crossclang/Xcode-Support/install\n+++ b/junixsocket-native/crossclang/Xcode-Support/install\n@@ -26,14 +26,14 @@ fi\n \n for toolchain in $(ls -1 | grep '\\.xctoolchain$'); do\n echo Installing \"$toolchain\" ... \n- ( cd \"$toolchainsPath\" ; ln -s \"$pwd/$toolchain\" )\n+ ( cd \"$toolchainsPath\" ; ln -sf \"$pwd/$toolchain\" )\n done\n echo\n \n echo \"SDKs path: $sdksPath\"\n for sdk in $(ls -1 | grep '\\.sdk$'); do\n echo Installing \"$sdk\" ... \n- ( cd \"$sdksPath\" ; ln -s \"$pwd/$sdk\" )\n+ ( cd \"$sdksPath\" ; ln -sf \"$pwd/$sdk\" )\n done\n \n echo Done. Now please restart XCode\ndiff --git a/junixsocket-native/crossclang/bin/clang b/junixsocket-native/crossclang/bin/clang\nindex b15fe82ce..e8c9628a0 100755\n--- a/junixsocket-native/crossclang/bin/clang\n+++ b/junixsocket-native/crossclang/bin/clang\n@@ -31,7 +31,7 @@\n # set -x\n \n # Make sure to include all paths that may contain custom linkers etc.\n-PATH=\"$PATH\":/usr/bin:/opt/homebrew/bin:/usr/local/bin\n+PATH=\"$PATH\":/usr/bin:/opt/crossclang/local/bin:/opt/homebrew/bin:/usr/local/bin\n export PATH\n \n currentDir=$(cd \"$(dirname $0)\"; pwd)\n@@ -75,10 +75,16 @@ llvmName=llvm\n fileList=\n # ld64_sdk_version=10.9\n ld64_sdk_version=\n+hideUnknownWarningWarnings=0\n+\n+hasExportDynamic=0\n+ignoreExportDynamic=0\n \n skipGccArg=0\n analyze=0\n \n+extraVersionArgs=()\n+\n while [ $# -gt 0 ]; do\n v=\"$1\"\n shift\n@@ -107,6 +113,8 @@ while [ $# -gt 0 ]; do\n -Xcrossclang-use-gcc=* ) gccMode=1 ; compiler=\"${v#-Xcrossclang-use-gcc=}\" ; skipArg=1 ;;\n -Xcrossclang-output-strip-lib-prefix ) outputStripLibPrefix=1 ; skipArg=1 ;;\n -Xcrossclang-ld64-sdk-version ) ld64_sdk_version=\"$1\"; shift ; skipArg=1 ;;\n+ -Xcrossclang-hide-unknown-warning-warnings ) hideUnknownWarningWarnings=1 ; skipArg=1 ;;\n+ -Xcrossclang-ignore-export-dynamic) ignoreExportDynamic=1 ; skipArg=1 ;;\n # -index-store-path ) shift ; skipArg=1 ;; # if you're hitting this, set \"Enable Index-While-Building Functionality=No\" in Xcode build settings instead\n -filelist ) fileList=\"$1\" ; shift; skipArg=1 ;;\n -current_version ) shift ; skipArg=1 ;;\n@@ -141,6 +149,17 @@ while [ $# -gt 0 ]; do\n -l* ) libsArgs+=(\"$v\") ; skipArg=1 ;; # for compatibility, libs will be added last\n -target ) v=\"$1\"; target=\"$v\"; shift; skipArg=1 ;;\n c++ ) if [ \"$previous\" == \"-x\" ]; then looksLikeCPP=1; fi ;;\n+ -m64 ) extraVersionArgs+=(\"$v\") ;;\n+ -Xlinker )\n+ if [[ \"$1\" == \"-export_dynamic\" ]]; then\n+ hasExportDynamic=1\n+ elif [[ -n \"$1\" ]]; then\n+ clangArgs+=(\"-Xlinker\" \"$1\")\n+ gccArgs+=(\"-Xlinker\" \"$1\")\n+ fi\n+ shift\n+ skipArg=1\n+ ;;\n - ) hasFiles=1 ;;\n esac\n \n@@ -160,6 +179,11 @@ while [ $# -gt 0 ]; do\n previous=\"$v\"\n done\n \n+if [[ $hasExportDynamic -eq 1 && $ignoreExportDynamic -eq 0 ]]; then\n+ clangArgs+=(\"-Xlinker\" \"-export_dynamic\")\n+ gccArgs+=(\"-Xlinker\" \"-export_dynamic\")\n+fi\n+\n if [[ $analyze -gt 0 && $gccMode -gt 0 ]]; then\n # When using the static code analyzer, switch back to clang\n compiler=clang\n@@ -288,7 +312,7 @@ if [[ \"$target\" != \"unspecified\" ]]; then\n PATH=/usr/bin:$PATH\n fi\n \n- target=$($(which $compiler) --version | grep \"^Target: \" | head -n 1)\n+ target=$($(which $compiler) --version ${extraVersionArgs[@]} | grep \"^Target: \" | head -n 1)\n target=${target##* }\n if [ -z \"$target\" ]; then\n echo \"Could not determine target\" >&2\n@@ -335,7 +359,7 @@ if [[ \"$target\" != \"unspecified\" ]]; then\n echo \"Warning: crossclang has an incomplete configuration for target \\\"$target\\\" -- you need to run sync-target-sdk first!\" >&2\n fi\n elif [[ \"$defaultFallback\" -eq 0 ]]; then\n- platformTarget=$($(which $compiler) --version | grep \"^Target: \" | head -n 1)\n+ platformTarget=$($(which $compiler) --version ${extraVersionArgs[@]} | grep \"^Target: \" | head -n 1)\n platformTarget=${platformTarget##* }\n \n tryPlatformClang=0\n@@ -628,6 +652,8 @@ if [[ $withAndWithoutLC -eq 1 ]]; then\n \n \"$compilerBinary\" ${isystem_decls[@]} ${clangLinkerArgs[@]} ${wwoArgs[@]} ${clangArgs[@]} ${libsArgs[@]} && \\\n \"$compilerBinary\" ${isystem_decls[@]} ${clangLinkerArgs[@]} ${wwoArgsNoDeps[@]} ${clangArgsNoDeps[@]} ${libsArgs[@]}\n+elif [[ $hideUnknownWarningWarnings -eq 1 ]]; then\n+ exec \"$compilerBinary\" ${isystem_decls[@]} ${clangLinkerArgs[@]} ${output_args[@]} ${clangArgs[@]} ${libsArgs[@]} 2> >(grep -v -E \"unrecognized command-line option .* may have been intended to silence\")\n else\n exec \"$compilerBinary\" ${isystem_decls[@]} ${clangLinkerArgs[@]} ${output_args[@]} ${clangArgs[@]} ${libsArgs[@]}\n fi\ndiff --git a/junixsocket-native/junixsocket-native.xcodeproj/project.pbxproj b/junixsocket-native/junixsocket-native.xcodeproj/project.pbxproj\nindex add6e3089..9636100f0 100644\n--- a/junixsocket-native/junixsocket-native.xcodeproj/project.pbxproj\n+++ b/junixsocket-native/junixsocket-native.xcodeproj/project.pbxproj\n@@ -13,6 +13,8 @@\n \t\t\tbuildPhases = (\n \t\t\t);\n \t\t\tdependencies = (\n+\t\t\t\t436B5AF32827E55000574CD4 /* PBXTargetDependency */,\n+\t\t\t\t436B5AB928244D5700574CD4 /* PBXTargetDependency */,\n \t\t\t\t43B3E076266756780024822F /* PBXTargetDependency */,\n \t\t\t\t430235DB2650CCCD00823167 /* PBXTargetDependency */,\n \t\t\t\t432EF19C261AD6AF00F4A583 /* PBXTargetDependency */,\n@@ -29,6 +31,7 @@\n \t\t\t\t43B3E03E266730080024822F /* PBXTargetDependency */,\n \t\t\t\t432EF1D8261ADDA000F4A583 /* PBXTargetDependency */,\n \t\t\t\t43B3E00626660A7A0024822F /* PBXTargetDependency */,\n+\t\t\t\t43684DB9282EE2CA005F2989 /* PBXTargetDependency */,\n \t\t\t\t432EF1AB261AD97A00F4A583 /* PBXTargetDependency */,\n \t\t\t);\n \t\t\tname = \"All Architectures\";\n@@ -587,6 +590,184 @@\n \t\t4304A61F266DFCEF003BCEDF /* listen.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233AF2650AB4B00823167 /* listen.c */; };\n \t\t4304A620266DFCEF003BCEDF /* ancillary.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233A52650AB4900823167 /* ancillary.c */; };\n \t\t4304A621266DFCEF003BCEDF /* accept.c in Sources */ = {isa = PBXBuildFile; fileRef = 4302339E2650AB4900823167 /* accept.c */; };\n+\t\t43684D82282EE24B005F2989 /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t43684D83282EE24B005F2989 /* jni.h in Headers */ = {isa = PBXBuildFile; fileRef = 430235C02650AC3200823167 /* jni.h */; };\n+\t\t43684D84282EE24B005F2989 /* ancillary.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233C52650AB4E00823167 /* ancillary.h */; };\n+\t\t43684D85282EE24B005F2989 /* pipe.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B3DF81265EEC930024822F /* pipe.h */; };\n+\t\t43684D86282EE24B005F2989 /* init.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233BE2650AB4D00823167 /* init.h */; };\n+\t\t43684D87282EE24B005F2989 /* send.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AA2650AB4A00823167 /* send.h */; };\n+\t\t43684D88282EE24B005F2989 /* listen.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233B12650AB4B00823167 /* listen.h */; };\n+\t\t43684D89282EE24B005F2989 /* config.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A22650AB4900823167 /* config.h */; };\n+\t\t43684D8A282EE24B005F2989 /* socketpair.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B3DFB6266082000024822F /* socketpair.h */; };\n+\t\t43684D8B282EE24B005F2989 /* connect.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A72650AB4A00823167 /* connect.h */; };\n+\t\t43684D8C282EE24B005F2989 /* jniutil.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A12650AB4900823167 /* jniutil.h */; };\n+\t\t43684D8D282EE24B005F2989 /* socketoptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 4302339D2650AB4900823167 /* socketoptions.h */; };\n+\t\t43684D8E282EE24B005F2989 /* filedescriptors.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AC2650AB4A00823167 /* filedescriptors.h */; };\n+\t\t43684D8F282EE24B005F2989 /* exceptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A82650AB4A00823167 /* exceptions.h */; };\n+\t\t43684D90282EE24B005F2989 /* capabilities.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A42650AB4900823167 /* capabilities.h */; };\n+\t\t43684D91282EE24B005F2989 /* org_newsclub_net_unix_NativeUnixSocket.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233C02650AB4D00823167 /* org_newsclub_net_unix_NativeUnixSocket.h */; };\n+\t\t43684D92282EE24B005F2989 /* socket.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233B42650AB4B00823167 /* socket.h */; };\n+\t\t43684D93282EE24B005F2989 /* ckmacros.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233BF2650AB4D00823167 /* ckmacros.h */; };\n+\t\t43684D94282EE24B005F2989 /* address.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233B92650AB4C00823167 /* address.h */; };\n+\t\t43684D95282EE24B005F2989 /* polling.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A92650AB4A00823167 /* polling.h */; };\n+\t\t43684D96282EE24B005F2989 /* accept.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233BB2650AB4C00823167 /* accept.h */; };\n+\t\t43684D97282EE24B005F2989 /* reflection.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AD2650AB4A00823167 /* reflection.h */; };\n+\t\t43684D98282EE24B005F2989 /* jniport.h in Headers */ = {isa = PBXBuildFile; fileRef = 430235C12650AC3200823167 /* jniport.h */; };\n+\t\t43684D99282EE24B005F2989 /* receive.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A62650AB4A00823167 /* receive.h */; };\n+\t\t43684D9A282EE24B005F2989 /* credentials.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AE2650AB4A00823167 /* credentials.h */; };\n+\t\t43684D9B282EE24B005F2989 /* bind.h in Headers */ = {isa = PBXBuildFile; fileRef = 4302339F2650AB4900823167 /* bind.h */; };\n+\t\t43684D9D282EE24B005F2989 /* filedescriptors.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C42650AB4E00823167 /* filedescriptors.c */; };\n+\t\t43684D9E282EE24B005F2989 /* bind.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C32650AB4D00823167 /* bind.c */; };\n+\t\t43684D9F282EE24B005F2989 /* address.c in Sources */ = {isa = PBXBuildFile; fileRef = 4302339C2650AB4900823167 /* address.c */; };\n+\t\t43684DA0282EE24B005F2989 /* send.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B22650AB4B00823167 /* send.c */; };\n+\t\t43684DA1282EE24B005F2989 /* socket.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C22650AB4D00823167 /* socket.c */; };\n+\t\t43684DA2282EE24B005F2989 /* pipe.c in Sources */ = {isa = PBXBuildFile; fileRef = 43B3DF82265EEC930024822F /* pipe.c */; };\n+\t\t43684DA3282EE24B005F2989 /* connect.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233BC2650AB4C00823167 /* connect.c */; };\n+\t\t43684DA4282EE24B005F2989 /* capabilities.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B02650AB4B00823167 /* capabilities.c */; };\n+\t\t43684DA5282EE24B005F2989 /* socketoptions.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B52650AB4B00823167 /* socketoptions.c */; };\n+\t\t43684DA6282EE24B005F2989 /* polling.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C12650AB4D00823167 /* polling.c */; };\n+\t\t43684DA7282EE24B005F2989 /* receive.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233AB2650AB4A00823167 /* receive.c */; };\n+\t\t43684DA8282EE24B005F2989 /* jniutil.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233A32650AB4900823167 /* jniutil.c */; };\n+\t\t43684DA9282EE24B005F2989 /* init.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B32650AB4B00823167 /* init.c */; };\n+\t\t43684DAA282EE24B005F2989 /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t43684DAB282EE24B005F2989 /* config.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233A02650AB4900823167 /* config.c */; };\n+\t\t43684DAC282EE24B005F2989 /* credentials.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C62650AB4E00823167 /* credentials.c */; };\n+\t\t43684DAD282EE24B005F2989 /* socketpair.c in Sources */ = {isa = PBXBuildFile; fileRef = 43B3DFB5266082000024822F /* socketpair.c */; };\n+\t\t43684DAE282EE24B005F2989 /* exceptions.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233BD2650AB4C00823167 /* exceptions.c */; };\n+\t\t43684DAF282EE24B005F2989 /* reflection.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233BA2650AB4C00823167 /* reflection.c */; };\n+\t\t43684DB0282EE24B005F2989 /* listen.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233AF2650AB4B00823167 /* listen.c */; };\n+\t\t43684DB1282EE24B005F2989 /* ancillary.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233A52650AB4900823167 /* ancillary.c */; };\n+\t\t43684DB2282EE24B005F2989 /* accept.c in Sources */ = {isa = PBXBuildFile; fileRef = 4302339E2650AB4900823167 /* accept.c */; };\n+\t\t436B5A8228244CB500574CD4 /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436B5A8328244CB500574CD4 /* jni.h in Headers */ = {isa = PBXBuildFile; fileRef = 430235C02650AC3200823167 /* jni.h */; };\n+\t\t436B5A8428244CB500574CD4 /* ancillary.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233C52650AB4E00823167 /* ancillary.h */; };\n+\t\t436B5A8528244CB500574CD4 /* pipe.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B3DF81265EEC930024822F /* pipe.h */; };\n+\t\t436B5A8628244CB500574CD4 /* init.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233BE2650AB4D00823167 /* init.h */; };\n+\t\t436B5A8728244CB500574CD4 /* send.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AA2650AB4A00823167 /* send.h */; };\n+\t\t436B5A8828244CB500574CD4 /* listen.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233B12650AB4B00823167 /* listen.h */; };\n+\t\t436B5A8928244CB500574CD4 /* config.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A22650AB4900823167 /* config.h */; };\n+\t\t436B5A8A28244CB500574CD4 /* socketpair.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B3DFB6266082000024822F /* socketpair.h */; };\n+\t\t436B5A8B28244CB500574CD4 /* connect.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A72650AB4A00823167 /* connect.h */; };\n+\t\t436B5A8C28244CB500574CD4 /* jniutil.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A12650AB4900823167 /* jniutil.h */; };\n+\t\t436B5A8D28244CB500574CD4 /* socketoptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 4302339D2650AB4900823167 /* socketoptions.h */; };\n+\t\t436B5A8E28244CB500574CD4 /* filedescriptors.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AC2650AB4A00823167 /* filedescriptors.h */; };\n+\t\t436B5A8F28244CB500574CD4 /* exceptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A82650AB4A00823167 /* exceptions.h */; };\n+\t\t436B5A9028244CB500574CD4 /* capabilities.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A42650AB4900823167 /* capabilities.h */; };\n+\t\t436B5A9128244CB500574CD4 /* org_newsclub_net_unix_NativeUnixSocket.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233C02650AB4D00823167 /* org_newsclub_net_unix_NativeUnixSocket.h */; };\n+\t\t436B5A9228244CB500574CD4 /* socket.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233B42650AB4B00823167 /* socket.h */; };\n+\t\t436B5A9328244CB500574CD4 /* ckmacros.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233BF2650AB4D00823167 /* ckmacros.h */; };\n+\t\t436B5A9428244CB500574CD4 /* address.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233B92650AB4C00823167 /* address.h */; };\n+\t\t436B5A9528244CB500574CD4 /* polling.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A92650AB4A00823167 /* polling.h */; };\n+\t\t436B5A9628244CB500574CD4 /* accept.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233BB2650AB4C00823167 /* accept.h */; };\n+\t\t436B5A9728244CB500574CD4 /* reflection.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AD2650AB4A00823167 /* reflection.h */; };\n+\t\t436B5A9828244CB500574CD4 /* jniport.h in Headers */ = {isa = PBXBuildFile; fileRef = 430235C12650AC3200823167 /* jniport.h */; };\n+\t\t436B5A9928244CB500574CD4 /* receive.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A62650AB4A00823167 /* receive.h */; };\n+\t\t436B5A9A28244CB500574CD4 /* credentials.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AE2650AB4A00823167 /* credentials.h */; };\n+\t\t436B5A9B28244CB500574CD4 /* bind.h in Headers */ = {isa = PBXBuildFile; fileRef = 4302339F2650AB4900823167 /* bind.h */; };\n+\t\t436B5A9D28244CB500574CD4 /* filedescriptors.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C42650AB4E00823167 /* filedescriptors.c */; };\n+\t\t436B5A9E28244CB500574CD4 /* bind.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C32650AB4D00823167 /* bind.c */; };\n+\t\t436B5A9F28244CB500574CD4 /* address.c in Sources */ = {isa = PBXBuildFile; fileRef = 4302339C2650AB4900823167 /* address.c */; };\n+\t\t436B5AA028244CB500574CD4 /* send.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B22650AB4B00823167 /* send.c */; };\n+\t\t436B5AA128244CB500574CD4 /* socket.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C22650AB4D00823167 /* socket.c */; };\n+\t\t436B5AA228244CB500574CD4 /* pipe.c in Sources */ = {isa = PBXBuildFile; fileRef = 43B3DF82265EEC930024822F /* pipe.c */; };\n+\t\t436B5AA328244CB500574CD4 /* connect.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233BC2650AB4C00823167 /* connect.c */; };\n+\t\t436B5AA428244CB500574CD4 /* capabilities.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B02650AB4B00823167 /* capabilities.c */; };\n+\t\t436B5AA528244CB500574CD4 /* socketoptions.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B52650AB4B00823167 /* socketoptions.c */; };\n+\t\t436B5AA628244CB500574CD4 /* polling.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C12650AB4D00823167 /* polling.c */; };\n+\t\t436B5AA728244CB500574CD4 /* receive.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233AB2650AB4A00823167 /* receive.c */; };\n+\t\t436B5AA828244CB500574CD4 /* jniutil.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233A32650AB4900823167 /* jniutil.c */; };\n+\t\t436B5AA928244CB500574CD4 /* init.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B32650AB4B00823167 /* init.c */; };\n+\t\t436B5AAA28244CB500574CD4 /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436B5AAB28244CB500574CD4 /* config.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233A02650AB4900823167 /* config.c */; };\n+\t\t436B5AAC28244CB500574CD4 /* credentials.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C62650AB4E00823167 /* credentials.c */; };\n+\t\t436B5AAD28244CB500574CD4 /* socketpair.c in Sources */ = {isa = PBXBuildFile; fileRef = 43B3DFB5266082000024822F /* socketpair.c */; };\n+\t\t436B5AAE28244CB500574CD4 /* exceptions.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233BD2650AB4C00823167 /* exceptions.c */; };\n+\t\t436B5AAF28244CB500574CD4 /* reflection.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233BA2650AB4C00823167 /* reflection.c */; };\n+\t\t436B5AB028244CB500574CD4 /* listen.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233AF2650AB4B00823167 /* listen.c */; };\n+\t\t436B5AB128244CB500574CD4 /* ancillary.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233A52650AB4900823167 /* ancillary.c */; };\n+\t\t436B5AB228244CB500574CD4 /* accept.c in Sources */ = {isa = PBXBuildFile; fileRef = 4302339E2650AB4900823167 /* accept.c */; };\n+\t\t436B5ABC2826F49A00574CD4 /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436B5ABD2826F49A00574CD4 /* jni.h in Headers */ = {isa = PBXBuildFile; fileRef = 430235C02650AC3200823167 /* jni.h */; };\n+\t\t436B5ABE2826F49A00574CD4 /* ancillary.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233C52650AB4E00823167 /* ancillary.h */; };\n+\t\t436B5ABF2826F49A00574CD4 /* pipe.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B3DF81265EEC930024822F /* pipe.h */; };\n+\t\t436B5AC02826F49A00574CD4 /* init.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233BE2650AB4D00823167 /* init.h */; };\n+\t\t436B5AC12826F49A00574CD4 /* send.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AA2650AB4A00823167 /* send.h */; };\n+\t\t436B5AC22826F49A00574CD4 /* listen.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233B12650AB4B00823167 /* listen.h */; };\n+\t\t436B5AC32826F49A00574CD4 /* config.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A22650AB4900823167 /* config.h */; };\n+\t\t436B5AC42826F49A00574CD4 /* socketpair.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B3DFB6266082000024822F /* socketpair.h */; };\n+\t\t436B5AC52826F49A00574CD4 /* connect.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A72650AB4A00823167 /* connect.h */; };\n+\t\t436B5AC62826F49A00574CD4 /* jniutil.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A12650AB4900823167 /* jniutil.h */; };\n+\t\t436B5AC72826F49A00574CD4 /* socketoptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 4302339D2650AB4900823167 /* socketoptions.h */; };\n+\t\t436B5AC82826F49A00574CD4 /* filedescriptors.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AC2650AB4A00823167 /* filedescriptors.h */; };\n+\t\t436B5AC92826F49A00574CD4 /* exceptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A82650AB4A00823167 /* exceptions.h */; };\n+\t\t436B5ACA2826F49A00574CD4 /* capabilities.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A42650AB4900823167 /* capabilities.h */; };\n+\t\t436B5ACB2826F49A00574CD4 /* org_newsclub_net_unix_NativeUnixSocket.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233C02650AB4D00823167 /* org_newsclub_net_unix_NativeUnixSocket.h */; };\n+\t\t436B5ACC2826F49A00574CD4 /* socket.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233B42650AB4B00823167 /* socket.h */; };\n+\t\t436B5ACD2826F49A00574CD4 /* ckmacros.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233BF2650AB4D00823167 /* ckmacros.h */; };\n+\t\t436B5ACE2826F49A00574CD4 /* address.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233B92650AB4C00823167 /* address.h */; };\n+\t\t436B5ACF2826F49A00574CD4 /* polling.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A92650AB4A00823167 /* polling.h */; };\n+\t\t436B5AD02826F49A00574CD4 /* accept.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233BB2650AB4C00823167 /* accept.h */; };\n+\t\t436B5AD12826F49A00574CD4 /* reflection.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AD2650AB4A00823167 /* reflection.h */; };\n+\t\t436B5AD22826F49A00574CD4 /* jniport.h in Headers */ = {isa = PBXBuildFile; fileRef = 430235C12650AC3200823167 /* jniport.h */; };\n+\t\t436B5AD32826F49A00574CD4 /* receive.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233A62650AB4A00823167 /* receive.h */; };\n+\t\t436B5AD42826F49A00574CD4 /* credentials.h in Headers */ = {isa = PBXBuildFile; fileRef = 430233AE2650AB4A00823167 /* credentials.h */; };\n+\t\t436B5AD52826F49A00574CD4 /* bind.h in Headers */ = {isa = PBXBuildFile; fileRef = 4302339F2650AB4900823167 /* bind.h */; };\n+\t\t436B5AD72826F49A00574CD4 /* filedescriptors.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C42650AB4E00823167 /* filedescriptors.c */; };\n+\t\t436B5AD82826F49A00574CD4 /* bind.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C32650AB4D00823167 /* bind.c */; };\n+\t\t436B5AD92826F49A00574CD4 /* address.c in Sources */ = {isa = PBXBuildFile; fileRef = 4302339C2650AB4900823167 /* address.c */; };\n+\t\t436B5ADA2826F49A00574CD4 /* send.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B22650AB4B00823167 /* send.c */; };\n+\t\t436B5ADB2826F49A00574CD4 /* socket.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C22650AB4D00823167 /* socket.c */; };\n+\t\t436B5ADC2826F49A00574CD4 /* pipe.c in Sources */ = {isa = PBXBuildFile; fileRef = 43B3DF82265EEC930024822F /* pipe.c */; };\n+\t\t436B5ADD2826F49A00574CD4 /* connect.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233BC2650AB4C00823167 /* connect.c */; };\n+\t\t436B5ADE2826F49A00574CD4 /* capabilities.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B02650AB4B00823167 /* capabilities.c */; };\n+\t\t436B5ADF2826F49A00574CD4 /* socketoptions.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B52650AB4B00823167 /* socketoptions.c */; };\n+\t\t436B5AE02826F49A00574CD4 /* polling.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C12650AB4D00823167 /* polling.c */; };\n+\t\t436B5AE12826F49A00574CD4 /* receive.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233AB2650AB4A00823167 /* receive.c */; };\n+\t\t436B5AE22826F49A00574CD4 /* jniutil.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233A32650AB4900823167 /* jniutil.c */; };\n+\t\t436B5AE32826F49A00574CD4 /* init.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233B32650AB4B00823167 /* init.c */; };\n+\t\t436B5AE42826F49A00574CD4 /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436B5AE52826F49A00574CD4 /* config.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233A02650AB4900823167 /* config.c */; };\n+\t\t436B5AE62826F49A00574CD4 /* credentials.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233C62650AB4E00823167 /* credentials.c */; };\n+\t\t436B5AE72826F49A00574CD4 /* socketpair.c in Sources */ = {isa = PBXBuildFile; fileRef = 43B3DFB5266082000024822F /* socketpair.c */; };\n+\t\t436B5AE82826F49A00574CD4 /* exceptions.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233BD2650AB4C00823167 /* exceptions.c */; };\n+\t\t436B5AE92826F49A00574CD4 /* reflection.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233BA2650AB4C00823167 /* reflection.c */; };\n+\t\t436B5AEA2826F49A00574CD4 /* listen.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233AF2650AB4B00823167 /* listen.c */; };\n+\t\t436B5AEB2826F49A00574CD4 /* ancillary.c in Sources */ = {isa = PBXBuildFile; fileRef = 430233A52650AB4900823167 /* ancillary.c */; };\n+\t\t436B5AEC2826F49A00574CD4 /* accept.c in Sources */ = {isa = PBXBuildFile; fileRef = 4302339E2650AB4900823167 /* accept.c */; };\n+\t\t436E166127FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166227FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166327FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166427FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166527FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166627FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166727FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166827FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166927FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166A27FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166B27FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166C27FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166D27FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166E27FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E166F27FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E167027FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E167127FBB70B00A553EC /* tipc.h in Headers */ = {isa = PBXBuildFile; fileRef = 436E165F27FBB70B00A553EC /* tipc.h */; };\n+\t\t436E167227FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167327FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167427FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167527FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167627FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167727FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167827FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167927FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167A27FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167B27FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167C27FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167D27FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167E27FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E167F27FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E168027FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E168127FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n+\t\t436E168227FBB70B00A553EC /* tipc.c in Sources */ = {isa = PBXBuildFile; fileRef = 436E166027FBB70B00A553EC /* tipc.c */; };\n \t\t43B3DF83265EEC930024822F /* pipe.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B3DF81265EEC930024822F /* pipe.h */; };\n \t\t43B3DF84265EEC930024822F /* pipe.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B3DF81265EEC930024822F /* pipe.h */; };\n \t\t43B3DF85265EEC930024822F /* pipe.h in Headers */ = {isa = PBXBuildFile; fileRef = 43B3DF81265EEC930024822F /* pipe.h */; };\n@@ -906,6 +1087,27 @@\n \t\t\tremoteGlobalIDString = 432EF1F7261ADEDD00F4A583;\n \t\t\tremoteInfo = \"armv6--linux-gnueabihf\";\n \t\t};\n+\t\t43684DB8282EE2CA005F2989 /* PBXContainerItemProxy */ = {\n+\t\t\tisa = PBXContainerItemProxy;\n+\t\t\tcontainerPortal = 43D436B0261A55D0002D0C12 /* Project object */;\n+\t\t\tproxyType = 1;\n+\t\t\tremoteGlobalIDString = 43684D80282EE24B005F2989;\n+\t\t\tremoteInfo = \"aarch64-w64-mingw32\";\n+\t\t};\n+\t\t436B5AB828244D5700574CD4 /* PBXContainerItemProxy */ = {\n+\t\t\tisa = PBXContainerItemProxy;\n+\t\t\tcontainerPortal = 43D436B0261A55D0002D0C12 /* Project object */;\n+\t\t\tproxyType = 1;\n+\t\t\tremoteGlobalIDString = 436B5A8028244CB500574CD4;\n+\t\t\tremoteInfo = \"powerpc-ibm-aix7.2\";\n+\t\t};\n+\t\t436B5AF22827E55000574CD4 /* PBXContainerItemProxy */ = {\n+\t\t\tisa = PBXContainerItemProxy;\n+\t\t\tcontainerPortal = 43D436B0261A55D0002D0C12 /* Project object */;\n+\t\t\tproxyType = 1;\n+\t\t\tremoteGlobalIDString = 436B5ABA2826F49A00574CD4;\n+\t\t\tremoteInfo = \"powerpc-ibm-os400\";\n+\t\t};\n \t\t43B3E00526660A7A0024822F /* PBXContainerItemProxy */ = {\n \t\t\tisa = PBXContainerItemProxy;\n \t\t\tcontainerPortal = 43D436B0261A55D0002D0C12 /* Project object */;\n@@ -997,6 +1199,11 @@\n \t\t432EF203261ADEDD00F4A583 /* libjunixsocket-armv6--linux-gnueabihf.so */ = {isa = PBXFileReference; explicitFileType = \"compiled.mach-o.dylib\"; includeInIndex = 0; path = \"libjunixsocket-armv6--linux-gnueabihf.so\"; sourceTree = BUILT_PRODUCTS_DIR; };\n \t\t432EF212261AE29200F4A583 /* libjunixsocket-x86_64-apple-darwin18.2.0.dylib */ = {isa = PBXFileReference; explicitFileType = \"compiled.mach-o.dylib\"; includeInIndex = 0; path = \"libjunixsocket-x86_64-apple-darwin18.2.0.dylib\"; sourceTree = BUILT_PRODUCTS_DIR; };\n \t\t43663EE2261AECC400CEED08 /* libjunixsocket-current.dylib */ = {isa = PBXFileReference; explicitFileType = \"compiled.mach-o.dylib\"; includeInIndex = 0; path = \"libjunixsocket-current.dylib\"; sourceTree = BUILT_PRODUCTS_DIR; };\n+\t\t43684DB7282EE24B005F2989 /* libjunixsocket-aarch64-w64-mingw32.so */ = {isa = PBXFileReference; explicitFileType = \"compiled.mach-o.dylib\"; includeInIndex = 0; path = \"libjunixsocket-aarch64-w64-mingw32.so\"; sourceTree = BUILT_PRODUCTS_DIR; };\n+\t\t436B5AB728244CB500574CD4 /* libjunixsocket-powerpc-ibm-aix7.2.so */ = {isa = PBXFileReference; explicitFileType = \"compiled.mach-o.dylib\"; includeInIndex = 0; path = \"libjunixsocket-powerpc-ibm-aix7.2.so\"; sourceTree = BUILT_PRODUCTS_DIR; };\n+\t\t436B5AF12826F49A00574CD4 /* libjunixsocket-powerpc-ibm-os400.so */ = {isa = PBXFileReference; explicitFileType = \"compiled.mach-o.dylib\"; includeInIndex = 0; path = \"libjunixsocket-powerpc-ibm-os400.so\"; sourceTree = BUILT_PRODUCTS_DIR; };\n+\t\t436E165F27FBB70B00A553EC /* tipc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = tipc.h; path = src/main/c/tipc.h; sourceTree = \"\"; };\n+\t\t436E166027FBB70B00A553EC /* tipc.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; name = tipc.c; path = src/main/c/tipc.c; sourceTree = \"\"; };\n \t\t43B3DF81265EEC930024822F /* pipe.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = pipe.h; path = src/main/c/pipe.h; sourceTree = \"\"; };\n \t\t43B3DF82265EEC930024822F /* pipe.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; name = pipe.c; path = src/main/c/pipe.c; sourceTree = \"\"; };\n \t\t43B3DFB5266082000024822F /* socketpair.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = socketpair.c; path = src/main/c/socketpair.c; sourceTree = \"\"; };\n@@ -1087,6 +1294,27 @@\n \t\t\t);\n \t\t\trunOnlyForDeploymentPostprocessing = 0;\n \t\t};\n+\t\t43684DB3282EE24B005F2989 /* Frameworks */ = {\n+\t\t\tisa = PBXFrameworksBuildPhase;\n+\t\t\tbuildActionMask = 2147483647;\n+\t\t\tfiles = (\n+\t\t\t);\n+\t\t\trunOnlyForDeploymentPostprocessing = 0;\n+\t\t};\n+\t\t436B5AB328244CB500574CD4 /* Frameworks */ = {\n+\t\t\tisa = PBXFrameworksBuildPhase;\n+\t\t\tbuildActionMask = 2147483647;\n+\t\t\tfiles = (\n+\t\t\t);\n+\t\t\trunOnlyForDeploymentPostprocessing = 0;\n+\t\t};\n+\t\t436B5AED2826F49A00574CD4 /* Frameworks */ = {\n+\t\t\tisa = PBXFrameworksBuildPhase;\n+\t\t\tbuildActionMask = 2147483647;\n+\t\t\tfiles = (\n+\t\t\t);\n+\t\t\trunOnlyForDeploymentPostprocessing = 0;\n+\t\t};\n \t\t43B3E00026660A2D0024822F /* Frameworks */ = {\n \t\t\tisa = PBXFrameworksBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n@@ -1194,6 +1422,8 @@\n \t\t\t\t4302339D2650AB4900823167 /* socketoptions.h */,\n \t\t\t\t43B3DFB5266082000024822F /* socketpair.c */,\n \t\t\t\t43B3DFB6266082000024822F /* socketpair.h */,\n+\t\t\t\t436E166027FBB70B00A553EC /* tipc.c */,\n+\t\t\t\t436E165F27FBB70B00A553EC /* tipc.h */,\n \t\t\t);\n \t\t\tname = Implementation;\n \t\t\tsourceTree = \"\";\n@@ -1238,6 +1468,9 @@\n \t\t\t\t43B3E074266756540024822F /* libjunixsocket-amd64-unknown-openbsd6.9.so */,\n \t\t\t\t43B3E0AC266971630024822F /* libjunixsocket-sparc-sun-solaris2.11.so */,\n \t\t\t\t4304A626266DFCEF003BCEDF /* libjunixsocket-x86_64-portbld-dragonfly6.0.so */,\n+\t\t\t\t436B5AB728244CB500574CD4 /* libjunixsocket-powerpc-ibm-aix7.2.so */,\n+\t\t\t\t436B5AF12826F49A00574CD4 /* libjunixsocket-powerpc-ibm-os400.so */,\n+\t\t\t\t43684DB7282EE24B005F2989 /* libjunixsocket-aarch64-w64-mingw32.so */,\n \t\t\t);\n \t\t\tname = Products;\n \t\t\tsourceTree = \"\";\n@@ -1249,6 +1482,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E167127FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t4304A5F3266DFCEF003BCEDF /* jni.h in Headers */,\n \t\t\t\t4304A5F4266DFCEF003BCEDF /* ancillary.h in Headers */,\n \t\t\t\t4304A5F5266DFCEF003BCEDF /* pipe.h in Headers */,\n@@ -1281,6 +1515,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166227FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235C32650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235A82650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF84265EEC930024822F /* pipe.h in Headers */,\n@@ -1313,6 +1548,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166D27FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235CD2650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235B22650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF8E265EEC930024822F /* pipe.h in Headers */,\n@@ -1345,6 +1581,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166627FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235C62650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235AB2650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF87265EEC930024822F /* pipe.h in Headers */,\n@@ -1377,6 +1614,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166927FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235C92650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235AE2650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF8A265EEC930024822F /* pipe.h in Headers */,\n@@ -1409,6 +1647,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166C27FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235CC2650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235B12650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF8D265EEC930024822F /* pipe.h in Headers */,\n@@ -1441,6 +1680,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166727FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235C72650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235AC2650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF88265EEC930024822F /* pipe.h in Headers */,\n@@ -1473,6 +1713,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166827FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235C82650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235AD2650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF89265EEC930024822F /* pipe.h in Headers */,\n@@ -1505,6 +1746,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166527FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235C52650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235AA2650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF86265EEC930024822F /* pipe.h in Headers */,\n@@ -1537,6 +1779,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166B27FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235CB2650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235B02650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF8C265EEC930024822F /* pipe.h in Headers */,\n@@ -1569,6 +1812,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166127FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235C22650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235A72650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF83265EEC930024822F /* pipe.h in Headers */,\n@@ -1597,10 +1841,110 @@\n \t\t\t);\n \t\t\trunOnlyForDeploymentPostprocessing = 0;\n \t\t};\n+\t\t43684D81282EE24B005F2989 /* Headers */ = {\n+\t\t\tisa = PBXHeadersBuildPhase;\n+\t\t\tbuildActionMask = 2147483647;\n+\t\t\tfiles = (\n+\t\t\t\t43684D82282EE24B005F2989 /* tipc.h in Headers */,\n+\t\t\t\t43684D83282EE24B005F2989 /* jni.h in Headers */,\n+\t\t\t\t43684D84282EE24B005F2989 /* ancillary.h in Headers */,\n+\t\t\t\t43684D85282EE24B005F2989 /* pipe.h in Headers */,\n+\t\t\t\t43684D86282EE24B005F2989 /* init.h in Headers */,\n+\t\t\t\t43684D87282EE24B005F2989 /* send.h in Headers */,\n+\t\t\t\t43684D88282EE24B005F2989 /* listen.h in Headers */,\n+\t\t\t\t43684D89282EE24B005F2989 /* config.h in Headers */,\n+\t\t\t\t43684D8A282EE24B005F2989 /* socketpair.h in Headers */,\n+\t\t\t\t43684D8B282EE24B005F2989 /* connect.h in Headers */,\n+\t\t\t\t43684D8C282EE24B005F2989 /* jniutil.h in Headers */,\n+\t\t\t\t43684D8D282EE24B005F2989 /* socketoptions.h in Headers */,\n+\t\t\t\t43684D8E282EE24B005F2989 /* filedescriptors.h in Headers */,\n+\t\t\t\t43684D8F282EE24B005F2989 /* exceptions.h in Headers */,\n+\t\t\t\t43684D90282EE24B005F2989 /* capabilities.h in Headers */,\n+\t\t\t\t43684D91282EE24B005F2989 /* org_newsclub_net_unix_NativeUnixSocket.h in Headers */,\n+\t\t\t\t43684D92282EE24B005F2989 /* socket.h in Headers */,\n+\t\t\t\t43684D93282EE24B005F2989 /* ckmacros.h in Headers */,\n+\t\t\t\t43684D94282EE24B005F2989 /* address.h in Headers */,\n+\t\t\t\t43684D95282EE24B005F2989 /* polling.h in Headers */,\n+\t\t\t\t43684D96282EE24B005F2989 /* accept.h in Headers */,\n+\t\t\t\t43684D97282EE24B005F2989 /* reflection.h in Headers */,\n+\t\t\t\t43684D98282EE24B005F2989 /* jniport.h in Headers */,\n+\t\t\t\t43684D99282EE24B005F2989 /* receive.h in Headers */,\n+\t\t\t\t43684D9A282EE24B005F2989 /* credentials.h in Headers */,\n+\t\t\t\t43684D9B282EE24B005F2989 /* bind.h in Headers */,\n+\t\t\t);\n+\t\t\trunOnlyForDeploymentPostprocessing = 0;\n+\t\t};\n+\t\t436B5A8128244CB500574CD4 /* Headers */ = {\n+\t\t\tisa = PBXHeadersBuildPhase;\n+\t\t\tbuildActionMask = 2147483647;\n+\t\t\tfiles = (\n+\t\t\t\t436B5A8228244CB500574CD4 /* tipc.h in Headers */,\n+\t\t\t\t436B5A8328244CB500574CD4 /* jni.h in Headers */,\n+\t\t\t\t436B5A8428244CB500574CD4 /* ancillary.h in Headers */,\n+\t\t\t\t436B5A8528244CB500574CD4 /* pipe.h in Headers */,\n+\t\t\t\t436B5A8628244CB500574CD4 /* init.h in Headers */,\n+\t\t\t\t436B5A8728244CB500574CD4 /* send.h in Headers */,\n+\t\t\t\t436B5A8828244CB500574CD4 /* listen.h in Headers */,\n+\t\t\t\t436B5A8928244CB500574CD4 /* config.h in Headers */,\n+\t\t\t\t436B5A8A28244CB500574CD4 /* socketpair.h in Headers */,\n+\t\t\t\t436B5A8B28244CB500574CD4 /* connect.h in Headers */,\n+\t\t\t\t436B5A8C28244CB500574CD4 /* jniutil.h in Headers */,\n+\t\t\t\t436B5A8D28244CB500574CD4 /* socketoptions.h in Headers */,\n+\t\t\t\t436B5A8E28244CB500574CD4 /* filedescriptors.h in Headers */,\n+\t\t\t\t436B5A8F28244CB500574CD4 /* exceptions.h in Headers */,\n+\t\t\t\t436B5A9028244CB500574CD4 /* capabilities.h in Headers */,\n+\t\t\t\t436B5A9128244CB500574CD4 /* org_newsclub_net_unix_NativeUnixSocket.h in Headers */,\n+\t\t\t\t436B5A9228244CB500574CD4 /* socket.h in Headers */,\n+\t\t\t\t436B5A9328244CB500574CD4 /* ckmacros.h in Headers */,\n+\t\t\t\t436B5A9428244CB500574CD4 /* address.h in Headers */,\n+\t\t\t\t436B5A9528244CB500574CD4 /* polling.h in Headers */,\n+\t\t\t\t436B5A9628244CB500574CD4 /* accept.h in Headers */,\n+\t\t\t\t436B5A9728244CB500574CD4 /* reflection.h in Headers */,\n+\t\t\t\t436B5A9828244CB500574CD4 /* jniport.h in Headers */,\n+\t\t\t\t436B5A9928244CB500574CD4 /* receive.h in Headers */,\n+\t\t\t\t436B5A9A28244CB500574CD4 /* credentials.h in Headers */,\n+\t\t\t\t436B5A9B28244CB500574CD4 /* bind.h in Headers */,\n+\t\t\t);\n+\t\t\trunOnlyForDeploymentPostprocessing = 0;\n+\t\t};\n+\t\t436B5ABB2826F49A00574CD4 /* Headers */ = {\n+\t\t\tisa = PBXHeadersBuildPhase;\n+\t\t\tbuildActionMask = 2147483647;\n+\t\t\tfiles = (\n+\t\t\t\t436B5ABC2826F49A00574CD4 /* tipc.h in Headers */,\n+\t\t\t\t436B5ABD2826F49A00574CD4 /* jni.h in Headers */,\n+\t\t\t\t436B5ABE2826F49A00574CD4 /* ancillary.h in Headers */,\n+\t\t\t\t436B5ABF2826F49A00574CD4 /* pipe.h in Headers */,\n+\t\t\t\t436B5AC02826F49A00574CD4 /* init.h in Headers */,\n+\t\t\t\t436B5AC12826F49A00574CD4 /* send.h in Headers */,\n+\t\t\t\t436B5AC22826F49A00574CD4 /* listen.h in Headers */,\n+\t\t\t\t436B5AC32826F49A00574CD4 /* config.h in Headers */,\n+\t\t\t\t436B5AC42826F49A00574CD4 /* socketpair.h in Headers */,\n+\t\t\t\t436B5AC52826F49A00574CD4 /* connect.h in Headers */,\n+\t\t\t\t436B5AC62826F49A00574CD4 /* jniutil.h in Headers */,\n+\t\t\t\t436B5AC72826F49A00574CD4 /* socketoptions.h in Headers */,\n+\t\t\t\t436B5AC82826F49A00574CD4 /* filedescriptors.h in Headers */,\n+\t\t\t\t436B5AC92826F49A00574CD4 /* exceptions.h in Headers */,\n+\t\t\t\t436B5ACA2826F49A00574CD4 /* capabilities.h in Headers */,\n+\t\t\t\t436B5ACB2826F49A00574CD4 /* org_newsclub_net_unix_NativeUnixSocket.h in Headers */,\n+\t\t\t\t436B5ACC2826F49A00574CD4 /* socket.h in Headers */,\n+\t\t\t\t436B5ACD2826F49A00574CD4 /* ckmacros.h in Headers */,\n+\t\t\t\t436B5ACE2826F49A00574CD4 /* address.h in Headers */,\n+\t\t\t\t436B5ACF2826F49A00574CD4 /* polling.h in Headers */,\n+\t\t\t\t436B5AD02826F49A00574CD4 /* accept.h in Headers */,\n+\t\t\t\t436B5AD12826F49A00574CD4 /* reflection.h in Headers */,\n+\t\t\t\t436B5AD22826F49A00574CD4 /* jniport.h in Headers */,\n+\t\t\t\t436B5AD32826F49A00574CD4 /* receive.h in Headers */,\n+\t\t\t\t436B5AD42826F49A00574CD4 /* credentials.h in Headers */,\n+\t\t\t\t436B5AD52826F49A00574CD4 /* bind.h in Headers */,\n+\t\t\t);\n+\t\t\trunOnlyForDeploymentPostprocessing = 0;\n+\t\t};\n \t\t43B3DFD026660A2D0024822F /* Headers */ = {\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166E27FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t43B3DFD126660A2D0024822F /* jni.h in Headers */,\n \t\t\t\t43B3DFD226660A2D0024822F /* ancillary.h in Headers */,\n \t\t\t\t43B3DFD326660A2D0024822F /* pipe.h in Headers */,\n@@ -1633,6 +1977,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166F27FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t43B3E00926672FD30024822F /* jni.h in Headers */,\n \t\t\t\t43B3E00A26672FD30024822F /* ancillary.h in Headers */,\n \t\t\t\t43B3E00B26672FD30024822F /* pipe.h in Headers */,\n@@ -1665,6 +2010,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166327FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t43B3E041266756540024822F /* jni.h in Headers */,\n \t\t\t\t43B3E042266756540024822F /* ancillary.h in Headers */,\n \t\t\t\t43B3E043266756540024822F /* pipe.h in Headers */,\n@@ -1697,6 +2043,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E167027FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t43B3E079266971630024822F /* jni.h in Headers */,\n \t\t\t\t43B3E07A266971630024822F /* ancillary.h in Headers */,\n \t\t\t\t43B3E07B266971630024822F /* pipe.h in Headers */,\n@@ -1729,6 +2076,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166427FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235C42650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235A92650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF85265EEC930024822F /* pipe.h in Headers */,\n@@ -1761,6 +2109,7 @@\n \t\t\tisa = PBXHeadersBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n \t\t\tfiles = (\n+\t\t\t\t436E166A27FBB70B00A553EC /* tipc.h in Headers */,\n \t\t\t\t430235CA2650AC3200823167 /* jni.h in Headers */,\n \t\t\t\t430235AF2650AB4F00823167 /* ancillary.h in Headers */,\n \t\t\t\t43B3DF8B265EEC930024822F /* pipe.h in Headers */,\n@@ -1979,6 +2328,57 @@\n \t\t\tproductReference = 43663EE2261AECC400CEED08 /* libjunixsocket-current.dylib */;\n \t\t\tproductType = \"com.apple.product-type.library.dynamic\";\n \t\t};\n+\t\t43684D80282EE24B005F2989 /* aarch64-w64-mingw32 */ = {\n+\t\t\tisa = PBXNativeTarget;\n+\t\t\tbuildConfigurationList = 43684DB4282EE24B005F2989 /* Build configuration list for PBXNativeTarget \"aarch64-w64-mingw32\" */;\n+\t\t\tbuildPhases = (\n+\t\t\t\t43684D81282EE24B005F2989 /* Headers */,\n+\t\t\t\t43684D9C282EE24B005F2989 /* Sources */,\n+\t\t\t\t43684DB3282EE24B005F2989 /* Frameworks */,\n+\t\t\t);\n+\t\t\tbuildRules = (\n+\t\t\t);\n+\t\t\tdependencies = (\n+\t\t\t);\n+\t\t\tname = \"aarch64-w64-mingw32\";\n+\t\t\tproductName = \"junixsocket-native\";\n+\t\t\tproductReference = 43684DB7282EE24B005F2989 /* libjunixsocket-aarch64-w64-mingw32.so */;\n+\t\t\tproductType = \"com.apple.product-type.library.dynamic\";\n+\t\t};\n+\t\t436B5A8028244CB500574CD4 /* powerpc-ibm-aix7.2 */ = {\n+\t\t\tisa = PBXNativeTarget;\n+\t\t\tbuildConfigurationList = 436B5AB428244CB500574CD4 /* Build configuration list for PBXNativeTarget \"powerpc-ibm-aix7.2\" */;\n+\t\t\tbuildPhases = (\n+\t\t\t\t436B5A8128244CB500574CD4 /* Headers */,\n+\t\t\t\t436B5A9C28244CB500574CD4 /* Sources */,\n+\t\t\t\t436B5AB328244CB500574CD4 /* Frameworks */,\n+\t\t\t);\n+\t\t\tbuildRules = (\n+\t\t\t);\n+\t\t\tdependencies = (\n+\t\t\t);\n+\t\t\tname = \"powerpc-ibm-aix7.2\";\n+\t\t\tproductName = \"junixsocket-native\";\n+\t\t\tproductReference = 436B5AB728244CB500574CD4 /* libjunixsocket-powerpc-ibm-aix7.2.so */;\n+\t\t\tproductType = \"com.apple.product-type.library.dynamic\";\n+\t\t};\n+\t\t436B5ABA2826F49A00574CD4 /* powerpc-ibm-os400 */ = {\n+\t\t\tisa = PBXNativeTarget;\n+\t\t\tbuildConfigurationList = 436B5AEE2826F49A00574CD4 /* Build configuration list for PBXNativeTarget \"powerpc-ibm-os400\" */;\n+\t\t\tbuildPhases = (\n+\t\t\t\t436B5ABB2826F49A00574CD4 /* Headers */,\n+\t\t\t\t436B5AD62826F49A00574CD4 /* Sources */,\n+\t\t\t\t436B5AED2826F49A00574CD4 /* Frameworks */,\n+\t\t\t);\n+\t\t\tbuildRules = (\n+\t\t\t);\n+\t\t\tdependencies = (\n+\t\t\t);\n+\t\t\tname = \"powerpc-ibm-os400\";\n+\t\t\tproductName = \"junixsocket-native\";\n+\t\t\tproductReference = 436B5AF12826F49A00574CD4 /* libjunixsocket-powerpc-ibm-os400.so */;\n+\t\t\tproductType = \"com.apple.product-type.library.dynamic\";\n+\t\t};\n \t\t43B3DFCF26660A2D0024822F /* x86_64-unknown-netbsd9.0 */ = {\n \t\t\tisa = PBXNativeTarget;\n \t\t\tbuildConfigurationList = 43B3E00126660A2D0024822F /* Build configuration list for PBXNativeTarget \"x86_64-unknown-netbsd9.0\" */;\n@@ -2118,11 +2518,14 @@\n \t\t\t\t432EF1F7261ADEDD00F4A583 /* armv6--linux-gnueabihf */,\n \t\t\t\t432EF1AC261AD9FB00F4A583 /* i386-pc-solaris2.11_m64 */,\n \t\t\t\t432EF1D9261ADDD400F4A583 /* powerpc64le-linux-gnu */,\n+\t\t\t\t436B5A8028244CB500574CD4 /* powerpc-ibm-aix7.2 */,\n+\t\t\t\t436B5ABA2826F49A00574CD4 /* powerpc-ibm-os400 */,\n \t\t\t\t432EF1E8261ADE4900F4A583 /* riscv64-redhat-linux */,\n \t\t\t\t432EF1BB261ADB5500F4A583 /* s390x-ibm-linux-gnu */,\n \t\t\t\t43D436BB261A564C002D0C12 /* x86_64-alpine-linux-musl */,\n \t\t\t\t432EF206261AE29200F4A583 /* x86_64-apple-darwin18.2.0 */,\n \t\t\t\t432EF1C8261ADD6B00F4A583 /* x86_64-unknown-freebsd12.1 */,\n+\t\t\t\t43684D80282EE24B005F2989 /* aarch64-w64-mingw32 */,\n \t\t\t\t432EF19D261AD6D700F4A583 /* x86_64-w64-mingw32 */,\n \t\t\t\t43B3DFCF26660A2D0024822F /* x86_64-unknown-netbsd9.0 */,\n \t\t\t\t43B3E00726672FD30024822F /* x86_64-unknown-linux-gnu */,\n@@ -2150,6 +2553,7 @@\n \t\t\t\t4304A617266DFCEF003BCEDF /* receive.c in Sources */,\n \t\t\t\t4304A618266DFCEF003BCEDF /* jniutil.c in Sources */,\n \t\t\t\t4304A619266DFCEF003BCEDF /* init.c in Sources */,\n+\t\t\t\t436E168227FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t4304A61A266DFCEF003BCEDF /* config.c in Sources */,\n \t\t\t\t4304A61B266DFCEF003BCEDF /* credentials.c in Sources */,\n \t\t\t\t4304A61C266DFCEF003BCEDF /* socketpair.c in Sources */,\n@@ -2178,6 +2582,7 @@\n \t\t\t\t4302347C2650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t4302341C2650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234DC2650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167327FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430233F82650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235B42650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFB8266082000024822F /* socketpair.c in Sources */,\n@@ -2206,6 +2611,7 @@\n \t\t\t\t430234862650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t430234262650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234E62650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167E27FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430234022650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235BE2650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFC2266082000024822F /* socketpair.c in Sources */,\n@@ -2234,6 +2640,7 @@\n \t\t\t\t4302347F2650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t4302341F2650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234DF2650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167727FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430233FB2650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235B72650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFBB266082000024822F /* socketpair.c in Sources */,\n@@ -2262,6 +2669,7 @@\n \t\t\t\t430234822650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t430234222650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234E22650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167A27FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430233FE2650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235BA2650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFBE266082000024822F /* socketpair.c in Sources */,\n@@ -2290,6 +2698,7 @@\n \t\t\t\t430234852650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t430234252650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234E52650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167D27FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430234012650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235BD2650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFC1266082000024822F /* socketpair.c in Sources */,\n@@ -2318,6 +2727,7 @@\n \t\t\t\t430234802650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t430234202650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234E02650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167827FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430233FC2650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235B82650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFBC266082000024822F /* socketpair.c in Sources */,\n@@ -2346,6 +2756,7 @@\n \t\t\t\t430234812650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t430234212650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234E12650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167927FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430233FD2650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235B92650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFBD266082000024822F /* socketpair.c in Sources */,\n@@ -2374,6 +2785,7 @@\n \t\t\t\t4302347E2650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t4302341E2650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234DE2650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167627FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430233FA2650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235B62650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFBA266082000024822F /* socketpair.c in Sources */,\n@@ -2402,6 +2814,7 @@\n \t\t\t\t430234842650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t430234242650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234E42650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167C27FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430234002650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235BC2650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFC0266082000024822F /* socketpair.c in Sources */,\n@@ -2430,6 +2843,7 @@\n \t\t\t\t4302347B2650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t4302341B2650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234DB2650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167227FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430233F72650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235B32650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFB7266082000024822F /* socketpair.c in Sources */,\n@@ -2441,6 +2855,93 @@\n \t\t\t);\n \t\t\trunOnlyForDeploymentPostprocessing = 0;\n \t\t};\n+\t\t43684D9C282EE24B005F2989 /* Sources */ = {\n+\t\t\tisa = PBXSourcesBuildPhase;\n+\t\t\tbuildActionMask = 2147483647;\n+\t\t\tfiles = (\n+\t\t\t\t43684D9D282EE24B005F2989 /* filedescriptors.c in Sources */,\n+\t\t\t\t43684D9E282EE24B005F2989 /* bind.c in Sources */,\n+\t\t\t\t43684D9F282EE24B005F2989 /* address.c in Sources */,\n+\t\t\t\t43684DA0282EE24B005F2989 /* send.c in Sources */,\n+\t\t\t\t43684DA1282EE24B005F2989 /* socket.c in Sources */,\n+\t\t\t\t43684DA2282EE24B005F2989 /* pipe.c in Sources */,\n+\t\t\t\t43684DA3282EE24B005F2989 /* connect.c in Sources */,\n+\t\t\t\t43684DA4282EE24B005F2989 /* capabilities.c in Sources */,\n+\t\t\t\t43684DA5282EE24B005F2989 /* socketoptions.c in Sources */,\n+\t\t\t\t43684DA6282EE24B005F2989 /* polling.c in Sources */,\n+\t\t\t\t43684DA7282EE24B005F2989 /* receive.c in Sources */,\n+\t\t\t\t43684DA8282EE24B005F2989 /* jniutil.c in Sources */,\n+\t\t\t\t43684DA9282EE24B005F2989 /* init.c in Sources */,\n+\t\t\t\t43684DAA282EE24B005F2989 /* tipc.c in Sources */,\n+\t\t\t\t43684DAB282EE24B005F2989 /* config.c in Sources */,\n+\t\t\t\t43684DAC282EE24B005F2989 /* credentials.c in Sources */,\n+\t\t\t\t43684DAD282EE24B005F2989 /* socketpair.c in Sources */,\n+\t\t\t\t43684DAE282EE24B005F2989 /* exceptions.c in Sources */,\n+\t\t\t\t43684DAF282EE24B005F2989 /* reflection.c in Sources */,\n+\t\t\t\t43684DB0282EE24B005F2989 /* listen.c in Sources */,\n+\t\t\t\t43684DB1282EE24B005F2989 /* ancillary.c in Sources */,\n+\t\t\t\t43684DB2282EE24B005F2989 /* accept.c in Sources */,\n+\t\t\t);\n+\t\t\trunOnlyForDeploymentPostprocessing = 0;\n+\t\t};\n+\t\t436B5A9C28244CB500574CD4 /* Sources */ = {\n+\t\t\tisa = PBXSourcesBuildPhase;\n+\t\t\tbuildActionMask = 2147483647;\n+\t\t\tfiles = (\n+\t\t\t\t436B5A9D28244CB500574CD4 /* filedescriptors.c in Sources */,\n+\t\t\t\t436B5A9E28244CB500574CD4 /* bind.c in Sources */,\n+\t\t\t\t436B5A9F28244CB500574CD4 /* address.c in Sources */,\n+\t\t\t\t436B5AA028244CB500574CD4 /* send.c in Sources */,\n+\t\t\t\t436B5AA128244CB500574CD4 /* socket.c in Sources */,\n+\t\t\t\t436B5AA228244CB500574CD4 /* pipe.c in Sources */,\n+\t\t\t\t436B5AA328244CB500574CD4 /* connect.c in Sources */,\n+\t\t\t\t436B5AA428244CB500574CD4 /* capabilities.c in Sources */,\n+\t\t\t\t436B5AA528244CB500574CD4 /* socketoptions.c in Sources */,\n+\t\t\t\t436B5AA628244CB500574CD4 /* polling.c in Sources */,\n+\t\t\t\t436B5AA728244CB500574CD4 /* receive.c in Sources */,\n+\t\t\t\t436B5AA828244CB500574CD4 /* jniutil.c in Sources */,\n+\t\t\t\t436B5AA928244CB500574CD4 /* init.c in Sources */,\n+\t\t\t\t436B5AAA28244CB500574CD4 /* tipc.c in Sources */,\n+\t\t\t\t436B5AAB28244CB500574CD4 /* config.c in Sources */,\n+\t\t\t\t436B5AAC28244CB500574CD4 /* credentials.c in Sources */,\n+\t\t\t\t436B5AAD28244CB500574CD4 /* socketpair.c in Sources */,\n+\t\t\t\t436B5AAE28244CB500574CD4 /* exceptions.c in Sources */,\n+\t\t\t\t436B5AAF28244CB500574CD4 /* reflection.c in Sources */,\n+\t\t\t\t436B5AB028244CB500574CD4 /* listen.c in Sources */,\n+\t\t\t\t436B5AB128244CB500574CD4 /* ancillary.c in Sources */,\n+\t\t\t\t436B5AB228244CB500574CD4 /* accept.c in Sources */,\n+\t\t\t);\n+\t\t\trunOnlyForDeploymentPostprocessing = 0;\n+\t\t};\n+\t\t436B5AD62826F49A00574CD4 /* Sources */ = {\n+\t\t\tisa = PBXSourcesBuildPhase;\n+\t\t\tbuildActionMask = 2147483647;\n+\t\t\tfiles = (\n+\t\t\t\t436B5AD72826F49A00574CD4 /* filedescriptors.c in Sources */,\n+\t\t\t\t436B5AD82826F49A00574CD4 /* bind.c in Sources */,\n+\t\t\t\t436B5AD92826F49A00574CD4 /* address.c in Sources */,\n+\t\t\t\t436B5ADA2826F49A00574CD4 /* send.c in Sources */,\n+\t\t\t\t436B5ADB2826F49A00574CD4 /* socket.c in Sources */,\n+\t\t\t\t436B5ADC2826F49A00574CD4 /* pipe.c in Sources */,\n+\t\t\t\t436B5ADD2826F49A00574CD4 /* connect.c in Sources */,\n+\t\t\t\t436B5ADE2826F49A00574CD4 /* capabilities.c in Sources */,\n+\t\t\t\t436B5ADF2826F49A00574CD4 /* socketoptions.c in Sources */,\n+\t\t\t\t436B5AE02826F49A00574CD4 /* polling.c in Sources */,\n+\t\t\t\t436B5AE12826F49A00574CD4 /* receive.c in Sources */,\n+\t\t\t\t436B5AE22826F49A00574CD4 /* jniutil.c in Sources */,\n+\t\t\t\t436B5AE32826F49A00574CD4 /* init.c in Sources */,\n+\t\t\t\t436B5AE42826F49A00574CD4 /* tipc.c in Sources */,\n+\t\t\t\t436B5AE52826F49A00574CD4 /* config.c in Sources */,\n+\t\t\t\t436B5AE62826F49A00574CD4 /* credentials.c in Sources */,\n+\t\t\t\t436B5AE72826F49A00574CD4 /* socketpair.c in Sources */,\n+\t\t\t\t436B5AE82826F49A00574CD4 /* exceptions.c in Sources */,\n+\t\t\t\t436B5AE92826F49A00574CD4 /* reflection.c in Sources */,\n+\t\t\t\t436B5AEA2826F49A00574CD4 /* listen.c in Sources */,\n+\t\t\t\t436B5AEB2826F49A00574CD4 /* ancillary.c in Sources */,\n+\t\t\t\t436B5AEC2826F49A00574CD4 /* accept.c in Sources */,\n+\t\t\t);\n+\t\t\trunOnlyForDeploymentPostprocessing = 0;\n+\t\t};\n \t\t43B3DFEA26660A2D0024822F /* Sources */ = {\n \t\t\tisa = PBXSourcesBuildPhase;\n \t\t\tbuildActionMask = 2147483647;\n@@ -2458,6 +2959,7 @@\n \t\t\t\t43B3DFF526660A2D0024822F /* receive.c in Sources */,\n \t\t\t\t43B3DFF626660A2D0024822F /* jniutil.c in Sources */,\n \t\t\t\t43B3DFF726660A2D0024822F /* init.c in Sources */,\n+\t\t\t\t436E167F27FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t43B3DFF826660A2D0024822F /* config.c in Sources */,\n \t\t\t\t43B3DFF926660A2D0024822F /* credentials.c in Sources */,\n \t\t\t\t43B3DFFA26660A2D0024822F /* socketpair.c in Sources */,\n@@ -2486,6 +2988,7 @@\n \t\t\t\t43B3E02D26672FD30024822F /* receive.c in Sources */,\n \t\t\t\t43B3E02E26672FD30024822F /* jniutil.c in Sources */,\n \t\t\t\t43B3E02F26672FD30024822F /* init.c in Sources */,\n+\t\t\t\t436E168027FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t43B3E03026672FD30024822F /* config.c in Sources */,\n \t\t\t\t43B3E03126672FD30024822F /* credentials.c in Sources */,\n \t\t\t\t43B3E03226672FD30024822F /* socketpair.c in Sources */,\n@@ -2514,6 +3017,7 @@\n \t\t\t\t43B3E065266756540024822F /* receive.c in Sources */,\n \t\t\t\t43B3E066266756540024822F /* jniutil.c in Sources */,\n \t\t\t\t43B3E067266756540024822F /* init.c in Sources */,\n+\t\t\t\t436E167427FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t43B3E068266756540024822F /* config.c in Sources */,\n \t\t\t\t43B3E069266756540024822F /* credentials.c in Sources */,\n \t\t\t\t43B3E06A266756540024822F /* socketpair.c in Sources */,\n@@ -2542,6 +3046,7 @@\n \t\t\t\t43B3E09D266971630024822F /* receive.c in Sources */,\n \t\t\t\t43B3E09E266971630024822F /* jniutil.c in Sources */,\n \t\t\t\t43B3E09F266971630024822F /* init.c in Sources */,\n+\t\t\t\t436E168127FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t43B3E0A0266971630024822F /* config.c in Sources */,\n \t\t\t\t43B3E0A1266971630024822F /* credentials.c in Sources */,\n \t\t\t\t43B3E0A2266971630024822F /* socketpair.c in Sources */,\n@@ -2570,6 +3075,7 @@\n \t\t\t\t4302347D2650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t4302341D2650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234DD2650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167527FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430233F92650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235B52650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFB9266082000024822F /* socketpair.c in Sources */,\n@@ -2598,6 +3104,7 @@\n \t\t\t\t430234832650AB4E00823167 /* receive.c in Sources */,\n \t\t\t\t430234232650AB4E00823167 /* jniutil.c in Sources */,\n \t\t\t\t430234E32650AB4F00823167 /* init.c in Sources */,\n+\t\t\t\t436E167B27FBB70B00A553EC /* tipc.c in Sources */,\n \t\t\t\t430233FF2650AB4E00823167 /* config.c in Sources */,\n \t\t\t\t430235BB2650AB4F00823167 /* credentials.c in Sources */,\n \t\t\t\t43B3DFBF266082000024822F /* socketpair.c in Sources */,\n@@ -2672,6 +3179,21 @@\n \t\t\ttarget = 432EF1F7261ADEDD00F4A583 /* armv6--linux-gnueabihf */;\n \t\t\ttargetProxy = 432EF204261AE01000F4A583 /* PBXContainerItemProxy */;\n \t\t};\n+\t\t43684DB9282EE2CA005F2989 /* PBXTargetDependency */ = {\n+\t\t\tisa = PBXTargetDependency;\n+\t\t\ttarget = 43684D80282EE24B005F2989 /* aarch64-w64-mingw32 */;\n+\t\t\ttargetProxy = 43684DB8282EE2CA005F2989 /* PBXContainerItemProxy */;\n+\t\t};\n+\t\t436B5AB928244D5700574CD4 /* PBXTargetDependency */ = {\n+\t\t\tisa = PBXTargetDependency;\n+\t\t\ttarget = 436B5A8028244CB500574CD4 /* powerpc-ibm-aix7.2 */;\n+\t\t\ttargetProxy = 436B5AB828244D5700574CD4 /* PBXContainerItemProxy */;\n+\t\t};\n+\t\t436B5AF32827E55000574CD4 /* PBXTargetDependency */ = {\n+\t\t\tisa = PBXTargetDependency;\n+\t\t\ttarget = 436B5ABA2826F49A00574CD4 /* powerpc-ibm-os400 */;\n+\t\t\ttargetProxy = 436B5AF22827E55000574CD4 /* PBXContainerItemProxy */;\n+\t\t};\n \t\t43B3E00626660A7A0024822F /* PBXTargetDependency */ = {\n \t\t\tisa = PBXTargetDependency;\n \t\t\ttarget = 43B3DFCF26660A2D0024822F /* x86_64-unknown-netbsd9.0 */;\n@@ -2725,7 +3247,7 @@\n \t\t\t\t\t\"-nostdlib\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -2754,7 +3276,7 @@\n \t\t\t\t\t\"-nostdlib\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -2797,7 +3319,7 @@\n \t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -2822,7 +3344,7 @@\n \t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -2852,7 +3374,7 @@\n \t\t\t\t\t\"-Xcrossclang-output-strip-lib-prefix\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -2882,7 +3404,7 @@\n \t\t\t\t\t\"-Xcrossclang-output-strip-lib-prefix\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -2909,7 +3431,7 @@\n \t\t\t\t\t\"-nostdlib\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -2936,7 +3458,7 @@\n \t\t\t\t\t\"-nostdlib\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -2962,7 +3484,7 @@\n \t\t\t\t\t\"-fno-lto\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -2988,7 +3510,7 @@\n \t\t\t\t\t\"-fno-lto\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -3013,7 +3535,7 @@\n \t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -3038,7 +3560,7 @@\n \t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -3063,7 +3585,7 @@\n \t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -3088,7 +3610,7 @@\n \t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -3117,7 +3639,7 @@\n \t\t\t\t\tllvm,\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -3146,7 +3668,7 @@\n \t\t\t\t\tllvm,\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -3171,7 +3693,7 @@\n \t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -3196,7 +3718,7 @@\n \t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -3302,6 +3824,216 @@\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n+\t\t43684DB5282EE24B005F2989 /* Debug */ = {\n+\t\t\tisa = XCBuildConfiguration;\n+\t\t\tbuildSettings = {\n+\t\t\t\tCLANG_ENABLE_OBJC_WEAK = YES;\n+\t\t\t\tCROSSCLANG_TARGET = \"aarch64-w64-mingw32\";\n+\t\t\t\tEXECUTABLE_EXTENSION = so;\n+\t\t\t\tLD_DEPENDENCY_INFO_FILE = \"\";\n+\t\t\t\tLD_LTO_OBJECT_FILE = \"\";\n+\t\t\t\tMACOSX_DEPLOYMENT_TARGET = \"\";\n+\t\t\t\tOTHER_CFLAGS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=aarch64-w64-mingw32-gcc\",\n+\t\t\t\t);\n+\t\t\t\tOTHER_LDFLAGS = (\n+\t\t\t\t\t\"$(inheritedx)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n+\t\t\t\t\t\"-lws2_32\",\n+\t\t\t\t\t\"-ladvapi32\",\n+\t\t\t\t\t\"-lmswsock\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=aarch64-w64-mingw32-gcc\",\n+\t\t\t\t\t\"-Xcrossclang-output-strip-lib-prefix\",\n+\t\t\t\t\t\"-Xcrossclang-ignore-export-dynamic\",\n+\t\t\t\t);\n+\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n+\t\t\t};\n+\t\t\tname = Debug;\n+\t\t};\n+\t\t43684DB6282EE24B005F2989 /* Release */ = {\n+\t\t\tisa = XCBuildConfiguration;\n+\t\t\tbuildSettings = {\n+\t\t\t\tCLANG_ENABLE_OBJC_WEAK = YES;\n+\t\t\t\tCROSSCLANG_TARGET = \"aarch64-w64-mingw32\";\n+\t\t\t\tEXECUTABLE_EXTENSION = so;\n+\t\t\t\tLD_DEPENDENCY_INFO_FILE = \"\";\n+\t\t\t\tLD_LTO_OBJECT_FILE = \"\";\n+\t\t\t\tMACOSX_DEPLOYMENT_TARGET = \"\";\n+\t\t\t\tOTHER_CFLAGS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=aarch64-w64-mingw32-gcc\",\n+\t\t\t\t);\n+\t\t\t\tOTHER_LDFLAGS = (\n+\t\t\t\t\t\"$(inheritedx)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n+\t\t\t\t\t\"-lWs2_32\",\n+\t\t\t\t\t\"-lAdvApi32\",\n+\t\t\t\t\t\"-lMswsock\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=aarch64-w64-mingw32-gcc\",\n+\t\t\t\t\t\"-Xcrossclang-output-strip-lib-prefix\",\n+\t\t\t\t\t\"-Xcrossclang-ignore-export-dynamic\",\n+\t\t\t\t);\n+\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n+\t\t\t};\n+\t\t\tname = Release;\n+\t\t};\n+\t\t436B5AB528244CB500574CD4 /* Debug */ = {\n+\t\t\tisa = XCBuildConfiguration;\n+\t\t\tbuildSettings = {\n+\t\t\t\tCLANG_ENABLE_OBJC_WEAK = YES;\n+\t\t\t\tCROSSCLANG_TARGET = \"powerpc-ibm-aix7.2.0.0\";\n+\t\t\t\tEXECUTABLE_EXTENSION = so;\n+\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n+\t\t\t\t\t_THREAD_SAFE_ERRNO,\n+\t\t\t\t\t\"_BSD=44\",\n+\t\t\t\t\t\"DEBUG=1\",\n+\t\t\t\t);\n+\t\t\t\tLD_DEPENDENCY_INFO_FILE = \"\";\n+\t\t\t\tLD_LTO_OBJECT_FILE = \"\";\n+\t\t\t\tMACOSX_DEPLOYMENT_TARGET = \"\";\n+\t\t\t\tOTHER_CFLAGS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n+\t\t\t\t\t\"-fPIC\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc\",\n+\t\t\t\t\t\"-maix64\",\n+\t\t\t\t);\n+\t\t\t\tOTHER_LDFLAGS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc\",\n+\t\t\t\t\t\"-maix64\",\n+\t\t\t\t\t\"-static-libgcc\",\n+\t\t\t\t\t\"-s\",\n+\t\t\t\t);\n+\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n+\t\t\t\tRUN_CLANG_STATIC_ANALYZER = NO;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n+\t\t\t};\n+\t\t\tname = Debug;\n+\t\t};\n+\t\t436B5AB628244CB500574CD4 /* Release */ = {\n+\t\t\tisa = XCBuildConfiguration;\n+\t\t\tbuildSettings = {\n+\t\t\t\tCLANG_ENABLE_OBJC_WEAK = YES;\n+\t\t\t\tCROSSCLANG_TARGET = \"powerpc-ibm-aix7.2.0.0\";\n+\t\t\t\tEXECUTABLE_EXTENSION = so;\n+\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n+\t\t\t\t\t_THREAD_SAFE_ERRNO,\n+\t\t\t\t\t\"_BSD=44\",\n+\t\t\t\t);\n+\t\t\t\tLD_DEPENDENCY_INFO_FILE = \"\";\n+\t\t\t\tLD_LTO_OBJECT_FILE = \"\";\n+\t\t\t\tMACOSX_DEPLOYMENT_TARGET = \"\";\n+\t\t\t\tOTHER_CFLAGS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n+\t\t\t\t\t\"-fPIC\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc\",\n+\t\t\t\t\t\"-maix64\",\n+\t\t\t\t);\n+\t\t\t\tOTHER_LDFLAGS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc\",\n+\t\t\t\t\t\"-maix64\",\n+\t\t\t\t\t\"-static-libgcc\",\n+\t\t\t\t\t\"-s\",\n+\t\t\t\t);\n+\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n+\t\t\t\tRUN_CLANG_STATIC_ANALYZER = NO;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n+\t\t\t};\n+\t\t\tname = Release;\n+\t\t};\n+\t\t436B5AEF2826F49A00574CD4 /* Debug */ = {\n+\t\t\tisa = XCBuildConfiguration;\n+\t\t\tbuildSettings = {\n+\t\t\t\tCLANG_ENABLE_OBJC_WEAK = YES;\n+\t\t\t\tCROSSCLANG_TARGET = \"powerpc-ibm-os400\";\n+\t\t\t\tEXECUTABLE_EXTENSION = so;\n+\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n+\t\t\t\t\t_THREAD_SAFE_ERRNO,\n+\t\t\t\t\t\"_BSD=44\",\n+\t\t\t\t\t\"DEBUG=1\",\n+\t\t\t\t\t_OS400,\n+\t\t\t\t);\n+\t\t\t\tLD_DEPENDENCY_INFO_FILE = \"\";\n+\t\t\t\tLD_LTO_OBJECT_FILE = \"\";\n+\t\t\t\tMACOSX_DEPLOYMENT_TARGET = \"\";\n+\t\t\t\tOTHER_CFLAGS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n+\t\t\t\t\t\"-fPIC\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc\",\n+\t\t\t\t\t\"-maix64\",\n+\t\t\t\t);\n+\t\t\t\tOTHER_LDFLAGS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"powerpc-ibm-aix7.2.0.0\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc\",\n+\t\t\t\t\t\"-maix64\",\n+\t\t\t\t\t\"-static-libgcc\",\n+\t\t\t\t\t\"-s\",\n+\t\t\t\t);\n+\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n+\t\t\t\tRUN_CLANG_STATIC_ANALYZER = NO;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n+\t\t\t};\n+\t\t\tname = Debug;\n+\t\t};\n+\t\t436B5AF02826F49A00574CD4 /* Release */ = {\n+\t\t\tisa = XCBuildConfiguration;\n+\t\t\tbuildSettings = {\n+\t\t\t\tCLANG_ENABLE_OBJC_WEAK = YES;\n+\t\t\t\tCROSSCLANG_TARGET = \"powerpc-ibm-os400\";\n+\t\t\t\tEXECUTABLE_EXTENSION = so;\n+\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n+\t\t\t\t\t_THREAD_SAFE_ERRNO,\n+\t\t\t\t\t\"_BSD=44\",\n+\t\t\t\t\t_OS400,\n+\t\t\t\t);\n+\t\t\t\tLD_DEPENDENCY_INFO_FILE = \"\";\n+\t\t\t\tLD_LTO_OBJECT_FILE = \"\";\n+\t\t\t\tMACOSX_DEPLOYMENT_TARGET = \"\";\n+\t\t\t\tOTHER_CFLAGS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n+\t\t\t\t\t\"-fPIC\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc\",\n+\t\t\t\t\t\"-maix64\",\n+\t\t\t\t);\n+\t\t\t\tOTHER_LDFLAGS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"-target\",\n+\t\t\t\t\t\"powerpc-ibm-aix7.2.0.0\",\n+\t\t\t\t\t\"-Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc\",\n+\t\t\t\t\t\"-maix64\",\n+\t\t\t\t\t\"-static-libgcc\",\n+\t\t\t\t\t\"-s\",\n+\t\t\t\t);\n+\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n+\t\t\t\tRUN_CLANG_STATIC_ANALYZER = NO;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n+\t\t\t};\n+\t\t\tname = Release;\n+\t\t};\n \t\t43B3E00226660A2D0024822F /* Debug */ = {\n \t\t\tisa = XCBuildConfiguration;\n \t\t\tbuildSettings = {\n@@ -3324,7 +4056,7 @@\n \t\t\t\t\t\"-Wl,--no-rosegment,--disable-new-dtags,-znognustack,-znoseparate-code,-znorelro\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -3350,7 +4082,7 @@\n \t\t\t\t\t\"-Wl,--no-rosegment,--disable-new-dtags,-znognustack,-znoseparate-code,-znorelro\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -3375,7 +4107,7 @@\n \t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -3400,7 +4132,7 @@\n \t\t\t\t\t\"$(CROSSCLANG_TARGET)\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -3426,7 +4158,7 @@\n \t\t\t\t\t\"-Wl,--no-rosegment,--disable-new-dtags\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -3452,7 +4184,7 @@\n \t\t\t\t\t\"-Wl,--no-rosegment,--disable-new-dtags\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -3485,7 +4217,7 @@\n \t\t\t\t\t\"-lrt\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -3518,7 +4250,7 @@\n \t\t\t\t\t\"-lrt\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -3751,7 +4483,12 @@\n \t\t\t\t\t\"-nostdlib\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n+\t\t\t\tSYSTEM_HEADER_SEARCH_PATHS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"$(SDKROOT)$(CROSSCLANGROOT)/usr/include\",\n+\t\t\t\t\t\"/opt/crossclang/target-sdks/x86_64-alpine-linux-musl/usr/include\",\n+\t\t\t\t);\n \t\t\t};\n \t\t\tname = Debug;\n \t\t};\n@@ -3778,7 +4515,12 @@\n \t\t\t\t\t\"-nostdlib\",\n \t\t\t\t);\n \t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n-\t\t\t\tSDKROOT = crossclang;\n+\t\t\t\tSDKROOT = crossclang.macosx1.0;\n+\t\t\t\tSYSTEM_HEADER_SEARCH_PATHS = (\n+\t\t\t\t\t\"$(inherited)\",\n+\t\t\t\t\t\"$(SDKROOT)$(CROSSCLANGROOT)/usr/include\",\n+\t\t\t\t\t\"/opt/crossclang/target-sdks/x86_64-alpine-linux-musl/usr/include\",\n+\t\t\t\t);\n \t\t\t};\n \t\t\tname = Release;\n \t\t};\n@@ -3893,6 +4635,33 @@\n \t\t\tdefaultConfigurationIsVisible = 0;\n \t\t\tdefaultConfigurationName = Release;\n \t\t};\n+\t\t43684DB4282EE24B005F2989 /* Build configuration list for PBXNativeTarget \"aarch64-w64-mingw32\" */ = {\n+\t\t\tisa = XCConfigurationList;\n+\t\t\tbuildConfigurations = (\n+\t\t\t\t43684DB5282EE24B005F2989 /* Debug */,\n+\t\t\t\t43684DB6282EE24B005F2989 /* Release */,\n+\t\t\t);\n+\t\t\tdefaultConfigurationIsVisible = 0;\n+\t\t\tdefaultConfigurationName = Release;\n+\t\t};\n+\t\t436B5AB428244CB500574CD4 /* Build configuration list for PBXNativeTarget \"powerpc-ibm-aix7.2\" */ = {\n+\t\t\tisa = XCConfigurationList;\n+\t\t\tbuildConfigurations = (\n+\t\t\t\t436B5AB528244CB500574CD4 /* Debug */,\n+\t\t\t\t436B5AB628244CB500574CD4 /* Release */,\n+\t\t\t);\n+\t\t\tdefaultConfigurationIsVisible = 0;\n+\t\t\tdefaultConfigurationName = Release;\n+\t\t};\n+\t\t436B5AEE2826F49A00574CD4 /* Build configuration list for PBXNativeTarget \"powerpc-ibm-os400\" */ = {\n+\t\t\tisa = XCConfigurationList;\n+\t\t\tbuildConfigurations = (\n+\t\t\t\t436B5AEF2826F49A00574CD4 /* Debug */,\n+\t\t\t\t436B5AF02826F49A00574CD4 /* Release */,\n+\t\t\t);\n+\t\t\tdefaultConfigurationIsVisible = 0;\n+\t\t\tdefaultConfigurationName = Release;\n+\t\t};\n \t\t43B3E00126660A2D0024822F /* Build configuration list for PBXNativeTarget \"x86_64-unknown-netbsd9.0\" */ = {\n \t\t\tisa = XCConfigurationList;\n \t\t\tbuildConfigurations = (\ndiff --git a/junixsocket-native/junixsocket-native.xcodeproj/xcshareddata/xcschemes/aarch64-w64-mingw32.xcscheme b/junixsocket-native/junixsocket-native.xcodeproj/xcshareddata/xcschemes/aarch64-w64-mingw32.xcscheme\nnew file mode 100644\nindex 000000000..f600fdcf4\n--- /dev/null\n+++ b/junixsocket-native/junixsocket-native.xcodeproj/xcshareddata/xcschemes/aarch64-w64-mingw32.xcscheme\n@@ -0,0 +1,67 @@\n+\n+\n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+\ndiff --git a/junixsocket-native/junixsocket-native.xcodeproj/xcshareddata/xcschemes/powerpc-ibm-aix7.2.xcscheme b/junixsocket-native/junixsocket-native.xcodeproj/xcshareddata/xcschemes/powerpc-ibm-aix7.2.xcscheme\nnew file mode 100644\nindex 000000000..b3d78f413\n--- /dev/null\n+++ b/junixsocket-native/junixsocket-native.xcodeproj/xcshareddata/xcschemes/powerpc-ibm-aix7.2.xcscheme\n@@ -0,0 +1,67 @@\n+\n+\n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+\ndiff --git a/junixsocket-native/junixsocket-native.xcodeproj/xcshareddata/xcschemes/powerpc-ibm-os400.xcscheme b/junixsocket-native/junixsocket-native.xcodeproj/xcshareddata/xcschemes/powerpc-ibm-os400.xcscheme\nnew file mode 100644\nindex 000000000..8fa3ed8f2\n--- /dev/null\n+++ b/junixsocket-native/junixsocket-native.xcodeproj/xcshareddata/xcschemes/powerpc-ibm-os400.xcscheme\n@@ -0,0 +1,67 @@\n+\n+\n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+\ndiff --git a/junixsocket-native/pom.xml b/junixsocket-native/pom.xml\nindex b54f99741..b740b84e9 100644\n--- a/junixsocket-native/pom.xml\n+++ b/junixsocket-native/pom.xml\n@@ -8,7 +8,7 @@\n \n com.kohlschutter.junixsocket\n junixsocket-parent\n- 2.4.1-SNAPSHOT\n+ 2.5.0-SNAPSHOT\n ../pom.xml\n \n junixsocket-native\ndiff --git a/junixsocket-native/src/main/c/accept.c b/junixsocket-native/src/main/c/accept.c\nindex 4e26614ca..fcef0f998 100644\n--- a/junixsocket-native/src/main/c/accept.c\n+++ b/junixsocket-native/src/main/c/accept.c\n@@ -27,27 +27,35 @@\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: accept\n- * Signature: ([BLjava/io/FileDescriptor;Ljava/io/FileDescriptor;JI)Z\n+ * Signature: (Ljava/nio/ByteBuffer;ILjava/io/FileDescriptor;Ljava/io/FileDescriptor;JI)Z\n */\n-JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_accept(\n- JNIEnv * env, jclass clazz CK_UNUSED, jbyteArray addr, jobject fdServer,\n- jobject fd, jlong expectedInode, int timeout)\n+JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_accept\n+(\n+ JNIEnv * env, jclass clazz CK_UNUSED, jobject ab, jint abLen, jobject fdServer,\n+ jobject fd, jlong expectedInode, int timeout)\n {\n CK_ARGUMENT_POTENTIALLY_UNUSED(timeout);\n \n- struct sockaddr_un su = {0};\n- socklen_t suLength = 0;\n+ jux_sockaddr_t *addr = (*env)->GetDirectBufferAddress(env, ab);\n+ socklen_t suLength = (socklen_t)abLen;\n \n int serverHandle = _getFD(env, fdServer);\n+ if(serverHandle < 0) {\n+ _throwException(env, kExceptionSocketException, \"Socket is closed\");\n+ return false;\n+ }\n \n- if(expectedInode > 0) {\n- suLength = initSu(env, &su, addr);\n+ if(expectedInode > 0 && suLength > 0) {\n+ if(addr->addr.sa_family != AF_UNIX) {\n+ _throwException(env, kExceptionSocketException, \"Cannot check inode for this type of socket\");\n+ return false;\n+ }\n \n- if(suLength > 0 && su.sun_path[0] != 0) {\n+ if(addr->un.sun_path[0] != 0) {\n struct stat fdStat;\n \n // It's OK when the file's gone, but not OK if it refers to another inode.\n- int statRes = stat(su.sun_path, &fdStat);\n+ int statRes = stat(addr->un.sun_path, &fdStat);\n if(statRes == 0) {\n ino_t statInode = fdStat.st_ino;\n \n@@ -74,18 +82,16 @@ JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_accept(\n }\n #endif\n \n- suLength = sizeof(struct sockaddr_un);\n-\n int socketHandle;\n int errnum = 0;\n do {\n #if defined(junixsocket_have_accept4)\n- socketHandle = accept4(serverHandle, (struct sockaddr *)&su, &suLength, SOCK_CLOEXEC);\n+ socketHandle = accept4(serverHandle, (struct sockaddr *)addr, &suLength, SOCK_CLOEXEC);\n if(socketHandle == -1 && errno == ENOSYS) {\n- socketHandle = accept(serverHandle, (struct sockaddr *)&su, &suLength);\n+ socketHandle = accept(serverHandle, (struct sockaddr *)addr, &suLength);\n }\n #else\n- socketHandle = accept(serverHandle, (struct sockaddr *)&su, &suLength);\n+ socketHandle = accept(serverHandle, (struct sockaddr *)addr, &suLength);\n #endif\n } while(socketHandle == -1 && (errnum = socket_errno) == EINTR);\n \n@@ -93,15 +99,16 @@ JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_accept(\n if(checkNonBlocking(serverHandle, errnum)) {\n // non-blocking socket, nothing to accept\n } else {\n- _throwErrnumException(env, errnum, fdServer);\n+ _throwSockoptErrnumException(env, errnum, fdServer);\n }\n return false;\n }\n \n #if !defined(junixsocket_have_accept4)\n # if defined(_WIN32)\n- HANDLE h = (HANDLE)_get_osfhandle(socketHandle);\n- SetHandleInformation(h, HANDLE_FLAG_INHERIT, 0);\n+ // FIXME -- crashes on some Windows versions/compilers; omitting since it's non-essential\n+ // HANDLE h = (HANDLE)_get_osfhandle(socketHandle);\n+ // SetHandleInformation(h, HANDLE_FLAG_INHERIT, 0);\n # elif defined(FD_CLOEXEC)\n fcntl(socketHandle, F_SETFD, FD_CLOEXEC);\n # endif\ndiff --git a/junixsocket-native/src/main/c/address.c b/junixsocket-native/src/main/c/address.c\nindex fdb047659..6a530bad9 100644\n--- a/junixsocket-native/src/main/c/address.c\n+++ b/junixsocket-native/src/main/c/address.c\n@@ -22,10 +22,33 @@\n #include \"exceptions.h\"\n #include \"filedescriptors.h\"\n #include \"jniutil.h\"\n+#include \"socket.h\"\n \n // Either we have sun_len (and we can skip the null byte), or we add the null byte at the end\n static const socklen_t SUN_NAME_MAX_LEN = (socklen_t)(sizeof(struct sockaddr_un) - 2);\n \n+struct __attribute__((__packed__)) jux_tipc_addr {\n+ jint addrType;\n+ jint scope;\n+ jint a;\n+ jint b;\n+ jint c;\n+};\n+\n+int domainToNative(int domain) {\n+ switch(domain) {\n+ case org_newsclub_net_unix_NativeUnixSocket_DOMAIN_UNIX:\n+ return AF_UNIX;\n+#if junixsocket_have_tipc\n+ case org_newsclub_net_unix_NativeUnixSocket_DOMAIN_TIPC:\n+ return AF_TIPC;\n+#endif\n+ default:\n+ // do not throw: _throwException(env, kExceptionSocketException, \"Unsupported domain\");\n+ return -1;\n+ }\n+}\n+\n /**\n * Initializes a sockaddr_un given a byte[] address, returning the socklen,\n * or 0 if an error occurred.\n@@ -77,13 +100,27 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_maxAddressLen\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n- * Method: sockAddrUnLength\n- * Signature: ()I\n+ * Method: sockAddrLength\n+ * Signature: (I)I\n */\n-JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrUnLength\n-(JNIEnv * env CK_UNUSED, jclass clazz CK_UNUSED)\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrLength\n+(JNIEnv * env, jclass clazz CK_UNUSED, jint domain)\n {\n- return sizeof(struct sockaddr_un);\n+ if(domain == 0) {\n+ // return maximum size of any supported address.\n+ return sizeof(jux_sockaddr_t);\n+ }\n+ switch(domainToNative(domain)) {\n+ case AF_UNIX:\n+ return sizeof(struct sockaddr_un);\n+#if junixsocket_have_tipc\n+ case AF_TIPC:\n+ return sizeof(struct sockaddr_tipc);\n+#endif\n+ default:\n+ _throwException(env, kExceptionSocketException, \"Unsupported domain\");\n+ return -1;\n+ }\n }\n \n static jbyteArray sockAddrUnToBytes(JNIEnv *env, struct sockaddr_un *addr, socklen_t len) {\n@@ -91,7 +128,8 @@ static jbyteArray sockAddrUnToBytes(JNIEnv *env, struct sockaddr_un *addr, sockl\n return NULL;\n }\n #if defined(junixsocket_have_sun_len)\n- if(addr->sun_len < len) {\n+ len = MIN(len, sizeof(struct sockaddr_un)-2);\n+ if(len < 256 && addr->sun_len < len) {\n len = addr->sun_len;\n }\n #endif\n@@ -127,17 +165,43 @@ static jbyteArray sockAddrUnToBytes(JNIEnv *env, struct sockaddr_un *addr, sockl\n return array;\n }\n \n+#if junixsocket_have_tipc\n+\n+static jbyteArray sockAddrTipcToBytes(JNIEnv *env, struct sockaddr_tipc *addr) {\n+ CK_IGNORE_RESERVED_IDENTIFIER_BEGIN // htonl\n+ struct jux_tipc_addr buf = {\n+ .addrType = htonl(addr->addrtype),\n+ .scope = htonl(addr->scope),\n+ .a = htonl(addr->addr.nameseq.type),\n+ .b = htonl(addr->addr.nameseq.lower),\n+ .c = htonl(addr->addr.nameseq.upper)\n+ };\n+ CK_IGNORE_RESERVED_IDENTIFIER_END\n+\n+ jbyteArray array = (*env)->NewByteArray(env, sizeof(struct jux_tipc_addr));\n+ (*env)->SetByteArrayRegion(env, array, 0, sizeof(struct jux_tipc_addr), (jbyte*)&buf);\n+ return array;\n+}\n+\n+#endif\n+\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: sockname\n- * Signature: (Ljava/io/FileDescriptor;Z)[B\n+ * Signature: (ILjava/io/FileDescriptor;Z)[B\n */\n JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockname\n-(JNIEnv * env, jclass clazz CK_UNUSED, jobject fd, jboolean peerName) {\n+(JNIEnv * env, jclass clazz CK_UNUSED, jint domain, jobject fd, jboolean peerName) {\n int handle = _getFD(env, fd);\n \n- struct sockaddr_un addr = {0};\n- socklen_t len = sizeof(struct sockaddr_un);\n+ domain = domainToNative(domain);\n+ if(domain == -1) {\n+ _throwException(env, kExceptionSocketException, \"Unsupported domain\");\n+ return NULL;\n+ }\n+\n+ jux_sockaddr_t addr = {0};\n+ socklen_t len = sizeof(jux_sockaddr_t);\n \n int ret;\n if(peerName) {\n@@ -146,37 +210,75 @@ JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socknam\n ret = getsockname(handle, (struct sockaddr *)&addr, &len);\n }\n \n- if(ret != 0) {\n+ if(ret == -1) {\n int errnum = socket_errno;\n- if(errnum != ENOTCONN) {\n- _throwErrnumException(env, errnum, fd);\n+ switch(errnum) {\n+ case ENOTCONN:\n+ case EINVAL:\n+ case EBADF:\n+ case ENOTSOCK: // OSv socketpair\n+ // not connected or otherwise invalid\n+ break;\n+ default:\n+ _throwErrnumException(env, errnum, fd);\n }\n return NULL;\n }\n \n- if(len > (socklen_t)sizeof(struct sockaddr_un)) {\n+ if(len > (socklen_t)sizeof(jux_sockaddr_t)) {\n _throwException(env, kExceptionSocketException,\n- peerName ? \"peer name too long\" : \"socket name too long\");\n+ peerName ? \"peer sockname too long\" : \"sockname too long\");\n return NULL;\n }\n \n- if(len == 0) {\n+ if(len <= 2) {\n // hat tip: https://github.com/wahern/cqueues/blob/master/PORTING.md\n+ // also: Linux may return an incomplete address\n+ return NULL;\n+ }\n+\n+ if(addr.addr.sa_family != domain) {\n+#if defined(_WIN32)\n+ if(addr.addr.sa_family == AF_INET && domain == AF_UNIX) {\n+ // socketpair emulation uses AF_INET sockets\n+ // just return NULL here; it's OK.\n+ return NULL;\n+ }\n+#endif\n+ _throwException(env, kExceptionSocketException,\n+ \"Unexpected socket address family\");\n return NULL;\n }\n \n switch(((struct sockaddr *)&addr)->sa_family) {\n case AF_UNIX:\n+ {\n+ if(len > (socklen_t)sizeof(struct sockaddr_un)) {\n+ _throwException(env, kExceptionSocketException,\n+ peerName ? \"peer sockname too long\" : \"sockname too long\");\n+ return NULL;\n+ }\n+\n #if defined(junixsocket_have_sun_len)\n- len -= 2;\n+ len -= 2;\n #else\n- len -= 1;\n+ len -= 1;\n #endif\n- return sockAddrUnToBytes(env, (struct sockaddr_un *)&addr, len);\n+ return sockAddrUnToBytes(env, (struct sockaddr_un *)&addr, len);\n+ }\n #if defined(_WIN32)\n case AF_INET:\n // only to support our \"socketpair\" workaround (which we expected to return NULL here on UNIX)\n return NULL;\n+#endif\n+#if junixsocket_have_tipc\n+ case AF_TIPC:\n+ if(len > (socklen_t)sizeof(struct sockaddr_tipc)) {\n+ _throwException(env, kExceptionSocketException,\n+ peerName ? \"peer sockname too long\" : \"sockname too long\");\n+ return NULL;\n+ }\n+ return sockAddrTipcToBytes(env, &addr.tipc);\n #endif\n default:\n _throwException(env, kExceptionSocketException,\n@@ -187,50 +289,154 @@ JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socknam\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n- * Method: sockAddrUnToBytes\n- * Signature: (Ljava/nio/ByteBuffer;)[B\n+ * Method: sockAddrToBytes\n+ * Signature: (ILjava/nio/ByteBuffer;)[B\n */\n-JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrUnToBytes\n-(JNIEnv *env, jclass clazz CK_UNUSED, jobject directByteBuf) {\n+JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrToBytes\n+(JNIEnv *env, jclass clazz CK_UNUSED, jint domain, jobject directByteBuf) {\n+ domain = domainToNative(domain);\n+ size_t sockAddrLen;\n+ switch(domain) {\n+ case AF_UNIX:\n+ sockAddrLen = sizeof(struct sockaddr_un);\n+ break;\n+#if junixsocket_have_tipc\n+ case AF_TIPC:\n+ sockAddrLen = sizeof(struct sockaddr_tipc);\n+ break;\n+#endif\n+ default:\n+ _throwException(env, kExceptionSocketException, \"Unsupported domain\");\n+ return NULL;\n+ }\n+\n struct jni_direct_byte_buffer_ref directByteBufRef =\n- getDirectByteBufferRef (env, directByteBuf, 0, sizeof(struct sockaddr_un));\n+ getDirectByteBufferRef (env, directByteBuf, 0, sockAddrLen);\n if(directByteBufRef.size <= 0) {\n _throwException(env, kExceptionSocketException, \"Invalid byte buffer\");\n return NULL;\n }\n \n- struct sockaddr_un *addr = (struct sockaddr_un *)directByteBufRef.buf;\n- return sockAddrUnToBytes(env, addr, SUN_NAME_MAX_LEN);\n+ jux_sockaddr_t *addr = (jux_sockaddr_t *)directByteBufRef.buf;\n+ if(addr->addr.sa_family != domain) {\n+ if(addr->addr.sa_family == 0) {\n+ return NULL;\n+ }\n+#if defined(_WIN32)\n+ if(addr->addr.sa_family == AF_INET && domain == AF_UNIX) {\n+ // socketpair emulation uses AF_INET sockets\n+ // just return NULL here; it's OK.\n+ return NULL;\n+ }\n+#endif\n+ _throwException(env, kExceptionSocketException, \"Unexpected address family\");\n+ return NULL;\n+ }\n+\n+ switch(domain) {\n+ case AF_UNIX:\n+ return sockAddrUnToBytes(env, (struct sockaddr_un *)addr, SUN_NAME_MAX_LEN);\n+#if junixsocket_have_tipc\n+ case AF_TIPC:\n+ return sockAddrTipcToBytes(env, (struct sockaddr_tipc *)addr);\n+#endif\n+ default:\n+ _throwException(env, kExceptionSocketException, \"Unsupported domain\");\n+ return NULL;\n+ }\n }\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n- * Method: bytesToSockAddrUn\n- * Signature: (Ljava/nio/ByteBuffer;[B)V\n+ * Method: bytesToSockAddr\n+ * Signature: (ILjava/nio/ByteBuffer;[B)I\n */\n-JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bytesToSockAddrUn\n-(JNIEnv *env, jclass clazz CK_UNUSED, jobject directByteBuf, jbyteArray addressBytes) {\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bytesToSockAddr\n+(JNIEnv *env, jclass clazz CK_UNUSED, jint domain, jobject directByteBuf, jbyteArray addressBytes) {\n+ domain = domainToNative(domain);\n+ size_t sockAddrLen;\n+ switch(domain) {\n+ case AF_UNIX:\n+ sockAddrLen = sizeof(struct sockaddr_un);\n+ break;\n+#if junixsocket_have_tipc\n+ case AF_TIPC:\n+ sockAddrLen = sizeof(struct sockaddr_tipc);\n+ break;\n+#endif\n+ default:\n+ // do not throw: _throwException(env, kExceptionSocketException, \"Unsupported domain\");\n+ return -1;\n+ }\n+\n struct jni_direct_byte_buffer_ref directByteBufRef =\n- getDirectByteBufferRef (env, directByteBuf, 0, sizeof(struct sockaddr_un));\n+ getDirectByteBufferRef (env, directByteBuf, 0, sockAddrLen);\n if(directByteBufRef.size <= 0) {\n _throwException(env, kExceptionSocketException, \"Invalid byte buffer\");\n- return;\n+ return -1;\n }\n \n jsize len = addressBytes == NULL ? 0 : (*env)->GetArrayLength(env, addressBytes);\n if(len > directByteBufRef.size || len > INT_MAX) {\n _throwException(env, kExceptionSocketException, \"Byte array is too large\");\n- return;\n+ return -1;\n }\n \n- struct sockaddr_un *addr = (struct sockaddr_un *)directByteBufRef.buf;\n- memset(directByteBufRef.buf, 0, sizeof(struct sockaddr_un));\n- addr->sun_family = AF_UNIX;\n+ jux_sockaddr_t *addr = (jux_sockaddr_t *)directByteBufRef.buf;\n+ memset(directByteBufRef.buf, 0, sockAddrLen);\n \n- if(len > 0) {\n+ addr->addr.sa_family = domain;\n+ if(len <= 0) {\n+ return 0;\n+ }\n+\n+ switch(domain) {\n+ case AF_UNIX:\n+ {\n+ struct sockaddr_un *addrUn = (struct sockaddr_un *) addr;\n #if defined(junixsocket_have_sun_len)\n- addr->sun_len = ((socklen_t)len >= SUN_NAME_MAX_LEN) ? SUN_NAME_MAX_LEN : len + 1; // including zero byte\n+ addrUn->sun_len = ((socklen_t)len >= SUN_NAME_MAX_LEN) ? SUN_NAME_MAX_LEN : len + 1; // including zero byte\n+#endif\n+ (*env)->GetByteArrayRegion(env, addressBytes, 0, len, (signed char*)addrUn->sun_path);\n+ }\n+ break;\n+#if junixsocket_have_tipc\n+ case AF_TIPC:\n+ {\n+ struct jux_tipc_addr jaddr = {0};\n+ (*env)->GetByteArrayRegion(env, addressBytes, 0, sizeof(struct jux_tipc_addr), (void*)&jaddr);\n+\n+ CK_IGNORE_RESERVED_IDENTIFIER_BEGIN // ntohl\n+ addr->tipc.addrtype = ntohl(jaddr.addrType);\n+ addr->tipc.scope = ntohl(jaddr.scope);\n+ addr->tipc.addr.nameseq.type = ntohl(jaddr.a);\n+ addr->tipc.addr.nameseq.lower = ntohl(jaddr.b);\n+ addr->tipc.addr.nameseq.upper = ntohl(jaddr.c);\n+ CK_IGNORE_RESERVED_IDENTIFIER_END\n+ }\n+ break;\n #endif\n- (*env)->GetByteArrayRegion(env, addressBytes, 0, len, (signed char*)addr->sun_path);\n }\n+\n+ return (jint)sockAddrLen;\n+}\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: sockAddrDataOffset\n+ * Signature: ()I\n+ */\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrNativeDataOffset\n+ (JNIEnv *env CK_UNUSED, jclass klazz CK_UNUSED) {\n+ return offsetof(struct sockaddr, sa_data);\n+}\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: sockAddrNativeFamily\n+ * Signature: (Ljava/nio/ByteBuffer;)I\n+ */\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrNativeFamilyOffset\n+ (JNIEnv *env CK_UNUSED, jclass klazz CK_UNUSED) {\n+ return offsetof(struct sockaddr, sa_family);\n }\ndiff --git a/junixsocket-native/src/main/c/address.h b/junixsocket-native/src/main/c/address.h\nindex fc7873926..2f08bdb66 100644\n--- a/junixsocket-native/src/main/c/address.h\n+++ b/junixsocket-native/src/main/c/address.h\n@@ -21,6 +21,17 @@\n \n #include \"config.h\"\n \n+typedef union {\n+ struct sockaddr addr;\n+ struct sockaddr_un un;\n+#if junixsocket_have_tipc\n+ struct sockaddr_tipc tipc;\n+#endif\n+ char bytes[128];\n+} jux_sockaddr_t;\n+\n+\n socklen_t initSu(JNIEnv * env, struct sockaddr_un *su, jbyteArray addr);\n+int domainToNative(int domain);\n \n #endif /* address_h */\ndiff --git a/junixsocket-native/src/main/c/ancillary.c b/junixsocket-native/src/main/c/ancillary.c\nindex 0823c34a8..b04dc6558 100644\n--- a/junixsocket-native/src/main/c/ancillary.c\n+++ b/junixsocket-native/src/main/c/ancillary.c\n@@ -55,22 +55,50 @@ static jclass class_AncillaryDataSupport = NULL;\n static jfieldID fieldID_ancillaryReceiveBuffer = NULL;\n static jfieldID fieldID_pendingFileDescriptors = NULL;\n \n-jfieldID getFieldID_ancillaryReceiveBuffer() {\n+static jmethodID kSetTipcErrorInfo = NULL;\n+static jmethodID kSetTipcDestName = NULL;\n+\n+jfieldID getFieldID_ancillaryReceiveBuffer(void) {\n return fieldID_ancillaryReceiveBuffer;\n }\n-jfieldID getFieldID_pendingFileDescriptors() {\n+jfieldID getFieldID_pendingFileDescriptors(void) {\n return fieldID_pendingFileDescriptors;\n }\n+jmethodID getMethodID_setTipcErrorInfo(void) {\n+ return kSetTipcErrorInfo;\n+}\n+jmethodID getMethodID_setTipcDestName(void) {\n+ return kSetTipcDestName;\n+}\n \n void init_ancillary(JNIEnv *env) {\n class_AncillaryDataSupport = findClassAndGlobalRef(env, \"org/newsclub/net/unix/AncillaryDataSupport\");\n fieldID_ancillaryReceiveBuffer = (*env)->GetFieldID(env, class_AncillaryDataSupport, \"ancillaryReceiveBuffer\", \"Ljava/nio/ByteBuffer;\");\n fieldID_pendingFileDescriptors = (*env)->GetFieldID(env, class_AncillaryDataSupport, \"pendingFileDescriptors\", \"[I\");\n+\n+ kSetTipcErrorInfo = (*env)->GetMethodID(env, class_AncillaryDataSupport, \"setTipcErrorInfo\", \"(II)V\");\n+ kSetTipcDestName = (*env)->GetMethodID(env, class_AncillaryDataSupport, \"setTipcDestName\", \"(III)V\");\n }\n void destroy_ancillary(JNIEnv *env) {\n releaseClassGlobalRef(env, class_AncillaryDataSupport);\n fieldID_ancillaryReceiveBuffer = NULL;\n fieldID_pendingFileDescriptors = NULL;\n+ kSetTipcErrorInfo = NULL;\n+ kSetTipcDestName = NULL;\n }\n \n #endif\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: ancillaryBufMinLen\n+ * Signature: ()I\n+ */\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_ancillaryBufMinLen\n+ (JNIEnv *env CK_UNUSED, jclass klazz CK_UNUSED) {\n+#if defined(junixsocket_have_ancillary)\n+ return sizeof(struct cmsghdr);\n+#else\n+ return 0;\n+#endif\n+}\ndiff --git a/junixsocket-native/src/main/c/ancillary.h b/junixsocket-native/src/main/c/ancillary.h\nindex bb1f9f56d..cdb0dad84 100644\n--- a/junixsocket-native/src/main/c/ancillary.h\n+++ b/junixsocket-native/src/main/c/ancillary.h\n@@ -34,6 +34,8 @@ void destroy_ancillary(JNIEnv *env);\n \n jfieldID getFieldID_ancillaryReceiveBuffer(void);\n jfieldID getFieldID_pendingFileDescriptors(void);\n+jmethodID getMethodID_setTipcErrorInfo(void);\n+jmethodID getMethodID_setTipcDestName(void);\n \n #endif\n \ndiff --git a/junixsocket-native/src/main/c/bind.c b/junixsocket-native/src/main/c/bind.c\nindex 9c939e4a2..f90e9ee4b 100644\n--- a/junixsocket-native/src/main/c/bind.c\n+++ b/junixsocket-native/src/main/c/bind.c\n@@ -26,37 +26,62 @@\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: bind\n- * Signature: ([BLjava/io/FileDescriptor;I)J\n+ * Signature: (Ljava/nio/ByteBuffer;ILjava/io/FileDescriptor;I)J\n */\n-JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind(\n- JNIEnv * env, jclass clazz CK_UNUSED, jbyteArray addr, jobject fd, jint options)\n+JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind\n+ (JNIEnv * env, jclass clazz CK_UNUSED, jobject ab, jint abLen, jobject fd, jint options)\n {\n #if defined(_WIN32)\n CK_ARGUMENT_POTENTIALLY_UNUSED(options);\n #endif\n \n- struct sockaddr_un su = {0};\n- socklen_t suLength = initSu(env, &su, addr);\n- if(suLength == 0) {\n- _throwException(env, kExceptionSocketException,\n- \"Socket address length out of range\");\n- return -1;\n- }\n+ // FIXME domain\n+\n+ jux_sockaddr_t *addr = (*env)->GetDirectBufferAddress(env, ab);\n+ socklen_t suLength = (socklen_t)abLen;\n \n int serverHandle = _getFD(env, fd);\n- if(serverHandle <= 0) {\n- _throwException(env, kExceptionSocketException, \"Socket closed\");\n+ if(serverHandle < 0) {\n+ _throwException(env, kExceptionSocketException, \"Socket is closed\");\n return -1;\n }\n \n-#if defined(_WIN32)\n+ if(suLength == 0) {\n+ // unbind / anonymous bind\n+ int bindRes = bind(serverHandle, &addr->addr, 0);\n+ if(bindRes < 0) {\n+ _throwErrnumException(env, socket_errno, NULL);\n+ return -1;\n+ }\n+ _initFD(env, fd, serverHandle);\n+ return 0;\n+ }\n+\n+ if(\n+#if defined(_OS400)\n+ JNI_TRUE\n+#else\n+ addr->addr.sa_family != AF_UNIX\n+#endif\n+ ) {\n+ int bindRes = bind(serverHandle, &addr->addr, suLength);\n+ int myErr = socket_errno;\n+ if(bindRes < 0) {\n+ _throwErrnumException(env, myErr, NULL);\n+ return -1;\n+ }\n+ _initFD(env, fd, serverHandle);\n+ return 0;\n+ }\n \n- if(su.sun_path[0] != 0) {\n- DeleteFileA(su.sun_path);\n+#if defined(_WIN32)\n+ if(addr->addr.sa_family == AF_UNIX && addr->un.sun_path[0] != 0) {\n+ DeleteFileA(addr->un.sun_path);\n }\n \n int bindRes;\n- bindRes = bind(serverHandle, (struct sockaddr *)&su, suLength);\n+\n+ bindRes = bind(serverHandle, (struct sockaddr *)&addr->addr, suLength);\n int myErr = socket_errno;\n _initFD(env, fd, serverHandle);\n \n@@ -67,7 +92,7 @@ JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind(\n return 0;\n }\n #else\n- bool reuse = (options == -1);\n+ bool reuse = ((options & org_newsclub_net_unix_NativeUnixSocket_BIND_OPT_REUSE) != 0) && addr->addr.sa_family == AF_UNIX;\n bool useSuTmp = false;\n struct sockaddr_un suTmp;\n if(reuse) {\n@@ -105,19 +130,20 @@ JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind(\n // prevent raising SIGPIPE\n ret = setsockopt(serverHandle, SOL_SOCKET, SO_NOSIGPIPE, &optVal, sizeof(optVal));\n if(ret == -1) {\n+\n _throwSockoptErrnumException(env, socket_errno, fd);\n return -1;\n }\n #endif\n-\n int bindRes;\n- if(attempt == 0 && !reuse) {\n+\n+ if(attempt == 0 && !reuse && addr->addr.sa_family == AF_UNIX) {\n // if we're not going to reuse the socket, let's try to connect first.\n // This avoids changing file metadata (e.g. ctime!)\n bindRes = -1;\n errno = 0;\n } else {\n- bindRes = bind(serverHandle, (struct sockaddr *)&su, suLength);\n+ bindRes = bind(serverHandle, &addr->addr, suLength);\n }\n \n myErr = socket_errno;\n@@ -126,7 +152,7 @@ JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind(\n break;\n } else if(attempt == 0 && (!reuse || myErr == EADDRINUSE)) {\n if(reuse) {\n- if(su.sun_path[0] == 0) {\n+ if(addr->un.sun_path[0] == 0) {\n // nothing to be done in the abstract namespace\n } else {\n // if we're reusing the socket, it's better to move away the existing\n@@ -136,7 +162,7 @@ JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind(\n strcpy(suTmp.sun_path, \"/tmp/junixsocket.XXXXXX\\0\");\n mkstemp(suTmp.sun_path);\n \n- int renameRet = rename(su.sun_path, suTmp.sun_path);\n+ int renameRet = rename(addr->un.sun_path, suTmp.sun_path);\n if(renameRet == -1) {\n if(socket_errno != ENOENT) {\n // ignore failure\n@@ -157,7 +183,7 @@ JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind(\n // if the given file exists, but is not a socket, ENOTSOCK is returned\n // if access is denied, EACCESS is returned\n do {\n- ret = connect(serverHandle, (struct sockaddr *)&su, suLength);\n+ ret = connect(serverHandle, &addr->addr, suLength);\n } while(ret == -1 && (errno = socket_errno) == EINTR);\n \n if(ret == 0) {\n@@ -174,10 +200,10 @@ JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind(\n \n if(reuse || errno == ECONNREFUSED) {\n // either reuse existing socket, or take over a no longer working socket\n- if(su.sun_path[0] == 0) {\n+ if(addr->un.sun_path[0] == 0) {\n // no need to unlink in the abstract namespace\n continue;\n- } else if(unlink(su.sun_path) == -1) {\n+ } else if(unlink(addr->un.sun_path) == -1) {\n if(errno == ENOENT) {\n continue;\n }\n@@ -192,11 +218,13 @@ JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind(\n return -1;\n }\n \n- if(su.sun_path[0] == 0) {\n+ if(addr->addr.sa_family != AF_UNIX) {\n+ // nothing to do\n+ } else if(addr->un.sun_path[0] == 0) {\n // nothing to be done for the abstract namespace\n } else {\n #if !defined(_WIN32)\n- int chmodRes = chmod(su.sun_path, 0666);\n+ int chmodRes = chmod(addr->un.sun_path, 0666);\n if(chmodRes == -1) {\n myErr = errno;\n _throwErrnumException(env, myErr, NULL);\n@@ -210,12 +238,14 @@ JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind(\n struct stat fdStat;\n ino_t inode;\n \n- if(su.sun_path[0] == 0) {\n+ if(addr->addr.sa_family != AF_UNIX) {\n+ inode = 0;\n+ } else if(addr->un.sun_path[0] == 0) {\n // no inodes in the abstract namespace\n inode = 0;\n } else {\n #if !defined(_WIN32)\n- int statRes = stat(su.sun_path, &fdStat);\n+ int statRes = stat(addr->un.sun_path, &fdStat);\n if(statRes == -1) {\n if (errno == EINVAL) {\n inode = 0;\ndiff --git a/junixsocket-native/src/main/c/capabilities.c b/junixsocket-native/src/main/c/capabilities.c\nindex 2d08503e4..b3e4da59f 100644\n--- a/junixsocket-native/src/main/c/capabilities.c\n+++ b/junixsocket-native/src/main/c/capabilities.c\n@@ -19,16 +19,28 @@\n #include \"config.h\"\n #include \"capabilities.h\"\n \n+#include \"filedescriptors.h\"\n+#include \"init.h\"\n+\n CK_IGNORE_UNUSED_VARIABLE_BEGIN\n-// see AFUNIXSocketCapability.java in junixsocket-common\n+// see AFSocketCapability.java in junixsocket-common\n static int CAPABILITY_PEER_CREDENTIALS = (1 << 0);\n static int CAPABILITY_ANCILLARY_MESSAGES = (1 << 1);\n static int CAPABILITY_FILE_DESCRIPTORS = (1 << 2);\n static int CAPABILITY_ABSTRACT_NAMESPACE = (1 << 3);\n-static int CAPABILITY_DATAGRAMS = (1 << 4);\n+static int CAPABILITY_UNIX_DATAGRAMS = (1 << 4);\n static int CAPABILITY_NATIVE_SOCKETPAIR = (1 << 5);\n+static int CAPABILITY_FD_AS_REDIRECT = (1 << 6);\n+static int CAPABILITY_TIPC = (1 << 7);\n+static int CAPABILITY_UNIX_DOMAIN = (1 << 8);\n CK_IGNORE_UNUSED_VARIABLE_END\n \n+void init_capabilities(JNIEnv *env CK_UNUSED) {\n+}\n+\n+void destroy_capabilities(JNIEnv *env CK_UNUSED) {\n+}\n+\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: capabilities\n@@ -40,10 +52,17 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_capabilities(\n \n int capabilities = 0;\n \n+ if(supportsUNIX()) {\n+ capabilities |= CAPABILITY_UNIX_DOMAIN;\n+\n #if defined(LOCAL_PEERCRED) || defined(LOCAL_PEEREPID) || defined(LOCAL_PEEREUUID) || \\\n- defined(SO_PEERCRED) || defined(__NetBSD__) || defined(__sun) || defined(__sun__)\n+ defined(SO_PEERCRED) || defined(SO_PEERID) || defined(__NetBSD__) || defined(__sun) || defined(__sun__) || defined(SIO_AF_UNIX_GETPEERPID)\n+#if defined(_OS400)\n+ // SO_PEERID appears to be not implemented\n+#else\n capabilities |= CAPABILITY_PEER_CREDENTIALS;\n #endif\n+#endif\n \n #if defined(junixsocket_have_ancillary)\n capabilities |= CAPABILITY_ANCILLARY_MESSAGES;\n@@ -51,19 +70,29 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_capabilities(\n #endif\n \n #if defined(__linux__)\n- // despite earlier claims [1], they're not supported in Windows 10 (yet) [2]\n+ // despite earlier claims [1], it's not supported in Windows 10 (yet) [2]\n // [1] https://devblogs.microsoft.com/commandline/af_unix-comes-to-windows/\n // [2] https://github.com/microsoft/WSL/issues/4240\n capabilities |= CAPABILITY_ABSTRACT_NAMESPACE;\n #endif\n \n #if !defined(_WIN32)\n- capabilities |= CAPABILITY_DATAGRAMS;\n+ capabilities |= CAPABILITY_UNIX_DATAGRAMS;\n #endif\n \n #if !defined(_WIN32)\n capabilities |= CAPABILITY_NATIVE_SOCKETPAIR;\n #endif\n \n+ } // supportsUNIX()\n+\n+ if(supportsCastAsRedirect()) {\n+ capabilities |= CAPABILITY_FD_AS_REDIRECT;\n+ }\n+\n+ if(supportsTIPC()) {\n+ capabilities |= CAPABILITY_TIPC;\n+ }\n+\n return capabilities;\n }\ndiff --git a/junixsocket-native/src/main/c/capabilities.h b/junixsocket-native/src/main/c/capabilities.h\nindex 3c139465c..e714a8c58 100644\n--- a/junixsocket-native/src/main/c/capabilities.h\n+++ b/junixsocket-native/src/main/c/capabilities.h\n@@ -21,4 +21,7 @@\n \n #include \"config.h\"\n \n+void init_capabilities(JNIEnv *env);\n+void destroy_capabilities(JNIEnv *env);\n+\n #endif /* capabilities_h */\ndiff --git a/junixsocket-native/src/main/c/ckmacros.h b/junixsocket-native/src/main/c/ckmacros.h\nindex f4095a24f..5fd6d97dc 100644\n--- a/junixsocket-native/src/main/c/ckmacros.h\n+++ b/junixsocket-native/src/main/c/ckmacros.h\n@@ -103,8 +103,9 @@ _Pragma(\"clang diagnostic pop\")\n # define CK_IGNORE_CAST_BEGIN \\\n _Pragma(\"GCC diagnostic push\") \\\n _Pragma(\"GCC diagnostic ignored \\\"-Wint-to-pointer-cast\\\"\") \\\n-_Pragma(\"GCC diagnostic ignored \\\"-Wpointer-to-int-cast\\\"\")\n-_Pragma(\"GCC diagnostic ignored \\\"-Wbad-function-cast\\\"\")\n+_Pragma(\"GCC diagnostic ignored \\\"-Wpointer-to-int-cast\\\"\") \\\n+_Pragma(\"GCC diagnostic ignored \\\"-Wbad-function-cast\\\"\") \\\n+_Pragma(\"GCC diagnostic ignored \\\"-Wcast-function-type\\\"\")\n # define CK_IGNORE_CAST_END \\\n _Pragma(\"GCC diagnostic pop\")\n #else\n@@ -142,10 +143,15 @@ _Pragma(\"GCC diagnostic pop\")\n \n #define CK_UNUSED __attribute__((__unused__))\n \n-#if __clang || !defined(_WIN32)\n+#if defined(_WIN32)\n+# define CK_VISIBILITY_INTERNAL\n+# define CK_VISIBILITY_DEFAULT\n+#elif __clang\n # define CK_VISIBILITY_INTERNAL __attribute__((visibility(\"internal\")))\n+# define CK_VISIBILITY_DEFAULT __attribute__((visibility(\"default\")))\n #else\n-# define CK_VISIBILITY_INTERNAL\n+# define CK_VISIBILITY_INTERNAL __attribute__((visibility(\"hidden\")))\n+# define CK_VISIBILITY_DEFAULT __attribute__((visibility(\"default\")))\n #endif\n \n /**\ndiff --git a/junixsocket-native/src/main/c/config.c b/junixsocket-native/src/main/c/config.c\nindex 53de38e63..31f5e46b7 100644\n--- a/junixsocket-native/src/main/c/config.c\n+++ b/junixsocket-native/src/main/c/config.c\n@@ -28,3 +28,15 @@ CK_VISIBILITY_INTERNAL int clock_gettime(int ignored CK_UNUSED, struct timespec\n return 0;\n }\n # endif\n+\n+#if defined(_OS400)\n+int jux_mangleErrno(int err) {\n+ switch(err) {\n+ case 3418: // CP3418 Possible APAR condition or hardware failure\n+ // https://www.ibm.com/docs/en/i/7.5?topic=ssw_ibm_i_75/apis/gpeern.htm\n+ return EINVAL;\n+ default:\n+ return err;\n+ }\n+}\n+#endif\ndiff --git a/junixsocket-native/src/main/c/config.h b/junixsocket-native/src/main/c/config.h\nindex 261c16dfe..8eb275ae7 100644\n--- a/junixsocket-native/src/main/c/config.h\n+++ b/junixsocket-native/src/main/c/config.h\n@@ -60,6 +60,14 @@ CK_IGNORE_UNUSED_MACROS_BEGIN\n #define junixsocket_have_pipe2 // might be undef'ed below\n CK_IGNORE_UNUSED_MACROS_END\n \n+#if defined(_AIX)\n+# define junixsocket_use_poll_for_accept\n+# undef junixsocket_have_pipe2\n+#endif\n+#if defined(_OS400)\n+# define JUNIXSOCKET_HARDEN_CMSG_NXTHDR 1\n+#endif\n+\n #if !defined(uint64_t) && !defined(_INT64_TYPE) && !defined(_UINT64_T) && !defined(_UINT64_T_DEFINED_)\n # ifdef _LP64\n typedef unsigned long uint64_t;\n@@ -100,6 +108,13 @@ typedef struct sockaddr_un\n }sockaddr_un;\n # endif\n \n+# if !defined(SIO_AF_UNIX_GETPEERPID)\n+// https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Networking/WinSock/constant.SIO_AF_UNIX_GETPEERPID.html\n+// https://www.magnumdb.com/search?q=IOC_VENDOR\n+// https://www.mail-archive.com/mingw-w64-public@lists.sourceforge.net/msg18854.html\n+# define SIO_AF_UNIX_GETPEERPID _WSAIOR(IOC_VENDOR, 256)\n+# endif\n+\n // Redefining these errors simplifies WinSock error handling\n // make sure you're not using these error codes for anything not WinSock-related\n CK_IGNORE_UNUSED_MACROS_BEGIN\n@@ -175,6 +190,10 @@ extern \"C\" {\n # define JUNIXSOCKET_HARDEN_CMSG_NXTHDR 1\n #endif\n \n+#include \n+#include \n+#define junixsocket_have_tipc 1\n+\n #endif\n \n // Solaris\n@@ -206,6 +225,12 @@ typedef unsigned long socklen_t; /* 64-bits */\n # endif\n #endif\n \n+#if defined(__MACH__)\n+# if !defined(_DARWIN_C_SOURCE)\n+# define _DARWIN_C_SOURCE 1\n+# endif\n+#endif\n+\n #if defined(__MACH__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__BSD_VISIBLE)\n # define junixsocket_use_poll_for_accept\n //#define junixsocket_use_poll_interval_millis 1000\n@@ -238,6 +263,10 @@ typedef unsigned long socklen_t; /* 64-bits */\n #if defined(_WIN32)\n # define socket_errno (errno = WSAGetLastError())\n # define ssize_t int\n+#elif defined(_OS400)\n+CK_VISIBILITY_INTERNAL\n+int jux_mangleErrno(int);\n+# define socket_errno (errno = jux_mangleErrno(errno))\n #else\n # define socket_errno errno\n #endif\ndiff --git a/junixsocket-native/src/main/c/connect.c b/junixsocket-native/src/main/c/connect.c\nindex 49353c6ba..55de2eb0b 100644\n--- a/junixsocket-native/src/main/c/connect.c\n+++ b/junixsocket-native/src/main/c/connect.c\n@@ -26,31 +26,36 @@\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: connect\n- * Signature: ([BLjava/io/FileDescriptor;J)Z\n+ * Signature: (Ljava/nio/ByteBuffer;ILjava/io/FileDescriptor;J)Z\n */\n-JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_connect(\n- JNIEnv * env, jclass clazz CK_UNUSED, jbyteArray addr, jobject fd,\n- jlong expectedInode)\n+JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_connect\n+(\n+ JNIEnv * env, jclass clazz CK_UNUSED, jobject ab, jint abLen, jobject fd,\n+ jlong expectedInode)\n {\n- struct sockaddr_un su;\n- socklen_t suLength = initSu(env, &su, addr);\n- if(suLength == 0) {\n+ jux_sockaddr_t *addr = (*env)->GetDirectBufferAddress(env, ab);\n+ socklen_t addrLength = (socklen_t)abLen;\n+ if(addrLength == 0) {\n _throwException(env, kExceptionSocketException,\n \"Socket address length out of range\");\n return false;\n }\n \n int socketHandle = _getFD(env, fd);\n- if(socketHandle <= 0) {\n- _throwException(env, kExceptionSocketException, \"Socket closed\");\n+ if(socketHandle < 0) {\n+ _throwException(env, kExceptionSocketException, \"Socket is closed\");\n return false;\n }\n \n if(expectedInode > 0) {\n+ if(addr->addr.sa_family != AF_UNIX) {\n+ _throwException(env, kExceptionSocketException, \"Cannot check inode for this type of socket\");\n+ return false;\n+ }\n struct stat fdStat;\n \n // It's OK when the file's gone, but not OK if it refers to another inode.\n- int statRes = stat(su.sun_path, &fdStat);\n+ int statRes = stat(addr->un.sun_path, &fdStat);\n if(statRes == 0) {\n ino_t statInode = fdStat.st_ino;\n \n@@ -66,7 +71,7 @@ JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_connect(\n \n int ret;\n do {\n- ret = connect(socketHandle, (struct sockaddr *)&su, suLength);\n+ ret = connect(socketHandle, (struct sockaddr *)addr, addrLength);\n } while(ret == -1 && (errnum = socket_errno) == EINTR);\n \n if(ret == -1) {\n@@ -91,8 +96,8 @@ JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_connect(\n JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_disconnect\n (JNIEnv *env, jclass clazz CK_UNUSED, jobject fd) {\n int sockfd = _getFD(env, fd);\n- if(sockfd <= 0) {\n- _throwException(env, kExceptionSocketException, \"Socket closed\");\n+ if(sockfd < 0) {\n+ _throwException(env, kExceptionSocketException, \"Socket is closed\");\n return;\n }\n \n@@ -122,8 +127,8 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_disconnect\n JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_finishConnect\n (JNIEnv *env, jclass clazz CK_UNUSED, jobject fd) {\n int socketHandle = _getFD(env, fd);\n- if(socketHandle <= 0) {\n- _throwException(env, kExceptionSocketException, \"Socket closed\");\n+ if(socketHandle < 0) {\n+ _throwException(env, kExceptionSocketException, \"Socket is closed\");\n return false;\n }\n \n@@ -159,9 +164,8 @@ JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_finishCon\n goto end;\n }\n \n- struct sockaddr_un addr = {0};\n-\n- socklen_t addrSize = sizeof(struct sockaddr_un);\n+ jux_sockaddr_t addr = {0};\n+ socklen_t addrSize = sizeof(jux_sockaddr_t);\n ret = getpeername(socketHandle, (struct sockaddr *)&addr, &addrSize);\n if(ret != 0) {\n // not connected, ignore error\ndiff --git a/junixsocket-native/src/main/c/credentials.c b/junixsocket-native/src/main/c/credentials.c\nindex 22135b5a9..7725f635d 100644\n--- a/junixsocket-native/src/main/c/credentials.c\n+++ b/junixsocket-native/src/main/c/credentials.c\n@@ -31,6 +31,8 @@\n #include \"filedescriptors.h\"\n #include \"jniutil.h\"\n \n+#include \"init.h\"\n+\n #if defined(LOCAL_PEEREPID)\n \n static int ucredFromPid(pid_t pid, struct xucred* cr)\n@@ -75,12 +77,18 @@ static void initUidGidFromXucred(JNIEnv *env, jobject creds, struct xucred *cr)\n }\n #endif\n \n-#if defined(__NetBSD__) || defined(SO_PEERCRED)\n+#if defined(__NetBSD__) || defined(SO_PEERCRED) || defined(SO_PEERID) || defined(SIO_AF_UNIX_GETPEERPID)\n static void initUidGid(JNIEnv *env, jobject creds, jint pid, jint uid, jint gid) {\n- jlongArray gidArray = (*env)->NewLongArray(env, 1);\n- jlong *gids = (*env)->GetLongArrayElements(env, gidArray, 0);\n- gids[0] = gid;\n- (*env)->ReleaseLongArrayElements(env, gidArray, gids, 0);\n+ jlongArray gidArray;\n+\n+ if(gid == -1) {\n+ gidArray = NULL;\n+ } else {\n+ gidArray = (*env)->NewLongArray(env, 1);\n+ jlong *gids = (*env)->GetLongArrayElements(env, gidArray, 0);\n+ gids[0] = gid;\n+ (*env)->ReleaseLongArrayElements(env, gidArray, gids, 0);\n+ }\n \n setLongFieldValue(env, creds, \"uid\", uid);\n setLongFieldValue(env, creds, \"pid\", pid);\n@@ -100,9 +108,13 @@ JNIEXPORT jobject JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_peerCreden\n CK_ARGUMENT_POTENTIALLY_UNUSED(fdesc);\n \n #if defined(LOCAL_PEERCRED) || defined(LOCAL_PEEREPID) || defined(LOCAL_PEEREUUID) || \\\n- defined(SO_PEERCRED) || defined(__NetBSD__) || defined(__sun) || defined(__sun__)\n+ defined(SO_PEERCRED) || defined(SO_PEERID) || defined(__NetBSD__) || defined(__sun) || defined(__sun__) || defined(SIO_AF_UNIX_GETPEERPID)\n int fd = _getFD(env, fdesc);\n \n+ if(!supportsUNIX()) {\n+ return NULL;\n+ }\n+\n jboolean peerCredOK = true;\n CK_ARGUMENT_POTENTIALLY_UNUSED(peerCredOK);\n \n@@ -313,6 +325,30 @@ JNIEXPORT jobject JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_peerCreden\n initUidGid(env, creds, (jint)cr.pid, (jint)cr.uid, (jint)cr.gid);\n }\n }\n+# elif defined(SO_PEERID)\n+ {\n+ struct peercred_struct cr;\n+ socklen_t len = sizeof(cr);\n+ if(getsockopt(fd, SOL_SOCKET, SO_PEERID, &cr, &len) != 0) {\n+ if(socket_errno == EINVAL || errno == EOPNOTSUPP || errno == ENOPROTOOPT) {\n+ return NULL;\n+ } else {\n+ _throwErrnumException(env, socket_errno, NULL);\n+ return NULL;\n+ }\n+ } else {\n+ initUidGid(env, creds, (jint)cr.pid, (jint)cr.euid, (jint)cr.egid);\n+ }\n+ }\n+# elif defined(SIO_AF_UNIX_GETPEERPID)\n+ {\n+ u_long pid = -1;\n+ int ret = ioctlsocket(fd, SIO_AF_UNIX_GETPEERPID, &pid);\n+ if(ret != 0 && pid > 0) {\n+ return NULL;\n+ }\n+ initUidGid(env, creds, (jint)pid, -1, -1);\n+ }\n # endif\n \n #endif\ndiff --git a/junixsocket-native/src/main/c/exceptions.c b/junixsocket-native/src/main/c/exceptions.c\nindex 32a9c7cff..0d5cc58bd 100644\n--- a/junixsocket-native/src/main/c/exceptions.c\n+++ b/junixsocket-native/src/main/c/exceptions.c\n@@ -29,6 +29,8 @@ static char *kExceptionClassnames[kExceptionMaxExcl] = {\n \"java/lang/IndexOutOfBoundsException\", // kExceptionIndexOutOfBoundsException\n \"java/lang/IllegalStateException\", // kExceptionIllegalStateException\n \"java/lang/NullPointerException\", // kExceptionNullPointerException\n+ \"java/net/NoRouteToHostException\", // kExceptionNoRouteToHostException\n+ \"java/nio/channels/ClosedChannelException\", // kExceptionClosedChannelException\n };\n \n static jclass *kExceptionClasses;\n@@ -42,8 +44,19 @@ void init_exceptions(JNIEnv *env) {\n for (int i=0; iGetMethodID(env, exc, \"\",\n- \"(Ljava/lang/String;)V\");\n+\n+ jmethodID m = (*env)->GetMethodID(env, exc, \"\", \"(Ljava/lang/String;)V\");\n+ if(!m) {\n+ (*env)->ExceptionClear(env);\n+ m = (*env)->GetMethodID(env, exc, \"\", \"()V\");\n+ if(!m) {\n+#if DEBUG\n+ fprintf(stderr, \"Could not initialize handler for exception %s\\n\", kExceptionClassnames[i]);\n+#endif\n+ }\n+ }\n+\n+ kExceptionConstructors[i] = m;\n }\n }\n \n@@ -57,6 +70,11 @@ void destroy_exceptions(JNIEnv *env) {\n \n void _throwException(JNIEnv* env, ExceptionType exceptionType, char* message)\n {\n+ if((*env)->ExceptionCheck(env)) {\n+ // keep the existing exception\n+ return;\n+ }\n+\n if((int)exceptionType < 0 || exceptionType >= kExceptionMaxExcl) {\n exceptionType = kExceptionIllegalStateException;\n }\n@@ -84,6 +102,9 @@ void _throwErrnumException(JNIEnv* env, int errnum, jobject fdToClose)\n #endif\n exceptionType = kExceptionSocketTimeoutException;\n break;\n+ case EHOSTUNREACH:\n+ exceptionType = kExceptionNoRouteToHostException;\n+ break;\n case EPIPE:\n case EBADF:\n case ECONNRESET:\n@@ -148,10 +169,16 @@ void _throwErrnumException(JNIEnv* env, int errnum, jobject fdToClose)\n \n void _throwSockoptErrnumException(JNIEnv* env, int errnum, jobject fd)\n {\n- // when setsockopt returns an error with EINVAL, it means the socket was shut down already\n+ // when setsockopt returns an error with EINVAL, it may mean the socket was shut down already\n if(errnum == EINVAL) {\n- _throwException(env, kExceptionSocketException, \"Socket closed\");\n- return;\n+ int handle = _getFD(env, fd);\n+ struct sockaddr addr = {};\n+ socklen_t len = 0;\n+ int ret = getsockname(handle, &addr, &len);\n+ if(ret == -1) {\n+ _throwException(env, kExceptionSocketException, \"Socket is closed\");\n+ return;\n+ }\n }\n \n _throwErrnumException(env, errnum, fd);\ndiff --git a/junixsocket-native/src/main/c/exceptions.h b/junixsocket-native/src/main/c/exceptions.h\nindex 58a9c3497..3a3a56417 100644\n--- a/junixsocket-native/src/main/c/exceptions.h\n+++ b/junixsocket-native/src/main/c/exceptions.h\n@@ -27,6 +27,8 @@ typedef enum {\n kExceptionIndexOutOfBoundsException,\n kExceptionIllegalStateException,\n kExceptionNullPointerException,\n+ kExceptionNoRouteToHostException,\n+ kExceptionClosedChannelException,\n kExceptionMaxExcl\n } ExceptionType;\n \ndiff --git a/junixsocket-native/src/main/c/filedescriptors.c b/junixsocket-native/src/main/c/filedescriptors.c\nindex a9031e9eb..3c2a87127 100644\n--- a/junixsocket-native/src/main/c/filedescriptors.c\n+++ b/junixsocket-native/src/main/c/filedescriptors.c\n@@ -21,6 +21,7 @@\n \n #include \"exceptions.h\"\n #include \"jniutil.h\"\n+#include \"address.h\"\n \n static jclass class_FileDescriptor = NULL;\n static jfieldID fieldID_fd = NULL;\n@@ -36,9 +37,18 @@ typedef enum {\n kFDTypeOtherDatagramSocket,\n kFDTypeAFUNIXStreamSocket,\n kFDTypeAFUNIXDatagramSocket,\n+#if junixsocket_have_tipc\n+ kFDTypeAFTIPCStreamSocket,\n+ kFDTypeAFTIPCDatagramSocket,\n+#endif\n kFDTypeMaxExcl\n } FileDescriptorType;\n \n+#if junixsocket_have_tipc\n+static char* const kClassnameAFTIPCSocket = \"org/newsclub/net/unix/tipc/AFTIPCSocket\";\n+static char* const kClassnameAFTIPCDatagramSocket = \"org/newsclub/net/unix/tipc/AFTIPCDatagramSocket\";\n+#endif\n+\n // NOTE: The exceptions must all be either inherit from IOException or RuntimeException/Error\n static char *kFDTypeClassNames[kFDTypeMaxExcl] = {\n \"java/io/FileDescriptor\",\n@@ -47,14 +57,36 @@ static char *kFDTypeClassNames[kFDTypeMaxExcl] = {\n \"java/net/DatagramSocket\",\n \"org/newsclub/net/unix/AFUNIXSocket\",\n \"org/newsclub/net/unix/AFUNIXDatagramSocket\",\n+#if junixsocket_have_tipc\n+ kClassnameAFTIPCSocket,\n+ kClassnameAFTIPCDatagramSocket,\n+#endif\n };\n \n static jclass *kFDTypeClasses;\n \n+static jclass kRedirectImplClass;\n+static jmethodID kRedirectImplConstructor;\n+\n void init_filedescriptors(JNIEnv *env) {\n+ kRedirectImplClass = findClassAndGlobalRef0(env, \"java/lang/ProcessBuilder$RedirectPipeImpl\", JNI_TRUE);\n+ kRedirectImplConstructor = kRedirectImplClass == NULL ? NULL : (*env)->GetMethodID(env, kRedirectImplClass, \"\", \"()V\");\n+ (*env)->ExceptionClear(env);\n+\n kFDTypeClasses = malloc(sizeof(jclass) * kFDTypeMaxExcl);\n for(int i=0; i 0) {\n- shutdown(handle, SHUT_RDWR);\n+ if(fd == NULL) {\n+ if(handle >= 0) {\n+ shutdown(handle, SHUT_RDWR);\n #if defined(_WIN32)\n- ret = closesocket(handle);\n+ ret = closesocket(handle);\n #else\n- ret = close(handle);\n+ ret = close(handle);\n #endif\n- }\n- if(fd == NULL) {\n+ }\n return ret;\n }\n (*env)->MonitorEnter(env, fd);\n+\n+#if defined(_WIN32)\n+ jboolean isSocket;\n+ jlong handleWin = _getHandle(env, fd);\n+ if(handleWin > 0) {\n+ if(handle >= 0) {\n+ _close(handle);\n+ }\n+ DisconnectNamedPipe((HANDLE)handleWin);\n+ CloseHandle((HANDLE)handleWin);\n+ isSocket = false;\n+ } else {\n+ isSocket = true;\n+ }\n+#else\n+ if(handle >= 0) {\n+ shutdown(handle, SHUT_RDWR);\n+ ret = close(handle);\n+ }\n+\n+#endif\n+\n int fdHandle = _getFD(env, fd);\n _initFD(env, fd, -1);\n #if defined(_WIN32)\n@@ -154,18 +199,25 @@ int _closeFd(JNIEnv * env, jobject fd, int handle)\n #endif\n (*env)->MonitorExit(env, fd);\n \n- if(handle > 0) {\n- if(fdHandle > 0 && handle != fdHandle) {\n+ if(handle >= 0) {\n+ if(fdHandle >= 0 && handle != fdHandle) {\n #if DEBUG\n fprintf(stderr, \"NativeUnixSocket_closeFd inconsistency: handle %i vs fdHandle %i\\n\", handle, fdHandle);\n fflush(stderr);\n #endif\n }\n- } else if(fdHandle > 0) {\n- shutdown(fdHandle, SHUT_RDWR);\n+ }\n+\n+ if(fdHandle >= 0) {\n #if defined(_WIN32)\n- ret = closesocket(fdHandle);\n+ if(isSocket) {\n+ shutdown(fdHandle, SHUT_RDWR);\n+ ret = closesocket(fdHandle);\n+ } else {\n+ ret = _close(fdHandle);\n+ }\n #else\n+ shutdown(fdHandle, SHUT_RDWR);\n ret = close(fdHandle);\n #endif\n }\n@@ -209,7 +261,7 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_shutdown\n int ret = shutdown(handle, mode);\n if(ret == -1) {\n int errnum = socket_errno;\n- if(errnum == ENOTCONN) {\n+ if(errnum == ENOTCONN || errnum == EINVAL || errnum == EBADF) {\n // ignore\n return;\n }\n@@ -263,11 +315,17 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_configureBloc\n }\n \n jboolean checkNonBlocking(int handle, int errnum) {\n+ return checkNonBlocking0(handle, errnum, org_newsclub_net_unix_NativeUnixSocket_OPT_NON_BLOCKING);\n+}\n+\n+jboolean checkNonBlocking0(int handle, int errnum, int options) {\n #if defined(_WIN32)\n CK_ARGUMENT_POTENTIALLY_UNUSED(handle);\n- return errnum == 0 || errnum == WSAEWOULDBLOCK || errnum == 232 /* named pipes may return this? */;\n+ return ((options & org_newsclub_net_unix_NativeUnixSocket_OPT_NON_BLOCKING) != 0)\n+ && (errnum == 0 || errnum == WSAEWOULDBLOCK || errnum == 232 /* named pipes may return this? */);\n #else\n if (errnum == EWOULDBLOCK || errnum == EAGAIN || errnum == EINPROGRESS) {\n+ CK_ARGUMENT_POTENTIALLY_UNUSED(options);\n int flags = fcntl(handle, F_GETFL);\n return (flags != -1 && (flags & O_NONBLOCK));\n } else {\n@@ -288,7 +346,7 @@ JNIEXPORT jclass JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_primaryType\n }\n \n int handle = _getFD(env, fd);\n- if(handle <= 0) {\n+ if(handle < 0) {\n #if defined(_WIN32)\n jlong handleWin = _getHandle(env, fd);\n if(handleWin != -1) {\n@@ -298,8 +356,8 @@ JNIEXPORT jclass JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_primaryType\n return NULL;\n }\n \n- struct sockaddr_un addrUn = {0};\n- struct sockaddr *addr = (struct sockaddr *)&addrUn;\n+ jux_sockaddr_t addr0 = {0};\n+ struct sockaddr *addr = (struct sockaddr *)&addr0;\n \n int type = 0;\n socklen_t typeLen = sizeof(type);\n@@ -321,7 +379,7 @@ JNIEXPORT jclass JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_primaryType\n addr->sa_family = type;\n }\n #else\n- socklen_t len = sizeof(struct sockaddr_un);\n+ socklen_t len = sizeof(jux_sockaddr_t);\n ret = getsockname(handle, addr, &len);\n if(ret != 0) {\n int errnum = socket_errno;\n@@ -355,6 +413,17 @@ JNIEXPORT jclass JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_primaryType\n default:\n return kFDTypeClasses[kFDTypeOtherSocket];\n }\n+#if junixsocket_have_tipc\n+ case AF_TIPC:\n+ switch(type) {\n+ case SOCK_STREAM:\n+ return kFDTypeClasses[kFDTypeAFTIPCStreamSocket];\n+ case SOCK_DGRAM:\n+ return kFDTypeClasses[kFDTypeAFTIPCDatagramSocket];\n+ default:\n+ return kFDTypeClasses[kFDTypeOtherSocket];\n+ }\n+#endif\n default:\n switch(type) {\n case SOCK_STREAM:\n@@ -380,3 +449,28 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_copyFileDescr\n _initHandle(env, target, (jlong)_getHandle(env, source));\n #endif\n }\n+\n+JNIEXPORT jobject JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_initRedirect\n+(JNIEnv *env, jclass clazz CK_UNUSED, jobject fdesc)\n+{\n+ if(fdesc == NULL) {\n+ _throwException(env, kExceptionNullPointerException, \"fdesc\");\n+ return NULL;\n+ }\n+\n+ if(kRedirectImplConstructor == NULL) {\n+ return NULL;\n+ }\n+\n+ jobject redirect = (*env)->NewObject(env, kRedirectImplClass, kRedirectImplConstructor);\n+ setObjectFieldValue(env, redirect, \"fd\", \"Ljava/io/FileDescriptor;\", fdesc);\n+ return redirect;\n+}\n+\n+jboolean supportsCastAsRedirect(void) {\n+#if defined(_WIN32)\n+ return JNI_FALSE;\n+#else\n+ return kRedirectImplConstructor != NULL;\n+#endif\n+}\ndiff --git a/junixsocket-native/src/main/c/filedescriptors.h b/junixsocket-native/src/main/c/filedescriptors.h\nindex 658c49d4e..c0bd6d596 100644\n--- a/junixsocket-native/src/main/c/filedescriptors.h\n+++ b/junixsocket-native/src/main/c/filedescriptors.h\n@@ -25,8 +25,7 @@ void init_filedescriptors(JNIEnv *env);\n void destroy_filedescriptors(JNIEnv *env);\n \n CK_IGNORE_RESERVED_IDENTIFIER_BEGIN\n-__attribute__((visibility(\"hidden\")))\n-jint _getFD(JNIEnv *env, jobject fd);\n+CK_VISIBILITY_INTERNAL jint _getFD(JNIEnv *env, jobject fd);\n void _initFD(JNIEnv *env, jobject fd, jint handle);\n \n #if defined(_WIN32)\n@@ -38,5 +37,8 @@ int _closeFd(JNIEnv *env, jobject fd, int handle);\n CK_IGNORE_RESERVED_IDENTIFIER_END\n \n jboolean checkNonBlocking(int handle, int errnum);\n+jboolean checkNonBlocking0(int handle, int errnum, jint options);\n+\n+jboolean supportsCastAsRedirect(void);\n \n #endif /* filedescriptors_h */\ndiff --git a/junixsocket-native/src/main/c/init.c b/junixsocket-native/src/main/c/init.c\nindex a84e0937e..bc02678f9 100644\n--- a/junixsocket-native/src/main/c/init.c\n+++ b/junixsocket-native/src/main/c/init.c\n@@ -20,17 +20,62 @@\n #include \"init.h\"\n \n #include \"exceptions.h\"\n+#include \"capabilities.h\"\n+#include \"reflection.h\"\n #include \"ancillary.h\"\n #include \"filedescriptors.h\"\n #include \"polling.h\"\n+#include \"socketoptions.h\"\n+\n+static jboolean cap_supports_unix = false;\n+static jboolean cap_supports_tipc = false;\n+\n+static void init_unix(void) {\n+\n+ int ret = socket(AF_UNIX, SOCK_STREAM\n+#if defined(junixsocket_have_socket_cloexec)\n+ | SOCK_CLOEXEC\n+#endif\n+ , 0);\n+ if(ret >= 0) {\n+ cap_supports_unix = true;\n+#if defined(_WIN32)\n+ closesocket(ret);\n+#else\n+ close(ret);\n+#endif\n+ }\n+}\n+\n+#if defined(junixsocket_have_tipc)\n+static void init_tipc(void) {\n+\n+ int ret = socket(AF_TIPC, SOCK_STREAM\n+#if defined(junixsocket_have_socket_cloexec)\n+ | SOCK_CLOEXEC\n+#endif\n+ , 0);\n+ if(ret >= 0) {\n+ cap_supports_tipc = true;\n+ close(ret);\n+ }\n+}\n+#endif\n+\n+jboolean supportsUNIX(void) {\n+ return cap_supports_unix;\n+}\n+jboolean supportsTIPC(void) {\n+ return cap_supports_tipc;\n+}\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: init\n * Signature: ()V\n */\n-JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_init(\n- JNIEnv *env, jclass clazz CK_UNUSED)\n+JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_init\n+(JNIEnv *env, jclass clazz CK_UNUSED)\n {\n #if defined(_WIN32)\n WSADATA wsaData;\n@@ -42,11 +87,19 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_init(\n #endif\n \n init_exceptions(env);\n+ init_capabilities(env);\n+ init_reflection(env);\n+ init_unix();\n init_filedescriptors(env);\n #if defined(junixsocket_have_ancillary)\n init_ancillary(env);\n #endif\n+\n+#if defined(junixsocket_have_tipc)\n+ init_tipc();\n+#endif\n init_poll(env);\n+ init_socketoptions(env);\n }\n \n /*\n@@ -54,17 +107,20 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_init(\n * Method: destroy\n * Signature: ()V\n */\n-JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_destroy(\n- JNIEnv *env, jclass clazz CK_UNUSED)\n+JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_destroy\n+(JNIEnv *env, jclass clazz CK_UNUSED)\n {\n #if defined(_WIN32)\n WSACleanup();\n #endif\n \n destroy_exceptions(env);\n+ destroy_capabilities(env);\n+ destroy_reflection(env);\n destroy_filedescriptors(env);\n #if defined(junixsocket_have_ancillary)\n destroy_ancillary(env);\n #endif\n destroy_poll(env);\n+ destroy_socketoptions(env);\n }\ndiff --git a/junixsocket-native/src/main/c/init.h b/junixsocket-native/src/main/c/init.h\nindex 88be0e11b..69bf0f843 100644\n--- a/junixsocket-native/src/main/c/init.h\n+++ b/junixsocket-native/src/main/c/init.h\n@@ -21,4 +21,8 @@\n \n #include \"config.h\"\n \n+jboolean supportsUNIX(void);\n+\n+jboolean supportsTIPC(void);\n+\n #endif /* init_h */\ndiff --git a/junixsocket-native/src/main/c/jniutil.c b/junixsocket-native/src/main/c/jniutil.c\nindex 394102de3..e52a08135 100644\n--- a/junixsocket-native/src/main/c/jniutil.c\n+++ b/junixsocket-native/src/main/c/jniutil.c\n@@ -118,12 +118,23 @@ void setLongFieldValue(JNIEnv *env, jobject instance, char *fieldName,\n }\n \n jclass findClassAndGlobalRef(JNIEnv *env, char *className) {\n+ return findClassAndGlobalRef0(env, className, JNI_FALSE);\n+}\n+\n+jclass findClassAndGlobalRef0(JNIEnv *env, char *className, jboolean okIfMissing) {\n+\n jclass clazz = (*env)->FindClass(env, className);\n if (clazz) {\n return (*env)->NewGlobalRef(env, clazz);\n+ } else if(okIfMissing) {\n+//#if DEBUG\n+// fprintf(stderr, \"(junixsocket) Could not find optional class %s\\n\", className);\n+//#endif\n+ (*env)->ExceptionClear(env);\n+ return NULL;\n } else {\n #if DEBUG\n- fprintf(stderr, \"(junixsocket) Could not find class %s\", className);\n+ fprintf(stderr, \"(junixsocket) Could not find class %s\\n\", className);\n #endif\n return NULL;\n }\n@@ -131,7 +142,6 @@ jclass findClassAndGlobalRef(JNIEnv *env, char *className) {\n void releaseClassGlobalRef(JNIEnv *env, jclass klazz) {\n if (klazz) {\n (*env)->DeleteGlobalRef(env, klazz);\n- klazz = NULL;\n }\n }\n \ndiff --git a/junixsocket-native/src/main/c/jniutil.h b/junixsocket-native/src/main/c/jniutil.h\nindex 1d7e32ed9..a9459d5e5 100644\n--- a/junixsocket-native/src/main/c/jniutil.h\n+++ b/junixsocket-native/src/main/c/jniutil.h\n@@ -35,6 +35,7 @@ CK_VISIBILITY_INTERNAL void setLongFieldValue(JNIEnv *env, jobject instance, cha\n jlong value);\n \n CK_VISIBILITY_INTERNAL jclass findClassAndGlobalRef(JNIEnv *env, char *className);\n+CK_VISIBILITY_INTERNAL jclass findClassAndGlobalRef0(JNIEnv *env, char *className, jboolean okIfMissing);\n CK_VISIBILITY_INTERNAL void releaseClassGlobalRef(JNIEnv *env, jclass klazz);\n \n struct jni_direct_byte_buffer_ref {\n@@ -43,7 +44,7 @@ struct jni_direct_byte_buffer_ref {\n ssize_t size; // size of buffer (or -1 on error)\n void *padding;\n };\n-} CK_VISIBILITY_INTERNAL;\n+};\n \n /**\n * Ensures that a given direct byte buffer has a minimum size (which can be 0).\ndiff --git a/junixsocket-native/src/main/c/org_newsclub_net_unix_NativeUnixSocket.h b/junixsocket-native/src/main/c/org_newsclub_net_unix_NativeUnixSocket.h\nindex c126786d7..f33292711 100644\n--- a/junixsocket-native/src/main/c/org_newsclub_net_unix_NativeUnixSocket.h\n+++ b/junixsocket-native/src/main/c/org_newsclub_net_unix_NativeUnixSocket.h\n@@ -7,10 +7,16 @@\n #ifdef __cplusplus\n extern \"C\" {\n #endif\n+#undef org_newsclub_net_unix_NativeUnixSocket_DOMAIN_UNIX\n+#define org_newsclub_net_unix_NativeUnixSocket_DOMAIN_UNIX 1L\n+#undef org_newsclub_net_unix_NativeUnixSocket_DOMAIN_TIPC\n+#define org_newsclub_net_unix_NativeUnixSocket_DOMAIN_TIPC 30L\n #undef org_newsclub_net_unix_NativeUnixSocket_SOCK_STREAM\n #define org_newsclub_net_unix_NativeUnixSocket_SOCK_STREAM 1L\n #undef org_newsclub_net_unix_NativeUnixSocket_SOCK_DGRAM\n #define org_newsclub_net_unix_NativeUnixSocket_SOCK_DGRAM 2L\n+#undef org_newsclub_net_unix_NativeUnixSocket_SOCK_RDM\n+#define org_newsclub_net_unix_NativeUnixSocket_SOCK_RDM 4L\n #undef org_newsclub_net_unix_NativeUnixSocket_SOCK_SEQPACKET\n #define org_newsclub_net_unix_NativeUnixSocket_SOCK_SEQPACKET 5L\n #undef org_newsclub_net_unix_NativeUnixSocket_OPT_LOOKUP_SENDER\n@@ -21,6 +27,10 @@ extern \"C\" {\n #define org_newsclub_net_unix_NativeUnixSocket_OPT_NON_BLOCKING 4L\n #undef org_newsclub_net_unix_NativeUnixSocket_OPT_NON_SOCKET\n #define org_newsclub_net_unix_NativeUnixSocket_OPT_NON_SOCKET 8L\n+#undef org_newsclub_net_unix_NativeUnixSocket_OPT_DGRAM_MODE\n+#define org_newsclub_net_unix_NativeUnixSocket_OPT_DGRAM_MODE 16L\n+#undef org_newsclub_net_unix_NativeUnixSocket_BIND_OPT_REUSE\n+#define org_newsclub_net_unix_NativeUnixSocket_BIND_OPT_REUSE 1L\n #undef org_newsclub_net_unix_NativeUnixSocket_SOCKETSTATUS_INVALID\n #define org_newsclub_net_unix_NativeUnixSocket_SOCKETSTATUS_INVALID -1L\n #undef org_newsclub_net_unix_NativeUnixSocket_SOCKETSTATUS_UNKNOWN\n@@ -56,18 +66,18 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_capabilities\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: sockname\n- * Signature: (Ljava/io/FileDescriptor;Z)[B\n+ * Signature: (ILjava/io/FileDescriptor;Z)[B\n */\n JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockname\n- (JNIEnv *, jclass, jobject, jboolean);\n+ (JNIEnv *, jclass, jint, jobject, jboolean);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: bind\n- * Signature: ([BLjava/io/FileDescriptor;I)J\n+ * Signature: (Ljava/nio/ByteBuffer;ILjava/io/FileDescriptor;I)J\n */\n JNIEXPORT jlong JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bind\n- (JNIEnv *, jclass, jbyteArray, jobject, jint);\n+ (JNIEnv *, jclass, jobject, jint, jobject, jint);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n@@ -80,18 +90,18 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_listen\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: accept\n- * Signature: ([BLjava/io/FileDescriptor;Ljava/io/FileDescriptor;JI)Z\n+ * Signature: (Ljava/nio/ByteBuffer;ILjava/io/FileDescriptor;Ljava/io/FileDescriptor;JI)Z\n */\n JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_accept\n- (JNIEnv *, jclass, jbyteArray, jobject, jobject, jlong, jint);\n+ (JNIEnv *, jclass, jobject, jint, jobject, jobject, jlong, jint);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: connect\n- * Signature: ([BLjava/io/FileDescriptor;J)Z\n+ * Signature: (Ljava/nio/ByteBuffer;ILjava/io/FileDescriptor;J)Z\n */\n JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_connect\n- (JNIEnv *, jclass, jbyteArray, jobject, jlong);\n+ (JNIEnv *, jclass, jobject, jint, jobject, jlong);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n@@ -128,18 +138,18 @@ JNIEXPORT jclass JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_primaryType\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: read\n- * Signature: (Ljava/io/FileDescriptor;[BIILorg/newsclub/net/unix/AncillaryDataSupport;I)I\n+ * Signature: (Ljava/io/FileDescriptor;[BIIILorg/newsclub/net/unix/AncillaryDataSupport;I)I\n */\n JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_read\n- (JNIEnv *, jclass, jobject, jbyteArray, jint, jint, jobject, jint);\n+ (JNIEnv *, jclass, jobject, jbyteArray, jint, jint, jint, jobject, jint);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: write\n- * Signature: (Ljava/io/FileDescriptor;[BIILorg/newsclub/net/unix/AncillaryDataSupport;)I\n+ * Signature: (Ljava/io/FileDescriptor;[BIIILorg/newsclub/net/unix/AncillaryDataSupport;)I\n */\n JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_write\n- (JNIEnv *, jclass, jobject, jbyteArray, jint, jint, jobject);\n+ (JNIEnv *, jclass, jobject, jbyteArray, jint, jint, jint, jobject);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n@@ -152,10 +162,10 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_receive\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: send\n- * Signature: (Ljava/io/FileDescriptor;Ljava/nio/ByteBuffer;IILjava/nio/ByteBuffer;ILorg/newsclub/net/unix/AncillaryDataSupport;)I\n+ * Signature: (Ljava/io/FileDescriptor;Ljava/nio/ByteBuffer;IILjava/nio/ByteBuffer;IILorg/newsclub/net/unix/AncillaryDataSupport;)I\n */\n JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_send\n- (JNIEnv *, jclass, jobject, jobject, jint, jint, jobject, jint, jobject);\n+ (JNIEnv *, jclass, jobject, jobject, jint, jint, jobject, jint, jint, jobject);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n@@ -189,13 +199,29 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_getSocketOpti\n JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_setSocketOptionInt\n (JNIEnv *, jclass, jobject, jint, jint);\n \n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: getSocketOption\n+ * Signature: (Ljava/io/FileDescriptor;IILjava/lang/Class;)Ljava/lang/Object;\n+ */\n+JNIEXPORT jobject JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_getSocketOption\n+ (JNIEnv *, jclass, jobject, jint, jint, jclass);\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: setSocketOption\n+ * Signature: (Ljava/io/FileDescriptor;IILjava/lang/Object;)V\n+ */\n+JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_setSocketOption\n+ (JNIEnv *, jclass, jobject, jint, jint, jobject);\n+\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: available\n- * Signature: (Ljava/io/FileDescriptor;)I\n+ * Signature: (Ljava/io/FileDescriptor;Ljava/nio/ByteBuffer;)I\n */\n JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_available\n- (JNIEnv *, jclass, jobject);\n+ (JNIEnv *, jclass, jobject, jobject);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n@@ -208,7 +234,7 @@ JNIEXPORT jobject JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_peerCreden\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: initServerImpl\n- * Signature: (Ljava/net/ServerSocket;Lorg/newsclub/net/unix/AFUNIXSocketImpl;)V\n+ * Signature: (Ljava/net/ServerSocket;Lorg/newsclub/net/unix/AFSocketImpl;)V\n */\n JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_initServerImpl\n (JNIEnv *, jclass, jobject, jobject);\n@@ -216,15 +242,15 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_initServerImp\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: createSocket\n- * Signature: (Ljava/io/FileDescriptor;I)V\n+ * Signature: (Ljava/io/FileDescriptor;II)V\n */\n JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_createSocket\n- (JNIEnv *, jclass, jobject, jint);\n+ (JNIEnv *, jclass, jobject, jint, jint);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: setPort\n- * Signature: (Lorg/newsclub/net/unix/AFUNIXSocketAddress;I)V\n+ * Signature: (Ljava/net/SocketAddress;I)V\n */\n JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_setPort\n (JNIEnv *, jclass, jobject, jint);\n@@ -271,27 +297,35 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_maxAddressLen\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n- * Method: sockAddrUnLength\n+ * Method: sockAddrLength\n+ * Signature: (I)I\n+ */\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrLength\n+ (JNIEnv *, jclass, jint);\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: ancillaryBufMinLen\n * Signature: ()I\n */\n-JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrUnLength\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_ancillaryBufMinLen\n (JNIEnv *, jclass);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n- * Method: sockAddrUnToBytes\n- * Signature: (Ljava/nio/ByteBuffer;)[B\n+ * Method: sockAddrToBytes\n+ * Signature: (ILjava/nio/ByteBuffer;)[B\n */\n-JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrUnToBytes\n- (JNIEnv *, jclass, jobject);\n+JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrToBytes\n+ (JNIEnv *, jclass, jint, jobject);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n- * Method: bytesToSockAddrUn\n- * Signature: (Ljava/nio/ByteBuffer;[B)V\n+ * Method: bytesToSockAddr\n+ * Signature: (ILjava/nio/ByteBuffer;[B)I\n */\n-JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bytesToSockAddrUn\n- (JNIEnv *, jclass, jobject, jbyteArray);\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_bytesToSockAddr\n+ (JNIEnv *, jclass, jint, jobject, jbyteArray);\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n@@ -312,7 +346,7 @@ JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_initPipe\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: poll\n- * Signature: (Lorg/newsclub/net/unix/AFUNIXSelector/PollFd;I)I\n+ * Signature: (Lorg/newsclub/net/unix/AFSelector/PollFd;I)I\n */\n JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_poll\n (JNIEnv *, jclass, jobject, jint);\n@@ -328,10 +362,66 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_configureBloc\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: socketPair\n- * Signature: (ILjava/io/FileDescriptor;Ljava/io/FileDescriptor;)V\n+ * Signature: (IILjava/io/FileDescriptor;Ljava/io/FileDescriptor;)V\n */\n JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socketPair\n- (JNIEnv *, jclass, jint, jobject, jobject);\n+ (JNIEnv *, jclass, jint, jint, jobject, jobject);\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: initRedirect\n+ * Signature: (Ljava/io/FileDescriptor;)Ljava/lang/ProcessBuilder/Redirect;\n+ */\n+JNIEXPORT jobject JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_initRedirect\n+ (JNIEnv *, jclass, jobject);\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: deregisterSelectionKey\n+ * Signature: (Ljava/nio/channels/spi/AbstractSelectableChannel;Ljava/nio/channels/SelectionKey;)V\n+ */\n+JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_deregisterSelectionKey\n+ (JNIEnv *, jclass, jobject, jobject);\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: tipcGetNodeId\n+ * Signature: (I)[B\n+ */\n+JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_tipcGetNodeId\n+ (JNIEnv *, jclass, jint);\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: tipcGetLinkName\n+ * Signature: (II)[B\n+ */\n+JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_tipcGetLinkName\n+ (JNIEnv *, jclass, jint, jint);\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: sockAddrNativeDataOffset\n+ * Signature: ()I\n+ */\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrNativeDataOffset\n+ (JNIEnv *, jclass);\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: sockAddrNativeFamilyOffset\n+ * Signature: ()I\n+ */\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockAddrNativeFamilyOffset\n+ (JNIEnv *, jclass);\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: sockTypeToNative\n+ * Signature: (I)I\n+ */\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockTypeToNative\n+ (JNIEnv *, jclass, jint);\n \n #ifdef __cplusplus\n }\ndiff --git a/junixsocket-native/src/main/c/pipe.c b/junixsocket-native/src/main/c/pipe.c\nindex c892ff6fc..5f1a43f49 100644\n--- a/junixsocket-native/src/main/c/pipe.c\n+++ b/junixsocket-native/src/main/c/pipe.c\n@@ -17,15 +17,16 @@\n */\n JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_initPipe\n (JNIEnv *env, jclass clazz CK_UNUSED, jobject fdSource, jobject fdSink, jboolean selectable) {\n- int fildes[2];\n+ int fildes[2] = {-1, -1};\n \n int ret;\n #if defined(_WIN32)\n CK_ARGUMENT_POTENTIALLY_UNUSED(fildes);\n CK_ARGUMENT_POTENTIALLY_UNUSED(ret);\n+\n if(selectable) {\n Java_org_newsclub_net_unix_NativeUnixSocket_socketPair\n- (env, NULL, SOCK_STREAM, fdSource, fdSink);\n+ (env, NULL, AF_UNIX, SOCK_STREAM, fdSource, fdSink);\n return true;\n } else {\n ret = _pipe((int*)&fildes, 256, O_BINARY | O_NOINHERIT);\n@@ -43,7 +44,6 @@ JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_initPipe\n # endif\n }\n }\n-\n #else\n CK_ARGUMENT_POTENTIALLY_UNUSED(selectable);\n \n@@ -55,8 +55,16 @@ JNIEXPORT jboolean JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_initPipe\n # endif\n }\n #endif\n- if(ret != 0) {\n- _throwSockoptErrnumException(env, socket_errno, NULL);\n+\n+ if(ret != 0) {\n+ _throwSockoptErrnumException(env,\n+#if defined(_WIN32)\n+ (selectable ? socket_errno : errno),\n+#else\n+ socket_errno,\n+#endif\n+ NULL);\n+\n return false;\n }\n \ndiff --git a/junixsocket-native/src/main/c/polling.c b/junixsocket-native/src/main/c/polling.c\nindex ffbb51257..6944f30b6 100644\n--- a/junixsocket-native/src/main/c/polling.c\n+++ b/junixsocket-native/src/main/c/polling.c\n@@ -29,7 +29,7 @@ static jfieldID fieldID_ops = NULL;\n static jfieldID fieldID_rops = NULL;\n \n void init_poll(JNIEnv *env) {\n- class_PollFd = findClassAndGlobalRef(env, \"org/newsclub/net/unix/AFUNIXSelector$PollFd\");\n+ class_PollFd = findClassAndGlobalRef(env, \"org/newsclub/net/unix/AFSelector$PollFd\");\n fieldID_fds = (*env)->GetFieldID(env, class_PollFd, \"fds\", \"[Ljava/io/FileDescriptor;\");\n fieldID_ops = (*env)->GetFieldID(env, class_PollFd, \"ops\", \"[I\");\n fieldID_rops = (*env)->GetFieldID(env, class_PollFd, \"rops\", \"[I\");\n@@ -46,6 +46,7 @@ static const int OP_READ = (1<<0);\n static const int OP_WRITE = (1<<2);\n static const int OP_CONNECT = (1<<3);\n static const int OP_ACCEPT = (1<<4);\n+static const int OP_INVALID = (1<<7); // custom\n \n static int opToEvent(int op) {\n int event = 0;\n@@ -66,8 +67,8 @@ static int eventToOp(int event) {\n if((event & POLLOUT)) {\n op |= (OP_WRITE | OP_CONNECT); // will be masked accordingly later\n }\n- if((event & POLLHUP)) {\n- // FIXME should we set op to 0?\n+ if((event & ((POLLERR | POLLHUP | POLLNVAL))) != 0) {\n+ op |= OP_INVALID;\n }\n return op;\n }\n@@ -89,6 +90,10 @@ jint pollWithTimeout(JNIEnv * env, jobject fd, int handle, int timeout) {\n #else\n struct timeval optVal;\n #endif\n+ if(handle < 0) {\n+ _throwException(env, kExceptionSocketException, \"Socket is closed\");\n+ return -1;\n+ }\n \n socklen_t optLen = sizeof(optVal);\n int ret = getsockopt(handle, SOL_SOCKET, SO_RCVTIMEO, WIN32_NEEDS_CHARP &optVal, &optLen);\n@@ -233,14 +238,14 @@ jint pollWithMillis(int handle, uint64_t millis) {\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: available\n- * Signature: (Ljava/io/FileDescriptor;)I\n+ * Signature: (Ljava/io/FileDescriptor;Ljava/nio/ByteBuffer;)I\n */\n-JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_available(\n- JNIEnv * env, jclass clazz CK_UNUSED, jobject fd)\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_available\n+ (JNIEnv * env, jclass clazz CK_UNUSED, jobject fd, jobject buffer)\n {\n int handle = _getFD(env, fd);\n- if (handle <= 0) {\n- _throwException(env, kExceptionSocketException, \"Socket closed\");\n+ if (handle < 0) {\n+ _throwException(env, kExceptionSocketException, \"Socket is closed\");\n return 0;\n }\n \n@@ -249,15 +254,67 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_available(\n \n int ret;\n #if defined(_WIN32)\n- u_long count;\n- ret = ioctlsocket(handle, FIONREAD, &count);\n+ long count;\n+ ret = ioctlsocket(handle, FIONREAD, (u_long*)&count);\n #else\n- int count;\n+ int count = 0;\n+\n+# if defined(_AIX)\n+ ret = ioctlx(handle, FIONREAD, &count, 0);\n+# else\n ret = ioctl(handle, FIONREAD, &count);\n+# endif\n+\n+ if(count < 0) {\n+ count = 0;\n+ }\n+\n #endif\n- if((int)count == -1 || ret == -1) {\n- _throwErrnumException(env, socket_errno, fd);\n- return -1;\n+ if(ret == -1) {\n+ int myerr = socket_errno;\n+ if(myerr == ENOTTY) {\n+ // e.g., TIPC on Linux may not implement this call\n+ // we resort to polling and peeking with recv's MSG_PEEK\n+\n+ struct pollfd pollFd = {\n+ .events = POLLIN,\n+ .fd = handle\n+ };\n+#if defined(_WIN32)\n+ ret = WSAPoll(&pollFd, 1, 0);\n+#else\n+ ret = poll(&pollFd, 1, 0);\n+#endif\n+ if(ret != 1 || (pollFd.revents & POLLIN) == 0) {\n+ // also ignore subsequent errors\n+ return 0;\n+ }\n+\n+ struct jni_direct_byte_buffer_ref dataBufferRef =\n+ getDirectByteBufferRef (env, buffer, 0, 0);\n+ if(dataBufferRef.size == -1) {\n+ // ignore subsequent errors\n+ return 0;\n+ } else if(dataBufferRef.buf == NULL) {\n+ // ignore subsequent errors\n+ return 0;\n+ }\n+\n+ ssize_t count = recv(handle, (char*)&dataBufferRef.buf, dataBufferRef.size, MSG_PEEK\n+#if defined(MSG_TRUNC)\n+ | MSG_TRUNC // ask for the correct amount in case our buffer is too small\n+#endif\n+ );\n+ if(count > 0) {\n+ return (jint)count;\n+ }\n+ return 0;\n+ } else if(myerr == ESPIPE) {\n+ return 0;\n+ } else {\n+ _throwErrnumException(env, myerr, fd);\n+ return -1;\n+ }\n }\n \n return count;\n@@ -266,7 +323,7 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_available(\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: poll\n- * Signature: (Lorg/newsclub/net/unix/AFUNIXSelector/PollFd;I)I\n+ * Signature: (Lorg/newsclub/net/unix/AFSelector/PollFd;I)I\n */\n JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_poll\n (JNIEnv *env, jclass clazz CK_UNUSED, jobject pollFdObj, jint timeout) {\n@@ -286,16 +343,28 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_poll\n struct pollfd* pollFd = calloc(nfds, sizeof(struct pollfd));\n \n jint *buf = calloc(nfds, sizeof(jint));\n- (*env)->GetIntArrayRegion(env, opsObj, 0, nfds, buf);\n- for(int i=0;iGetIntArrayRegion(env, opsObj, 0, nfds, buf);\n for(int i=0; iGetObjectArrayElement(env, fdsObj, i);\n- int fd = _getFD(env, fdObj);\n- pollFd[i].fd = fd;\n+\n+ struct pollfd *pfd = &pollFd[i];\n+ if(fdObj) {\n+ int fd = _getFD(env, fdObj);\n+ pfd->fd = fd;\n+ pfd->events = opToEvent(buf[i]);\n+ } else {\n+ pfd->fd = 0;\n+ pfd->events = 0;\n+ }\n+}\n+\n+#if defined(_OS400)\n+ if(timeout == -1) {\n+ // unclear why, but a timeout of -1 returns EINVAL\n+ timeout = INT_MAX;\n }\n+#endif\n \n #if defined(_WIN32)\n int ret = WSAPoll(pollFd, nfds, timeout);\n@@ -309,11 +378,16 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_poll\n }\n \n for(int i=0; iSetIntArrayRegion(env, ropsObj, 0, nfds, buf);\n \n+\n end:\n free(buf);\n free(pollFd);\ndiff --git a/junixsocket-native/src/main/c/receive.c b/junixsocket-native/src/main/c/receive.c\nindex 090b8c3f0..b7a1f019c 100644\n--- a/junixsocket-native/src/main/c/receive.c\n+++ b/junixsocket-native/src/main/c/receive.c\n@@ -24,6 +24,14 @@\n #include \"ancillary.h\"\n #include \"jniutil.h\"\n #include \"polling.h\"\n+#include \"address.h\"\n+\n+#if junixsocket_have_tipc\n+struct jux_tipc_errinfo {\n+ uint32_t errorCode;\n+ uint32_t dataLength;\n+};\n+#endif\n \n static int optToFlags(jint opt) {\n int flags = 0;\n@@ -33,26 +41,32 @@ static int optToFlags(jint opt) {\n return flags;\n }\n \n-ssize_t recv_wrapper(int handle, jbyte *buf, jint length, struct sockaddr_un *senderBuf, socklen_t *senderBufLen, int opt) {\n-\n+static ssize_t recv_wrapper(int handle, jbyte *buf, jint length, jux_sockaddr_t *senderBuf, socklen_t *senderBufLen, jint opt) {\n int flags = optToFlags(opt);\n \n ssize_t count;\n do {\n- if (senderBuf != NULL) {\n- count = recvfrom(handle, (char*)buf, length, flags, (struct sockaddr *)senderBuf, senderBufLen);\n- } else if((opt & org_newsclub_net_unix_NativeUnixSocket_OPT_NON_SOCKET) != 0 && flags == 0) {\n+ if((opt & org_newsclub_net_unix_NativeUnixSocket_OPT_NON_SOCKET) != 0 && flags == 0) {\n // \"read\" can be used with pipes, too.\n count = read(handle, (char*)buf, length);\n+ if(senderBufLen) {\n+ *senderBufLen = 0;\n+ }\n+ } else if (senderBuf != NULL) {\n+ count = recvfrom(handle, (char*)buf, length, flags, (struct sockaddr *)senderBuf, senderBufLen);\n } else {\n count = recv(handle, (char*)buf, length, flags);\n+ if(count == -1 && socket_errno == ENOTSOCK) {\n+ // unexpected non-socket, try again with read\n+ count = read(handle, (char*)buf, length);\n+ }\n }\n } while(count == (ssize_t)-1 && (socket_errno == EINTR));\n \n return count;\n }\n \n-ssize_t recvmsg_wrapper(JNIEnv * env, int handle, jbyte *buf, jint length, struct sockaddr_un *senderBuf, socklen_t *senderBufLen, int opt, jobject ancSupp) {\n+static ssize_t recvmsg_wrapper(JNIEnv * env, int handle, jbyte *buf, jint length, jux_sockaddr_t *senderBuf, socklen_t *senderBufLen, jint opt, jobject ancSupp) {\n #if !defined(junixsocket_have_ancillary)\n CK_ARGUMENT_POTENTIALLY_UNUSED(env);\n CK_ARGUMENT_POTENTIALLY_UNUSED(ancSupp);\n@@ -85,6 +99,10 @@ ssize_t recvmsg_wrapper(JNIEnv * env, int handle, jbyte *buf, jint length, struc\n \n if (control == NULL || controlLen == 0 || ancSupp == NULL) {\n return recv_wrapper(handle, buf, length, senderBuf, senderBufLen, opt);\n+ } else if(controlLen < sizeof(struct cmsghdr)) {\n+ // DragonFlyBSD doesn't throw an exception by itself, so we have to do it.\n+ _throwException(env, kExceptionSocketException, \"No buffer space available\");\n+ return -1;\n }\n \n int flags = optToFlags(opt);\n@@ -116,25 +134,26 @@ ssize_t recvmsg_wrapper(JNIEnv * env, int handle, jbyte *buf, jint length, struc\n return count;\n }\n \n- if(controlLen < sizeof(struct cmsghdr)) {\n- // DragonFlyBSD doesn't throw an exception by itself, so we have to do it.\n- _throwException(env, kExceptionSocketException, \"No buffer space available\");\n- return -1;\n- }\n-\n+ struct cmsghdr *cmsgPrev = NULL;\n for(struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg =\n junixsocket_CMSG_NXTHDR(&msg, cmsg)) {\n+ if(cmsg == cmsgPrev) {\n+ break;\n+ }\n+ cmsgPrev = cmsg;\n+\n+ char *endBytes = (char*)cmsg + cmsg->cmsg_len;\n+ char *controlEnd = (char*)control + controlLen;\n+ if(controlEnd < endBytes) {\n+ endBytes = controlEnd;\n+ }\n+ unsigned char *data = CMSG_DATA(cmsg);\n+ size_t len = ((unsigned char *)endBytes - data);\n+\n if(cmsg->cmsg_level == SOL_SOCKET\n && cmsg->cmsg_type == SCM_RIGHTS) {\n- char *endBytes = (char*)cmsg + cmsg->cmsg_len;\n- char *controlEnd = (char*)control + controlLen;\n- if(controlEnd < endBytes) {\n- endBytes = controlEnd;\n- }\n \n- unsigned char *data = CMSG_DATA(cmsg);\n- unsigned char *end = (unsigned char *)endBytes;\n- int numFds = (int)(end - data) / sizeof(int);\n+ int numFds = (int)(len) / sizeof(int);\n \n CK_STATIC_ASSERT(sizeof(int)==sizeof(jint));\n \n@@ -153,12 +172,31 @@ ssize_t recvmsg_wrapper(JNIEnv * env, int handle, jbyte *buf, jint length, struc\n _throwException(env, kExceptionSocketException, \"No buffer space available\");\n return -1;\n }\n+#if junixsocket_have_tipc\n+ } else if(cmsg->cmsg_level == SOL_TIPC && cmsg->cmsg_type == TIPC_ERRINFO && len == 8) {\n+ CK_IGNORE_CAST_ALIGN_BEGIN\n+ struct jux_tipc_errinfo *errInfo = (struct jux_tipc_errinfo *)data;\n+ CK_IGNORE_CAST_ALIGN_END\n+\n+ jmethodID kSetTipcErrorInfo = getMethodID_setTipcErrorInfo();\n+ if(kSetTipcErrorInfo != NULL) {\n+ (*env)->CallVoidMethod(env, ancSupp, kSetTipcErrorInfo, errInfo->errorCode, errInfo->dataLength);\n+ }\n+ } else if(cmsg->cmsg_level == SOL_TIPC && cmsg->cmsg_type == TIPC_DESTNAME && len == 12) {\n+ CK_IGNORE_CAST_ALIGN_BEGIN\n+ struct tipc_name_seq* addr = (struct tipc_name_seq*)data; // three bytes\n+ CK_IGNORE_CAST_ALIGN_END\n+ jmethodID kSetTipcDestName = getMethodID_setTipcDestName();\n+ if(kSetTipcDestName != NULL) {\n+ (*env)->CallVoidMethod(env, ancSupp, kSetTipcDestName, addr->type, addr->lower, addr->upper);\n+ }\n+#endif\n } else {\n #if DEBUG\n if(cmsg->cmsg_level == 0 && cmsg->cmsg_type == 0) {\n continue;\n } else {\n- fprintf(stderr, \"NativeUnixSocket_read: Unexpected cmsg level:%i type:%i\\n\", cmsg->cmsg_level, cmsg->cmsg_type);\n+ fprintf(stderr, \"NativeUnixSocket_read: Unexpected cmsg level:%i type:%i len:%zu\\n\", cmsg->cmsg_level, cmsg->cmsg_type, len);\n fflush(stderr);\n }\n #endif\n@@ -172,17 +210,18 @@ ssize_t recvmsg_wrapper(JNIEnv * env, int handle, jbyte *buf, jint length, struc\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: read\n- * Signature: (Ljava/io/FileDescriptor;[BIILorg/newsclub/net/unix/AncillaryDataSupport;)I\n+ * Signature: (Ljava/io/FileDescriptor;[BIIILorg/newsclub/net/unix/AncillaryDataSupport;)I\n */\n JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_read(\n JNIEnv * env, jclass clazz CK_UNUSED, jobject fd, jbyteArray jbuf,\n- jint offset, jint length, jobject ancSupp, jint hardTimeoutMillis)\n+ jint offset, jint length, jint opt, jobject ancSupp, jint hardTimeoutMillis)\n {\n #if defined(_WIN32)\n CK_ARGUMENT_POTENTIALLY_UNUSED(ancSupp);\n #endif\n CK_ARGUMENT_POTENTIALLY_UNUSED(hardTimeoutMillis);\n \n+\n // Performance: In order to read a single byte, simply don't specify a receive buffer.\n if(jbuf) {\n jsize bufLen = (*env)->GetArrayLength(env, jbuf);\n@@ -226,7 +265,6 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_read(\n \n ssize_t count;\n \n- int opt = 0;\n count = recvmsg_wrapper(env, handle, buf, length, NULL, 0, opt, ancSupp);\n \n jint returnValue;\n@@ -261,15 +299,15 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_receive\n CK_ARGUMENT_POTENTIALLY_UNUSED(hardTimeoutMillis);\n \n int handle = _getFD(env, fd);\n- if (handle <= 0) {\n- _throwException(env, kExceptionSocketException, \"Socket closed\");\n+ if(handle < 0) {\n+ _throwException(env, kExceptionSocketException, \"Socket is closed\");\n return -1;\n }\n \n #if defined(junixsocket_use_poll_for_read)\n int ret = pollWithTimeout(env, fd, handle, hardTimeoutMillis);\n if(ret < 1) {\n- if(checkNonBlocking(handle, socket_errno)) {\n+ if(checkNonBlocking0(handle, socket_errno, opt)) {\n // non-blocking socket\n return 0;\n } else if(ret == -1) {\n@@ -297,33 +335,57 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_receive\n }\n \n struct jni_direct_byte_buffer_ref addressBufferRef =\n- getDirectByteBufferRef (env, addressBuffer, 0, sizeof(struct sockaddr_un));\n+ getDirectByteBufferRef (env, addressBuffer, 0, sizeof(jux_sockaddr_t));\n if(addressBufferRef.size == -1) {\n _throwException(env, kExceptionSocketException, \"Cannot get addressBuffer\");\n return -1;\n }\n \n- struct sockaddr_un *senderBuf = (struct sockaddr_un *)addressBufferRef.buf;\n+ jux_sockaddr_t *senderBuf = (jux_sockaddr_t *)addressBufferRef.buf;\n socklen_t senderBufLen = (socklen_t)MIN(SOCKLEN_MAX, (unsigned)addressBufferRef.size);\n \n+ memset(senderBuf, 0, senderBufLen);\n ssize_t count = recvmsg_wrapper(env, handle, dataBufferRef.buf, length, senderBuf, &senderBufLen, opt, ancSupp);\n \n // NOTE: if we receive messages from an unbound socket, the \"sender\" may be just a bunch of zeros.\n \n+ int theError;\n if(count == -1) {\n- count = 0;\n- if(checkNonBlocking(handle, errno)) {\n- // no data on non-blocking socket\n+ theError = errno;\n+ } else if(count == 0) {\n+ // check if non-blocking below\n+ theError = EWOULDBLOCK;\n+ } else {\n+ return (jint)count;\n+ }\n+\n+ if(checkNonBlocking0(handle, theError, opt)) {\n+ theError = errno;\n+ // no data on non-blocking socket, or terminated connection?\n+ if(count == 0 && theError != 0) {\n+ _throwException(env, kExceptionClosedChannelException, NULL);\n+ } else if(theError == 0 || theError == EAGAIN || theError == ETIMEDOUT\n+#if defined(_WIN32)\n+ || theError == WSAETIMEDOUT\n+#endif\n+ || theError == EINTR) {\n+ // just return 0\n } else {\n- // read(2) returns -1 on error. Java throws an Exception.\n- if(!(*env)->ExceptionCheck(env)) {\n- _throwErrnumException(env, errno, fd);\n- }\n- goto end;\n+ _throwErrnumException(env, errno, fd);\n+ }\n+ return 0;\n+ } else if(theError == EWOULDBLOCK) {\n+ return -1;\n+ } else if(count == -1) {\n+ if(theError == ENOENT) {\n+ return -1;\n+ }\n+ // read(2) returns -1 on error. Java throws an Exception.\n+ if(!(*env)->ExceptionCheck(env)) {\n+ _throwErrnumException(env, theError, fd);\n }\n }\n-\n-end:\n+ count = 0;\n \n return (jint)count;\n }\ndiff --git a/junixsocket-native/src/main/c/receive.h b/junixsocket-native/src/main/c/receive.h\nindex af93077aa..5b318bcd2 100644\n--- a/junixsocket-native/src/main/c/receive.h\n+++ b/junixsocket-native/src/main/c/receive.h\n@@ -20,7 +20,7 @@\n #define receive_h\n \n #include \"config.h\"\n+#include \"address.h\"\n \n-ssize_t recvmsg_wrapper(JNIEnv * env, int handle, jbyte *buf, jint length, struct sockaddr_un *senderBuf, socklen_t *senderBufLen, int opt, jobject ancSupp);\n \n #endif /* receive_h */\ndiff --git a/junixsocket-native/src/main/c/reflection.c b/junixsocket-native/src/main/c/reflection.c\nindex 067b7d3b8..dbc83d162 100644\n--- a/junixsocket-native/src/main/c/reflection.c\n+++ b/junixsocket-native/src/main/c/reflection.c\n@@ -24,6 +24,19 @@\n \n static jboolean doSetServerSocket = true;\n \n+static jclass kClassAbstractSelectableChannel;\n+static jmethodID kMethodRemoveKey;\n+\n+void init_reflection(JNIEnv *env) {\n+ kClassAbstractSelectableChannel = findClassAndGlobalRef(env, \"java/nio/channels/spi/AbstractSelectableChannel\");\n+ if(kClassAbstractSelectableChannel) {\n+ kMethodRemoveKey = (*env)->GetMethodID(env, kClassAbstractSelectableChannel, \"removeKey\", \"(Ljava/nio/channels/SelectionKey;)V\");\n+ }\n+}\n+void destroy_reflection(JNIEnv *env) {\n+ releaseClassGlobalRef(env, kClassAbstractSelectableChannel);\n+}\n+\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: initServerImpl\n@@ -132,3 +145,21 @@ JNIEXPORT jobject JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_currentRMI\n \n return socket;\n }\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: deregisterSelectionKey\n+ * Signature: (Ljava/nio/channels/spi/AbstractSelectableChannel;Ljava/nio/channels/SelectionKey;)V\n+ */\n+JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_deregisterSelectionKey\n+ (JNIEnv * env, jclass clazz CK_UNUSED, jobject chann, jobject key)\n+{\n+ if(chann == NULL) {\n+ return;\n+ }\n+ if(kMethodRemoveKey != NULL) {\n+ (*env)->CallVoidMethod(env, chann, kMethodRemoveKey, key);\n+ } else {\n+ // FIXME\n+ }\n+}\ndiff --git a/junixsocket-native/src/main/c/reflection.h b/junixsocket-native/src/main/c/reflection.h\nindex 0339b68f7..8010c6d21 100644\n--- a/junixsocket-native/src/main/c/reflection.h\n+++ b/junixsocket-native/src/main/c/reflection.h\n@@ -21,4 +21,7 @@\n \n #include \"config.h\"\n \n+void init_reflection(JNIEnv *env);\n+void destroy_reflection(JNIEnv *env);\n+\n #endif /* reflection_h */\ndiff --git a/junixsocket-native/src/main/c/send.c b/junixsocket-native/src/main/c/send.c\nindex f58c2689e..869c33237 100644\n--- a/junixsocket-native/src/main/c/send.c\n+++ b/junixsocket-native/src/main/c/send.c\n@@ -25,15 +25,37 @@\n #include \"receive.h\"\n #include \"jniutil.h\"\n \n-static jboolean sleepForRetryWriting() {\n+#if __has_include()\n+#include \n+#endif\n+#if __has_include()\n+#include \n+#endif\n+\n+#if defined(junixsocket_have_ancillary)\n+static jboolean sleepForRetryWriting(void) {\n usleep(1000); // 1 ms\n return true;\n }\n+#endif\n \n-ssize_t send_wrapper(int handle, jbyte *buf, jint length, struct sockaddr_un *sendTo, socklen_t sendToLen, int opt) {\n- ssize_t count;\n+ssize_t send_wrapper(int handle, jbyte *buf, jint length, struct sockaddr_un *sendTo, socklen_t sendToLen, jint opt) {\n+ ssize_t count = 0;\n \n- do {\n+ const jboolean dgramMode = (opt & org_newsclub_net_unix_NativeUnixSocket_OPT_DGRAM_MODE) != 0;\n+ const jboolean nonBlockingMode = (opt & org_newsclub_net_unix_NativeUnixSocket_OPT_NON_BLOCKING) != 0;\n+\n+// if(!dgramMode) {\n+// int sndBuf;\n+// socklen_t sndBufLen = sizeof(sndBuf);\n+// int ret = getsockopt(handle, SOL_SOCKET, SO_SNDBUF, (char*)&sndBuf, &sndBufLen);\n+// if(ret == 0 && sndBuf < length && sndBuf > 0) {\n+// length = sndBuf;\n+// }\n+// }\n+\n+ int loop=0;\n+ for(;loop<3;loop++) {\n errno = 0;\n if (sendTo != NULL) {\n count = sendto(handle, (char*)buf, length, 0, (struct sockaddr *)sendTo, sendToLen);\n@@ -42,19 +64,51 @@ ssize_t send_wrapper(int handle, jbyte *buf, jint length, struct sockaddr_un *se\n count = write(handle, (char*)buf, length);\n } else {\n count = send(handle, (char*)buf, length, 0);\n+ if(count == -1 && socket_errno == ENOTSOCK) {\n+ // unexpected non-socket, try again with write\n+ count = write(handle, (char*)buf, length);\n+ }\n }\n // on macOS/BSD, send seems to not block if the send buffer is full, so we have to handle ENOBUFS\n- } while(count == -1 && (socket_errno == EINTR ||\n- (\n- errno == ENOBUFS\n- && (opt & org_newsclub_net_unix_NativeUnixSocket_OPT_NON_BLOCKING) == 0\n- && sleepForRetryWriting()\n- )\n- ));\n+ if(count >= 0) {\n+ break;\n+ }\n+ if(socket_errno == EINTR) {\n+ continue;\n+ }\n+ if(errno == ENOBUFS) {\n+ if(!dgramMode) {\n+ break;\n+ }\n+ if(nonBlockingMode) {\n+ break;\n+ }\n+ count = 0; // don't throw\n+#if defined(sched_yield)\n+ sched_yield();\n+#else\n+ struct pollfd fds[] = {\n+ {\n+ .fd = handle,\n+ .events = (POLLOUT),\n+ .revents = 0\n+ }\n+ };\n+\n+# if defined(_WIN32)\n+ WSAPoll(fds, 1, -1);\n+# else\n+ poll(fds, 1, -1);\n+# endif\n+#endif\n+ continue;\n+ }\n+ break;\n+ }\n return count;\n }\n \n-ssize_t sendmsg_wrapper(JNIEnv * env, int handle, jbyte *buf, jint length, struct sockaddr_un *sendTo, socklen_t sendToLen, int opt, jobject ancSupp) {\n+ssize_t sendmsg_wrapper(JNIEnv * env, int handle, jbyte *buf, jint length, struct sockaddr_un *sendTo, socklen_t sendToLen, jint opt, jobject ancSupp) {\n #if !defined(junixsocket_have_ancillary)\n CK_ARGUMENT_POTENTIALLY_UNUSED(env);\n CK_ARGUMENT_POTENTIALLY_UNUSED(ancSupp);\n@@ -128,13 +182,13 @@ ssize_t sendmsg_wrapper(JNIEnv * env, int handle, jbyte *buf, jint length, struc\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: write\n- * Signature: (Ljava/io/FileDescriptor;[BIILorg/newsclub/net/unix/AncillaryDataSupport;)I\n+ * Signature: (Ljava/io/FileDescriptor;[BIIILorg/newsclub/net/unix/AncillaryDataSupport;)I\n */\n JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_write(\n JNIEnv * env, jclass clazz CK_UNUSED, jobject fd, jbyteArray jbuf,\n- jint offset, jint length, jobject ancSupp)\n+ jint offset, jint length, jint opt, jobject ancSupp)\n {\n-#if defined(_WIN32)\n+#if defined(_WIN32) || defined(_AIX)\n CK_ARGUMENT_POTENTIALLY_UNUSED(ancSupp);\n #endif\n \n@@ -167,7 +221,7 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_write(\n ssize_t count;\n \n #if defined(junixsocket_have_ancillary)\n- count = sendmsg_wrapper(env, handle, buf, length, NULL, 0, 0, ancSupp);\n+ count = sendmsg_wrapper(env, handle, buf, length, NULL, 0, opt, ancSupp);\n \n #else\n errno = 0;\n@@ -179,7 +233,7 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_write(\n free(buf);\n \n if(count == -1) {\n- if(checkNonBlocking(handle, errno)) {\n+ if(checkNonBlocking0(handle, errno, opt)) {\n return 0;\n } else {\n _throwErrnumException(env, errno, fd);\n@@ -193,13 +247,13 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_write(\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: send\n- * Signature: (Ljava/io/FileDescriptor;Ljava/nio/ByteBuffer;IILjava/nio/ByteBuffer;ILorg/newsclub/net/unix/AncillaryDataSupport;)I\n+ * Signature: (Ljava/io/FileDescriptor;Ljava/nio/ByteBuffer;IILjava/nio/ByteBuffer;IILorg/newsclub/net/unix/AncillaryDataSupport;)I\n */\n JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_send\n-(JNIEnv *env, jclass clazz CK_UNUSED, jobject fd, jobject buffer, jint offset, jint length, jobject addressBuffer, jint opt, jobject ancSupp) {\n+(JNIEnv *env, jclass clazz CK_UNUSED, jobject fd, jobject buffer, jint offset, jint length, jobject addressBuffer, jint addressLen, jint opt, jobject ancSupp) {\n int handle = _getFD(env, fd);\n- if (handle <= 0) {\n- _throwException(env, kExceptionSocketException, \"Socket closed\");\n+ if(handle < 0) {\n+ _throwException(env, kExceptionSocketException, \"Socket is closed\");\n return 0;\n }\n \n@@ -224,7 +278,7 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_send\n }\n \n struct sockaddr_un *sendTo = (struct sockaddr_un *)(addressBufferRef.buf);\n- socklen_t sendToLen = (socklen_t)MIN(SOCKLEN_MAX, (unsigned)addressBufferRef.size);\n+ socklen_t sendToLen = (socklen_t) MIN(SOCKLEN_MAX, MIN((unsigned)addressLen, (unsigned)addressBufferRef.size));\n \n ssize_t ret = sendmsg_wrapper(env, handle, dataBufferRef.buf, length, sendTo, sendToLen, opt, ancSupp);\n if(ret < 0) {\ndiff --git a/junixsocket-native/src/main/c/socket.c b/junixsocket-native/src/main/c/socket.c\nindex d476f292b..92f221742 100644\n--- a/junixsocket-native/src/main/c/socket.c\n+++ b/junixsocket-native/src/main/c/socket.c\n@@ -22,6 +22,7 @@\n #include \"org_newsclub_net_unix_NativeUnixSocket.h\"\n #include \"filedescriptors.h\"\n #include \"exceptions.h\"\n+#include \"address.h\"\n \n int sockTypeToNative(JNIEnv *env, int type) {\n switch(type) {\n@@ -36,29 +37,47 @@ int sockTypeToNative(JNIEnv *env, int type) {\n return -1;\n }\n }\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: sockTypeToNative\n+ * Signature: (I)I\n+ */\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_sockTypeToNative\n+ (JNIEnv *env, jclass klazz CK_UNUSED, jint type) {\n+ return sockTypeToNative(env, type);\n+}\n+\n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: createSocket\n * Signature: (Ljava/io/FileDescriptor;I)V\n */\n JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_createSocket\n-(JNIEnv * env, jclass clazz CK_UNUSED, jobject fd, jint type) {\n+(JNIEnv * env, jclass clazz CK_UNUSED, jobject fd, jint domain, jint type) {\n int handle = _getFD(env, fd);\n+\n if(handle > 0) {\n // already initialized\n _throwException(env, kExceptionSocketException, \"Already created\");\n return;\n }\n \n+ domain = domainToNative(domain);\n+ if(domain == -1) {\n+ _throwException(env, kExceptionSocketException, \"Unsupported domain\");\n+ return;\n+ }\n+\n type = sockTypeToNative(env, type);\n if(type == -1) {\n return;\n }\n \n #if defined(junixsocket_have_socket_cloexec)\n- handle = socket(AF_UNIX, type | SOCK_CLOEXEC, 0);\n+ handle = socket(domain, type | SOCK_CLOEXEC, 0);\n if(handle == -1 && errno == EPROTONOSUPPORT) {\n- handle = socket(AF_UNIX, type, 0);\n+ handle = socket(domain, type, 0);\n if(handle > 0) {\n # if defined(FD_CLOEXEC)\n fcntl(handle, F_SETFD, FD_CLOEXEC); // best effort\n@@ -66,9 +85,9 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_createSocket\n }\n }\n #else\n- handle = socket(AF_UNIX, type, 0);\n+ handle = socket(domain, type, 0);\n #endif\n- if(handle <= 0) {\n+ if(handle < 0) {\n _throwErrnumException(env, socket_errno, fd);\n return;\n }\n@@ -79,8 +98,9 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_createSocket\n fcntl(handle, F_SETFD, FD_CLOEXEC); // best effort\n # elif defined(_WIN32)\n // WSASocketW does not support AF_UNIX, so we can't set this atomically like on Linux\n- HANDLE h = (HANDLE)_get_osfhandle(handle);\n- SetHandleInformation(h, HANDLE_FLAG_INHERIT, 0); // best effort\n+ // FIXME -- crashes on some Windows versions/compilers; omitting since it's non-essential\n+ // HANDLE h = (HANDLE)_get_osfhandle(handle);\n+ // SetHandleInformation(h, HANDLE_FLAG_INHERIT, 0); // best effort\n # endif\n #endif\n \n@@ -95,11 +115,11 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_createSocket\n JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socketStatus\n (JNIEnv *env, jclass clazz CK_UNUSED, jobject fd) {\n int handle = _getFD(env, fd);\n- if(handle <= 0) {\n+ if(handle < 0) {\n return org_newsclub_net_unix_NativeUnixSocket_SOCKETSTATUS_INVALID;\n }\n- struct sockaddr_un addr = {0};\n- socklen_t len = sizeof(struct sockaddr_un);\n+ jux_sockaddr_t addr = {0};\n+ socklen_t len = sizeof(jux_sockaddr_t);\n \n int ret;\n \n@@ -109,6 +129,7 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socketStatus\n switch(errnum) {\n case EINVAL:\n case ENOTCONN:\n+ case ENOTSOCK: // OSv socketpair\n break;\n default:\n _throwErrnumException(env, errnum, fd);\n@@ -124,23 +145,30 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socketStatus\n switch(errnum) {\n case EINVAL:\n case ENOTCONN:\n+ case ENOTSOCK: // OSv socketpair\n break;\n default:\n _throwErrnumException(env, errnum, fd);\n return -1;\n }\n } else if (len > 0) {\n- jboolean hasNonZero = false;\n+ if(addr.addr.sa_family == AF_UNIX) {\n+ // this is AF_UNIX specific\n+ jboolean hasNonZero = false;\n \n- len -= offsetof(struct sockaddr_un, sun_path);\n+ len -= offsetof(struct sockaddr_un, sun_path);\n \n- for(socklen_t i=0;iGetMethodID(env, kIntegerClass, \"\", \"(I)V\");\n+ kIntegerIntValue = kIntegerClass == NULL ? NULL : (*env)->GetMethodID(env, kIntegerClass, \"intValue\", \"()I\");\n+ if(kIntegerConstructor == NULL || kIntegerIntValue == NULL) {\n+ releaseClassGlobalRef(env, kIntegerClass);\n+ kIntegerClass = NULL;\n+ }\n+\n+ kAFTIPCGroupRequestClass = findClassAndGlobalRef0(env, \"org/newsclub/net/unix/tipc/AFTIPCGroupRequest\", true);\n+ kAFTIPCGroupRequestFromNative = kAFTIPCGroupRequestClass == NULL ? NULL : (*env)->GetStaticMethodID(env, kAFTIPCGroupRequestClass, \"fromNative\", \"(IIII)Lorg/newsclub/net/unix/tipc/AFTIPCGroupRequest;\");\n+ kAFTIPCGroupRequestGetType = kAFTIPCGroupRequestClass == NULL ? NULL : (*env)->GetMethodID(env, kAFTIPCGroupRequestClass, \"getType\", \"()I\");\n+ kAFTIPCGroupRequestGetInstance = kAFTIPCGroupRequestClass == NULL ? NULL : (*env)->GetMethodID(env, kAFTIPCGroupRequestClass, \"getInstance\", \"()I\");\n+ kAFTIPCGroupRequestGetScopeId = kAFTIPCGroupRequestClass == NULL ? NULL : (*env)->GetMethodID(env, kAFTIPCGroupRequestClass, \"getScopeId\", \"()I\");\n+ kAFTIPCGroupRequestGetFlagsValue = kAFTIPCGroupRequestClass == NULL ? NULL : (*env)->GetMethodID(env, kAFTIPCGroupRequestClass, \"getFlagsValue\", \"()I\");\n+ if(kAFTIPCGroupRequestGetType == NULL || kAFTIPCGroupRequestGetInstance == NULL || kAFTIPCGroupRequestGetScopeId == NULL || kAFTIPCGroupRequestGetFlagsValue == NULL) {\n+ releaseClassGlobalRef(env, kAFTIPCGroupRequestClass);\n+ kAFTIPCGroupRequestClass = NULL;\n+ }\n+}\n+\n+void destroy_socketoptions(JNIEnv *env) {\n+ releaseClassGlobalRef(env, kIntegerClass);\n+ releaseClassGlobalRef(env, kAFTIPCGroupRequestClass);\n+}\n+\n static jint convertSocketOptionToNative(jint optID)\n {\n switch(optID) {\n@@ -47,8 +85,8 @@ static jint convertSocketOptionToNative(jint optID)\n * Method: getSocketOptionInt\n * Signature: (Ljava/io/FileDescriptor;I)I\n */\n-JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_getSocketOptionInt(\n- JNIEnv * env, jclass clazz CK_UNUSED, jobject fd, jint optID)\n+JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_getSocketOptionInt\n+(JNIEnv * env, jclass clazz CK_UNUSED, jobject fd, jint optID)\n {\n int handle = _getFD(env, fd);\n \n@@ -104,8 +142,8 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_getSocketOpti\n * Method: setSocketOptionInt\n * Signature: (Ljava/io/FileDescriptor;II)V\n */\n-JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_setSocketOptionInt(\n- JNIEnv * env, jclass clazz CK_UNUSED, jobject fd, jint optID, jint value)\n+JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_setSocketOptionInt\n+(JNIEnv * env, jclass clazz CK_UNUSED, jobject fd, jint optID, jint value)\n {\n int handle = _getFD(env, fd);\n \n@@ -155,3 +193,186 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_setSocketOpti\n return;\n }\n }\n+\n+static jint optionDomainToNative(jint domain) {\n+ switch(domain) {\n+#if junixsocket_have_tipc\n+ case 271:\n+ return SOL_TIPC;\n+#endif\n+ default:\n+ return -1;\n+ }\n+}\n+\n+static jint optionNameToNative(jint domain, jint optionName) {\n+ switch(domain) {\n+ case 271: // TIPC\n+ if(optionName >= 127 && optionName <= 138) {\n+ // allow compiling with older kernel headers by not using constants here\n+ // this should be relatively safe since TIPC is Linux-only for us right now.\n+ return optionName;\n+ }\n+ return -1;\n+ default:\n+ return -1;\n+ }\n+}\n+\n+static jobject intToInteger(JNIEnv *env, void* valPtr, socklen_t valLen) {\n+ if(valLen < (signed)sizeof(jint)) {\n+ return NULL;\n+ }\n+ jint val = *((jint*)valPtr);\n+ return (*env)->NewObject(env, kIntegerClass, kIntegerConstructor, val);\n+}\n+\n+static jboolean integerToInt(JNIEnv *env, jobject val, void* out) {\n+ *(jint*)out = (jint)((*env)->CallIntMethod(env, val, kIntegerIntValue));\n+ return JNI_TRUE;\n+}\n+\n+\n+#if junixsocket_have_tipc\n+# if !defined(TIPC_GROUP_JOIN)\n+struct tipc_group_req {\n+ __u32 type;\n+ __u32 instance;\n+ __u32 scope;\n+ __u32 flags;\n+};\n+# endif\n+\n+static jobject groupReqToJava(JNIEnv *env, void* valPtr, socklen_t valLen) {\n+ if(valLen < sizeof(struct tipc_group_req)) {\n+ if(valLen == sizeof(jint)) {\n+ // response is just the group type\n+ return (*env)->CallStaticObjectMethod(env, kAFTIPCGroupRequestClass, kAFTIPCGroupRequestFromNative, *((jint*)valPtr),0,0,0);\n+ }\n+ return NULL;\n+ }\n+ struct tipc_group_req gr = *((struct tipc_group_req *)valPtr);\n+ return (*env)->CallStaticObjectMethod(env, kAFTIPCGroupRequestClass, kAFTIPCGroupRequestFromNative, gr.type, gr.instance, gr.scope, gr.flags);\n+}\n+\n+static jboolean javaToGroupReq(JNIEnv *env, jobject val, void* out) {\n+ struct tipc_group_req* gr = ((struct tipc_group_req *)out);\n+ gr->type = (*env)->CallIntMethod(env, val, kAFTIPCGroupRequestGetType);\n+ gr->instance = (*env)->CallIntMethod(env, val, kAFTIPCGroupRequestGetInstance);\n+ gr->scope = (*env)->CallIntMethod(env, val, kAFTIPCGroupRequestGetScopeId);\n+ gr->flags = (*env)->CallIntMethod(env, val, kAFTIPCGroupRequestGetFlagsValue);\n+\n+ return JNI_TRUE;\n+}\n+#endif\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: getSocketOption\n+ * Signature: (Ljava/io/FileDescriptor;IILjava/lang/Class;)Ljava/lang/Object;\n+ */\n+JNIEXPORT jobject JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_getSocketOption\n+(JNIEnv *env, jclass clazz CK_UNUSED, jobject fd, jint domain, jint optionName, jclass valueType)\n+{\n+ if(valueType == NULL) {\n+ _throwException(env, kExceptionNullPointerException, \"valueType\");\n+ return NULL;\n+ }\n+\n+ optionName = optionNameToNative(domain, optionName);\n+ domain = optionDomainToNative(domain);\n+ if(domain == -1 || optionName == -1) {\n+ _throwException(env, kExceptionSocketException, \"Unsupported socket option\");\n+ return NULL;\n+ }\n+\n+ int handle = _getFD(env, fd);\n+\n+ socklen_t valLen;\n+ jobject (*valConverter)(JNIEnv *env, void* valPtr, socklen_t valLen);\n+ if(kIntegerClass != NULL && (*env)->IsAssignableFrom(env, valueType, kIntegerClass)) {\n+ valLen = sizeof(jint);\n+ valConverter = &intToInteger;\n+#if junixsocket_have_tipc\n+ } else if(kAFTIPCGroupRequestClass != NULL && (*env)->IsAssignableFrom(env, valueType, kAFTIPCGroupRequestClass)) {\n+ valLen = sizeof(struct tipc_group_req);\n+ valConverter = &groupReqToJava;\n+#endif\n+ } else {\n+ _throwException(env, kExceptionSocketException, \"Unsupported value type\");\n+ return NULL;\n+ }\n+\n+ void *valPtr = calloc(valLen, 1);\n+\n+ int ret = getsockopt(handle, domain, optionName,\n+ WIN32_NEEDS_CHARP valPtr, &valLen);\n+ if(ret == -1) {\n+ _throwSockoptErrnumException(env, socket_errno, fd);\n+ free(valPtr);\n+ return NULL;\n+ }\n+\n+ jobject obj = valConverter(env, valPtr, valLen);\n+ if(obj == NULL) {\n+ _throwException(env, kExceptionSocketException, \"Unsupported response\");\n+ }\n+ free(valPtr);\n+ return obj;\n+}\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: setSocketOption\n+ * Signature: (Ljava/io/FileDescriptor;IILjava/lang/Object;)V\n+ */\n+JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_setSocketOption\n+(JNIEnv *env, jclass clazz CK_UNUSED, jobject fd, jint domain, jint optionName, jobject value)\n+{\n+ int handle = _getFD(env, fd);\n+\n+ optionName = optionNameToNative(domain, optionName);\n+ domain = optionDomainToNative(domain);\n+ if(domain == -1 || optionName == -1) {\n+ _throwException(env, kExceptionSocketException, \"Unsupported socket domain\");\n+ return;\n+ }\n+\n+ void* valPtr;\n+ socklen_t valLen;\n+ if(value == NULL) {\n+ valPtr = NULL;\n+ valLen = 0;\n+ } else {\n+ jclass objClass = (*env)->GetObjectClass(env, value);\n+ jboolean (*valConverter)(JNIEnv *,jobject,void*);\n+\n+ if(kIntegerClass != NULL && (*env)->IsAssignableFrom(env, objClass, kIntegerClass)) {\n+ valLen = sizeof(jint);\n+ valConverter = &integerToInt;\n+#if junixsocket_have_tipc\n+ } else if(kAFTIPCGroupRequestClass != NULL && (*env)->IsAssignableFrom(env, objClass, kAFTIPCGroupRequestClass)) {\n+ valLen = sizeof(struct tipc_group_req);\n+ valConverter = &javaToGroupReq;\n+#endif\n+ } else {\n+ _throwException(env, kExceptionSocketException, \"Unsupported value type\");\n+ return;\n+ }\n+ valPtr = calloc(valLen, 1);\n+\n+ if(!valConverter(env, value, valPtr)) {\n+ _throwException(env, kExceptionSocketException, \"Unsupported value\");\n+ goto end;\n+ }\n+ }\n+\n+ int ret = setsockopt(handle, domain, optionName,\n+ WIN32_NEEDS_CHARP valPtr, valLen);\n+ if(ret == -1) {\n+ _throwSockoptErrnumException(env, socket_errno, fd);\n+ }\n+\n+end:\n+ free(valPtr);\n+}\ndiff --git a/junixsocket-native/src/main/c/socketoptions.h b/junixsocket-native/src/main/c/socketoptions.h\nindex 5fa962e0e..177793e40 100644\n--- a/junixsocket-native/src/main/c/socketoptions.h\n+++ b/junixsocket-native/src/main/c/socketoptions.h\n@@ -21,4 +21,8 @@\n \n #include \"config.h\"\n \n+void init_socketoptions(JNIEnv *env);\n+\n+void destroy_socketoptions(JNIEnv *env);\n+\n #endif /* socketoptions_h */\ndiff --git a/junixsocket-native/src/main/c/socketpair.c b/junixsocket-native/src/main/c/socketpair.c\nindex 24e8961b3..91f543941 100644\n--- a/junixsocket-native/src/main/c/socketpair.c\n+++ b/junixsocket-native/src/main/c/socketpair.c\n@@ -11,14 +11,22 @@\n #include \"exceptions.h\"\n #include \"socket.h\"\n #include \"filedescriptors.h\"\n+#include \"address.h\"\n+#include \"init.h\"\n \n /*\n * Class: org_newsclub_net_unix_NativeUnixSocket\n * Method: socketPair\n- * Signature: (ILjava/io/FileDescriptor;Ljava/io/FileDescriptor;)V\n+ * Signature: (IILjava/io/FileDescriptor;Ljava/io/FileDescriptor;)V\n */\n JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socketPair\n-(JNIEnv *env, jclass clazz CK_UNUSED, jint type, jobject fd1, jobject fd2) {\n+(JNIEnv *env, jclass clazz CK_UNUSED, jint domain, jint type, jobject fd1, jobject fd2) {\n+ domain = domainToNative(domain);\n+ if(domain == -1) {\n+ _throwException(env, kExceptionSocketException, \"Unsupported domain\");\n+ return;\n+ }\n+\n type = sockTypeToNative(env, type);\n if(type == -1) {\n return;\n@@ -31,7 +39,7 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socketPair\n // return;\n \n int handleListen = socket(AF_INET, type, 0);\n- if(handleListen <= 0) {\n+ if(handleListen < 0) {\n _throwErrnumException(env, socket_errno, NULL);\n return;\n }\n@@ -63,7 +71,7 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socketPair\n }\n \n int handleConnect = socket(AF_INET, type, 0);\n- if(handleConnect <= 0) {\n+ if(handleConnect < 0) {\n _throwErrnumException(env, socket_errno, NULL);\n return;\n }\n@@ -71,8 +79,8 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socketPair\n u_long mode = 1;\n if(ioctlsocket(handleConnect, FIONBIO, &mode) != NO_ERROR) {\n int errnum = socket_errno;\n- close(handleListen);\n- close(handleConnect);\n+ closesocket(handleListen);\n+ closesocket(handleConnect);\n _throwErrnumException(env, errnum, NULL);\n return;\n }\n@@ -85,18 +93,18 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socketPair\n \n len = sizeof(struct sockaddr_in);\n int handleAccept = accept(handleListen, (struct sockaddr *)&addr, &len);\n- if(handleAccept <= 0) {\n+ if(handleAccept < 0) {\n _throwErrnumException(env, socket_errno, NULL);\n return;\n }\n \n- close(handleListen);\n+ closesocket(handleListen);\n \n mode = 0;\n if(ioctlsocket(handleConnect, FIONBIO, &mode) != NO_ERROR) {\n int errnum = socket_errno;\n- close(handleAccept);\n- close(handleConnect);\n+ closesocket(handleAccept);\n+ closesocket(handleConnect);\n _throwErrnumException(env, errnum, NULL);\n return;\n }\n@@ -107,18 +115,23 @@ JNIEXPORT void JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_socketPair\n int socket_vector[2];\n int ret;\n #if defined(junixsocket_have_socket_cloexec)\n- ret = socketpair(AF_UNIX, type, SOCK_CLOEXEC, socket_vector);\n- if(ret == -1 && errno == EPROTONOSUPPORT) {\n- ret = socketpair(AF_UNIX, type, 0, socket_vector);\n- if(ret == 0) {\n-# if defined(FD_CLOEXEC)\n- fcntl(socket_vector[0], F_SETFD, FD_CLOEXEC); // best effort\n- fcntl(socket_vector[1], F_SETFD, FD_CLOEXEC); // best effort\n-# endif\n+ if(supportsUNIX()) {\n+ ret = socketpair(domain, type, SOCK_CLOEXEC, socket_vector);\n+ if(ret == -1 && errno == EPROTONOSUPPORT) {\n+ ret = socketpair(domain, type, 0, socket_vector);\n+ if(ret == 0) {\n+# if defined(FD_CLOEXEC)\n+ fcntl(socket_vector[0], F_SETFD, FD_CLOEXEC); // best effort\n+ fcntl(socket_vector[1], F_SETFD, FD_CLOEXEC); // best effort\n+# endif\n+ }\n }\n+ } else {\n+ // workaround for OSv assert(proto == 0);\n+ ret = socketpair(domain, type, 0, socket_vector);\n }\n #else\n- ret = socketpair(AF_UNIX, type, 0, socket_vector);\n+ ret = socketpair(domain, type, 0, socket_vector);\n #endif\n if(ret == -1) {\n _throwErrnumException(env, socket_errno, NULL);\ndiff --git a/junixsocket-native/src/main/c/tipc.c b/junixsocket-native/src/main/c/tipc.c\nnew file mode 100644\nindex 000000000..d754a1865\n--- /dev/null\n+++ b/junixsocket-native/src/main/c/tipc.c\n@@ -0,0 +1,116 @@\n+//\n+// tipc.c\n+// junixsocket-native\n+//\n+// Created by Christian Kohlschütter\n+//\n+\n+#include \"tipc.h\"\n+\n+#include \"exceptions.h\"\n+\n+#if junixsocket_have_tipc\n+\n+#if !defined(SIOCGETLINKNAME)\n+#define SIOCGETLINKNAME SIOCPROTOPRIVATE\n+#define TIPC_MAX_LINK_NAME 68\n+struct tipc_sioc_ln_req {\n+ __u32 peer;\n+ __u32 bearer_id;\n+ char linkname[TIPC_MAX_LINK_NAME];\n+};\n+#endif\n+\n+#if !defined(SIOCGETNODEID)\n+#define SIOCGETNODEID (SIOCPROTOPRIVATE + 1)\n+#define TIPC_NODEID_LEN 16\n+struct tipc_sioc_nodeid_req {\n+ __u32 peer;\n+ char node_id[TIPC_NODEID_LEN];\n+};\n+#endif\n+\n+static int newTipcRDMSocket(void) {\n+#if defined(junixsocket_have_socket_cloexec)\n+ int fd = socket(AF_TIPC, SOCK_RDM | SOCK_CLOEXEC, 0);\n+ if(fd == -1 && errno == EPROTONOSUPPORT) {\n+ fd = socket(AF_TIPC, SOCK_RDM, 0);\n+ }\n+#else\n+ int fd = socket(AF_TIPC, SOCK_RDM, 0);\n+#endif\n+ return fd;\n+}\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: tipcGetNodeId\n+ * Signature: (I)[B\n+ */\n+JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_tipcGetNodeId\n+(JNIEnv *env, jclass clazz CK_UNUSED, jint peer)\n+{\n+ struct tipc_sioc_nodeid_req req = {\n+ .peer = peer\n+ };\n+\n+ int fd = newTipcRDMSocket();\n+ if(fd <= 0) {\n+ return NULL;\n+ }\n+ int ret = ioctl(fd, SIOCGETNODEID, &req);\n+ if(ret < 0) {\n+ int errnum = socket_errno;\n+ close(fd);\n+ if(errnum == ENOTTY) {\n+ // kernel does not implement ioctl\n+ } else {\n+ _throwErrnumException(env, errnum, NULL);\n+ }\n+ return NULL;\n+ }\n+ close(fd);\n+\n+ jsize len = (jsize)strnlen(req.node_id, TIPC_NODEID_LEN);\n+ jbyteArray buf = (*env)->NewByteArray(env, len);\n+ (*env)->SetByteArrayRegion(env, buf, 0, len, (jbyte*)&(req.node_id));\n+\n+ return buf;}\n+\n+/*\n+ * Class: org_newsclub_net_unix_NativeUnixSocket\n+ * Method: tipcGetLinkName\n+ * Signature: (II)[B\n+ */\n+JNIEXPORT jbyteArray JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_tipcGetLinkName\n+(JNIEnv *env, jclass clazz CK_UNUSED, jint peer, jint bearerId) {\n+ struct tipc_sioc_ln_req req = {\n+ .peer = peer,\n+ .bearer_id = bearerId\n+ };\n+\n+ int fd = newTipcRDMSocket();\n+ if(fd <= 0) {\n+ return NULL;\n+ }\n+ int ret = ioctl(fd, SIOCGETLINKNAME, &req);\n+ if(ret < 0) {\n+ int errnum = socket_errno;\n+ close(fd);\n+ if(errnum == ENOTTY) {\n+ // kernel does not implement ioctl\n+ } else {\n+ _throwErrnumException(env, errnum, NULL);\n+ }\n+ return NULL;\n+ }\n+ close(fd);\n+\n+ jsize len = (jsize)strnlen(req.linkname, TIPC_MAX_LINK_NAME);\n+ jbyteArray buf = (*env)->NewByteArray(env, len);\n+ (*env)->SetByteArrayRegion(env, buf, 0, len, (jbyte*)&(req.linkname));\n+\n+ return buf;\n+}\n+\n+#endif\ndiff --git a/junixsocket-native/src/main/c/tipc.h b/junixsocket-native/src/main/c/tipc.h\nnew file mode 100644\nindex 000000000..7d2a8a1a0\n--- /dev/null\n+++ b/junixsocket-native/src/main/c/tipc.h\n@@ -0,0 +1,13 @@\n+//\n+// tipc.h\n+// junixsocket-native\n+//\n+// Created by Christian Kohlschütter\n+//\n+\n+#ifndef tipc_h\n+#define tipc_h\n+\n+#include \"config.h\"\n+\n+#endif /* tipc_h */\ndiff --git a/junixsocket-native/src/main/nar/aol.properties b/junixsocket-native/src/main/nar/aol.properties\nindex 0d573f9b7..e8dcabf24 100644\n--- a/junixsocket-native/src/main/nar/aol.properties\n+++ b/junixsocket-native/src/main/nar/aol.properties\n@@ -116,6 +116,50 @@ aarch64.Linux.clang.cpp.options=${junixsocket.native.clang.cpp.options} -target\n aarch64.Linux.clang.cpp.includes=${junixsocket.native.default.cpp.includes}\n aarch64.Linux.clang.cpp.excludes=\n \n+ppc64.AIX.clang.linker.name=clang\n+ppc64.AIX.clang.linker.options=${junixsocket.native.default.linker.options} -target ${junixsocket.native.llvm.target} -maix64 -Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc -static-libgcc -s\n+ppc64.AIX.clang.c.compiler=clang\n+ppc64.AIX.clang.c.defines=_GNU_SOURCE\n+ppc64.AIX.clang.c.options=${junixsocket.native.clang.c.options} -maix64 -Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc -Xcrossclang-hide-unknown-warning-warnings -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target} -D_THREAD_SAFE_ERRNO -D_BSD=44\n+ppc64.AIX.clang.c.includes=${junixsocket.native.default.c.includes}\n+ppc64.AIX.clang.c.excludes=\n+ppc64.AIX.clang.java.include=\n+ppc64.AIX.clang.java.runtimeDirectory=IGNORED\n+ppc64.AIX.clang.lib.prefix=lib\n+ppc64.AIX.clang.shared.prefix=lib\n+ppc64.AIX.clang.static.extension=a\n+ppc64.AIX.clang.shared.extension=a\n+ppc64.AIX.clang.plugin.extension=a\n+ppc64.AIX.clang.jni.extension=a\n+ppc64.AIX.clang.executable.extension=\n+ppc64.AIX.clang.cpp.compiler=clang++\n+ppc64.AIX.clang.cpp.defines=_GNU_SOURCE\n+ppc64.AIX.clang.cpp.options=${junixsocket.native.clang.cpp.options} -target ${junixsocket.native.llvm.target}\n+ppc64.AIX.clang.cpp.includes=${junixsocket.native.default.cpp.includes}\n+ppc64.AIX.clang.cpp.excludes=\n+\n+ppc64.OS400.clang.linker.name=clang\n+ppc64.OS400.clang.linker.options=${junixsocket.native.default.linker.options} -target powerpc-ibm-aix7.2.0.0 -maix64 -Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc -static-libgcc -s\n+ppc64.OS400.clang.c.compiler=clang\n+ppc64.OS400.clang.c.defines=_GNU_SOURCE\n+ppc64.OS400.clang.c.options=${junixsocket.native.clang.c.options} -maix64 -Xcrossclang-use-gcc=powerpc-ibm-aix7.2-gcc -Xcrossclang-hide-unknown-warning-warnings -I${project.basedir}/src/main/c/jni -target ${junixsocket.native.llvm.target} -D_THREAD_SAFE_ERRNO -D_BSD=44 -D_OS400\n+ppc64.OS400.clang.c.includes=${junixsocket.native.default.c.includes}\n+ppc64.OS400.clang.c.excludes=\n+ppc64.OS400.clang.java.include=\n+ppc64.OS400.clang.java.runtimeDirectory=IGNORED\n+ppc64.OS400.clang.lib.prefix=\n+ppc64.OS400.clang.shared.prefix=\n+ppc64.OS400.clang.static.extension=srvpgm\n+ppc64.OS400.clang.shared.extension=srvpgm\n+ppc64.OS400.clang.plugin.extension=srvpgm\n+ppc64.OS400.clang.jni.extension=srvpgm\n+ppc64.OS400.clang.executable.extension=\n+ppc64.OS400.clang.cpp.compiler=clang++\n+ppc64.OS400.clang.cpp.defines=_GNU_SOURCE\n+ppc64.OS400.clang.cpp.options=${junixsocket.native.clang.cpp.options} -target ${junixsocket.native.llvm.target}\n+ppc64.OS400.clang.cpp.includes=${junixsocket.native.default.cpp.includes}\n+ppc64.OS400.clang.cpp.excludes=\n+\n ppc64le.Linux.clang.linker.name=clang\n ppc64le.Linux.clang.linker.options=${junixsocket.native.default.linker.options} -Xcrossclang-with-and-without-lc -target ${junixsocket.native.llvm.target}\n ppc64le.Linux.clang.c.compiler=clang\n@@ -187,7 +231,7 @@ amd64.Windows10.clang.linker.options=${junixsocket.native.default.linker.options\n #amd64.Windows10.clang.linker.options=${junixsocket.native.default.linker.options} -target ${junixsocket.native.llvm.target} -Xcrossclang-use-ldshim -Wl,--Xldshim-ld=x86_64-w64-mingw32-ld\n amd64.Windows10.clang.c.compiler=clang\n amd64.Windows10.clang.c.defines=\n-amd64.Windows10.clang.c.options=${junixsocket.native.clang.c.options} -I${project.basedir}/src/main/c/jni -target unspecified -Xcrossclang-use-gcc=x86_64-w64-mingw32-gcc\n+amd64.Windows10.clang.c.options=${junixsocket.native.clang.c.options} -I${project.basedir}/src/main/c/jni -target unspecified -Xcrossclang-use-gcc=x86_64-w64-mingw32-gcc -Xcrossclang-hide-unknown-warning-warnings\n amd64.Windows10.clang.c.includes=${junixsocket.native.default.c.includes}\n amd64.Windows10.clang.c.excludes=\n amd64.Windows10.clang.java.include=\n@@ -206,6 +250,29 @@ amd64.Windows10.clang.cpp.options=${junixsocket.native.clang.cpp.options} -targe\n amd64.Windows10.clang.cpp.includes=${junixsocket.native.default.cpp.includes}\n amd64.Windows10.clang.cpp.excludes=\n \n+aarch64.Windows10.clang.linker.name=clang\n+aarch64.Windows10.clang.linker.options=${junixsocket.native.default.linker.options} -target unspecified -Xcrossclang-use-gcc=aarch64-w64-mingw32-gcc -lws2_32 -ladvapi32 -lmswsock -Xcrossclang-output-strip-lib-prefix -Xcrossclang-ignore-export-dynamic\n+aarch64.Windows10.clang.c.compiler=clang\n+aarch64.Windows10.clang.c.defines=\n+aarch64.Windows10.clang.c.options=${junixsocket.native.clang.c.options} -I${project.basedir}/src/main/c/jni -target unspecified -Xcrossclang-use-gcc=aarch64-w64-mingw32-gcc -Xcrossclang-hide-unknown-warning-warnings\n+aarch64.Windows10.clang.c.includes=${junixsocket.native.default.c.includes}\n+aarch64.Windows10.clang.c.excludes=\n+aarch64.Windows10.clang.java.include=\n+aarch64.Windows10.clang.java.runtimeDirectory=IGNORED\n+aarch64.Windows10.clang.lib.prefix=lib\n+aarch64.Windows10.clang.shared.prefix=lib\n+aarch64.Windows10.clang.static.extension=a\n+aarch64.Windows10.clang.shared.extension=dll\n+aarch64.Windows10.clang.plugin.extension=bundle\n+# NOTE: jnilib is also hardcoded in nar-maven-plugin's GccLinker#getLinker(LinkType)\n+aarch64.Windows10.clang.jni.extension=dll\n+aarch64.Windows10.clang.executable.extension=\n+aarch64.Windows10.clang.cpp.compiler=clang++\n+aarch64.Windows10.clang.cpp.defines=\n+aarch64.Windows10.clang.cpp.options=${junixsocket.native.clang.cpp.options} -target ${junixsocket.native.llvm.target}\n+aarch64.Windows10.clang.cpp.includes=${junixsocket.native.default.cpp.includes}\n+aarch64.Windows10.clang.cpp.excludes=\n+\n sparcv9.SunOS.clang.linker.name=clang\n sparcv9.SunOS.clang.linker.options=${junixsocket.native.default.linker.options} -m64 -nostdlib -target ${junixsocket.native.llvm.target}\n sparcv9.SunOS.clang.c.compiler=clang\ndiff --git a/junixsocket-rmi/pom.xml b/junixsocket-rmi/pom.xml\nindex 5048fc3ff..4830ef6fd 100644\n--- a/junixsocket-rmi/pom.xml\n+++ b/junixsocket-rmi/pom.xml\n@@ -8,7 +8,7 @@\n \n com.kohlschutter.junixsocket\n junixsocket-parent\n- 2.4.1-SNAPSHOT\n+ 2.5.0-SNAPSHOT\n ../pom.xml\n \n junixsocket-rmi\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFNaming.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFNaming.java\nnew file mode 100644\nindex 000000000..5d5d2a7a7\n--- /dev/null\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFNaming.java\n@@ -0,0 +1,520 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.rmi;\n+\n+import java.io.Closeable;\n+import java.io.IOException;\n+import java.net.MalformedURLException;\n+import java.rmi.AccessException;\n+import java.rmi.AlreadyBoundException;\n+import java.rmi.ConnectIOException;\n+import java.rmi.Naming;\n+import java.rmi.NoSuchObjectException;\n+import java.rmi.NotBoundException;\n+import java.rmi.Remote;\n+import java.rmi.RemoteException;\n+import java.rmi.ServerException;\n+import java.rmi.registry.LocateRegistry;\n+import java.rmi.registry.Registry;\n+import java.rmi.server.RMISocketFactory;\n+import java.rmi.server.UnicastRemoteObject;\n+import java.util.HashMap;\n+import java.util.Map;\n+import java.util.Objects;\n+import java.util.concurrent.TimeUnit;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.rmi.ShutdownHookSupport.ShutdownHook;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * The {@link AFSocket}-compatible equivalent of {@link Naming}. Use this class for accessing RMI\n+ * registries that are reachable by {@link AFSocket}s.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFNaming extends AFRegistryAccess {\n+ private static final String RMI_SERVICE_NAME = AFRMIService.class.getName();\n+\n+ private static final Map INSTANCES = new HashMap<>();\n+\n+ private AFRegistry registry = null;\n+ private AFRMIService rmiService = null;\n+ private final int registryPort;\n+ private final int servicePort;\n+ AFRMISocketFactory socketFactory;\n+ private boolean remoteShutdownAllowed = true;\n+ private final AtomicBoolean shutdownInProgress = new AtomicBoolean(false);\n+ private final AtomicBoolean addedShutdownHook = new AtomicBoolean(false);\n+\n+ /**\n+ * Creates a new naming instance with the given ports.\n+ * \n+ * @param registryPort The registry port.\n+ * @param servicePort The port for AFRMIService.\n+ * @throws IOException on error.\n+ */\n+ protected AFNaming(final int registryPort, final int servicePort) throws IOException {\n+ super();\n+ this.registryPort = registryPort;\n+ this.servicePort = servicePort;\n+ }\n+\n+ /**\n+ * Creates a new {@link AFRegistry} given a {@link Registry} implementation.\n+ * \n+ * @param impl The implementation.\n+ * @return The new {@link AFRegistry} instance.\n+ * @throws RemoteException on error.\n+ */\n+ protected abstract AFRegistry newAFRegistry(Registry impl) throws RemoteException;\n+\n+ /**\n+ * Creates or returns the {@link AFRMISocketFactory} to be used with this instance.\n+ * \n+ * @return The socket factory.\n+ * @throws IOException on error.\n+ */\n+ protected abstract AFRMISocketFactory initSocketFactory() throws IOException;\n+\n+ @SuppressWarnings(\"unchecked\")\n+ static T getInstance(final int registryPort,\n+ @NonNull AFNamingProvider provider) throws RemoteException {\n+ Objects.requireNonNull(provider);\n+ final AFNamingRef sap = new AFNamingRef(provider, registryPort);\n+ T instance;\n+ synchronized (AFNaming.class) {\n+ instance = (T) INSTANCES.get(sap);\n+ if (instance == null) {\n+ try {\n+ instance = provider.newInstance(registryPort);\n+ Objects.requireNonNull(instance);\n+ instance.socketFactory = instance.initSocketFactory();\n+ } catch (RemoteException e) {\n+ throw e;\n+ } catch (IOException e) {\n+ throw new RemoteException(e.getMessage(), e);\n+ }\n+ INSTANCES.put(sap, instance);\n+ }\n+ }\n+ return instance;\n+ }\n+\n+ /**\n+ * Returns the {@link AFRMISocketFactory} associated with this instance.\n+ * \n+ * @return The {@link AFRMISocketFactory}.\n+ */\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n+ public synchronized AFRMISocketFactory getSocketFactory() {\n+ return socketFactory;\n+ }\n+\n+ /**\n+ * Returns the registry port.\n+ * \n+ * @return The port.\n+ */\n+ public final int getRegistryPort() {\n+ return registryPort;\n+ }\n+\n+ AFRMIService getRMIService() throws RemoteException, NotBoundException {\n+ return getRMIService(getRegistry());\n+ }\n+\n+ AFRMIService getRMIService(AFRegistry reg) throws RemoteException, NotBoundException {\n+ if (rmiService == null) {\n+ this.rmiService = getRMIServiceFromRegistry(reg);\n+ }\n+ return rmiService;\n+ }\n+\n+ AFRMIService getRMIServiceFromRegistry(AFRegistry reg) throws RemoteException, NotBoundException {\n+ AFRMIService service;\n+ service = (AFRMIService) reg.lookup(RMI_SERVICE_NAME, 5, TimeUnit.SECONDS);\n+ this.remoteShutdownAllowed = service.isShutdownAllowed();\n+ return service;\n+ }\n+\n+ private void closeUponRuntimeShutdown() {\n+ if (addedShutdownHook.compareAndSet(false, true)) {\n+ ShutdownHookSupport.addWeakShutdownHook(new ShutdownHook() {\n+\n+ @Override\n+ public void onRuntimeShutdown(Thread thread) throws IOException {\n+ synchronized (AFNaming.class) {\n+ if (registry != null && registry.isLocal()) {\n+ shutdownRegistry();\n+ }\n+ }\n+ }\n+ });\n+ }\n+ }\n+\n+ private void rebindRMIService(final AFRMIService assigner) throws RemoteException {\n+ rmiService = assigner;\n+ getRegistry().rebind(RMI_SERVICE_NAME, assigner);\n+ }\n+\n+ @Override\n+ public AFRegistry getRegistry() throws RemoteException {\n+ return getRegistry(0, TimeUnit.SECONDS);\n+ }\n+\n+ /**\n+ * Returns a reference to the existing RMI registry.\n+ * \n+ * If there's no registry running at this port after waiting for up to the given time, an\n+ * exception is thrown.\n+ * \n+ * @param timeout The timeout value.\n+ * @param unit The timeout unit.\n+ * @return The registry.\n+ * @throws RemoteException If there was a problem.\n+ */\n+ public AFRegistry getRegistry(long timeout, TimeUnit unit) throws RemoteException {\n+ if (shutdownInProgress.get()) {\n+ throw new ShutdownException();\n+ }\n+ synchronized (AFNaming.class) {\n+ AFRegistry reg = getRegistry(false);\n+ if (reg == null) {\n+ reg = openRegistry(timeout, unit);\n+ }\n+ return reg;\n+ }\n+ }\n+\n+ /**\n+ * Tries to access the registry, waiting some time if necessary.\n+ * \n+ * @param timeout The timeout.\n+ * @param unit The unit for the timeout.\n+ * @return The registry instance.\n+ * @throws RemoteException on error.\n+ */\n+ protected abstract AFRegistry openRegistry(long timeout, TimeUnit unit) throws RemoteException;\n+\n+ /**\n+ * Returns a reference to the RMI registry, or {@code null}.\n+ *\n+ * If there's no registry running at this port, and {@code create} is set to {@code true}, a new\n+ * one is created; when {@code create} is set to {@code false}, {@code null} is returned.\n+ * \n+ * @param create {@code true} if a new register may be created if necessary.\n+ * @return The registry, or {@code null}\n+ * @throws RemoteException If there was a problem.\n+ */\n+ public AFRegistry getRegistry(boolean create) throws RemoteException {\n+ if (shutdownInProgress.get()) {\n+ throw new ShutdownException();\n+ }\n+ synchronized (AFNaming.class) {\n+ if (registry != null) {\n+ return registry;\n+ } else if (!socketFactory.hasRegisteredPort(registryPort)) {\n+ return create ? createRegistry() : null;\n+ }\n+\n+ AFRegistry reg = locateRegistry();\n+ setRegistry(reg);\n+\n+ try {\n+ getRMIService(reg);\n+ } catch (NotBoundException | NoSuchObjectException | ConnectIOException e) {\n+ if (create) {\n+ setRegistry(null);\n+ return createRegistry();\n+ } else {\n+ throw new ServerException(\"Could not access \" + AFRMIService.class.getName(), e);\n+ }\n+ }\n+\n+ return registry;\n+ }\n+ }\n+\n+ private AFRegistry locateRegistry() throws RemoteException {\n+ Registry regImpl = LocateRegistry.getRegistry(null, registryPort, socketFactory);\n+ return regImpl == null ? null : newAFRegistry(regImpl);\n+ }\n+\n+ /**\n+ * Shuts this RMI Registry down.\n+ * \n+ * @throws RemoteException if the operation fails.\n+ */\n+ public void shutdownRegistry() throws RemoteException {\n+ synchronized (AFNaming.class) {\n+ if (registry == null) {\n+ return;\n+ }\n+\n+ AFRegistry registryToBeClosed = registry;\n+ AFRMIService rmiServiceToBeClosed = rmiService;\n+\n+ if (!registryToBeClosed.isLocal()) {\n+ if (!isRemoteShutdownAllowed()) {\n+ throw new ServerException(\"The server refuses to be shutdown remotely\");\n+ }\n+ setRegistry(null);\n+\n+ try {\n+ shutdownViaRMIService(registryToBeClosed, rmiServiceToBeClosed);\n+ } catch (Exception e) {\n+ // ignore\n+ }\n+ return;\n+ }\n+\n+ setRegistry(null);\n+\n+ if (!shutdownInProgress.compareAndSet(false, true)) {\n+ return;\n+ }\n+ try {\n+ unexportRMIService(registryToBeClosed, (AFRMIServiceImpl) rmiServiceToBeClosed);\n+ forceUnexportBound(registryToBeClosed);\n+ closeSocketFactory();\n+ shutdownRegistryFinishingTouches();\n+ } finally {\n+ shutdownInProgress.set(false);\n+ }\n+ }\n+ }\n+\n+ /**\n+ * Called by {@link #shutdownRegistry()} as the final step.\n+ */\n+ protected abstract void shutdownRegistryFinishingTouches();\n+\n+ private void unexportRMIService(AFRegistry reg, AFRMIServiceImpl serv) throws AccessException,\n+ RemoteException {\n+ if (serv != null) {\n+ serv.shutdownRegisteredCloseables();\n+ }\n+\n+ try {\n+ if (serv != null) {\n+ unexportObject(serv);\n+ }\n+ reg.unbind(RMI_SERVICE_NAME);\n+ } catch (ShutdownException | NotBoundException e) {\n+ // ignore\n+ }\n+ this.rmiService = null;\n+ }\n+\n+ private void forceUnexportBound(AFRegistry reg) {\n+ try {\n+ reg.forceUnexportBound();\n+ } catch (Exception e) {\n+ // ignore\n+ }\n+ }\n+\n+ private void closeSocketFactory() {\n+ if (socketFactory != null) {\n+ try {\n+ socketFactory.close();\n+ } catch (IOException e) {\n+ // ignore\n+ }\n+ }\n+ }\n+\n+ private void shutdownViaRMIService(AFRegistry reg, AFRMIService serv) throws RemoteException {\n+ try {\n+ if (serv == null) {\n+ serv = getRMIService(reg);\n+ }\n+ if (serv.isShutdownAllowed()) {\n+ serv.shutdown();\n+ }\n+ } catch (ServerException | ConnectIOException | NotBoundException e) {\n+ // ignore\n+ }\n+ }\n+\n+ /**\n+ * Creates a new RMI {@link Registry}.\n+ * \n+ * If there already was a registry created previously, it is shut down and replaced by the current\n+ * one.\n+ * \n+ * Use {@link #getRegistry()} to try to reuse an existing registry.\n+ * \n+ * @return The registry\n+ * @throws RemoteException if the operation fails.\n+ * @see #getRegistry()\n+ */\n+ public AFRegistry createRegistry() throws RemoteException {\n+ synchronized (AFNaming.class) {\n+ AFRegistry existingRegistry = registry;\n+ if (existingRegistry == null) {\n+ try {\n+ existingRegistry = getRegistry(false);\n+ } catch (ServerException e) {\n+ Throwable cause = e.getCause();\n+ if (cause instanceof NotBoundException || cause instanceof ConnectIOException) {\n+ existingRegistry = null;\n+ } else {\n+ throw e;\n+ }\n+ }\n+ }\n+ if (existingRegistry != null) {\n+ if (!isRemoteShutdownAllowed()) {\n+ throw new ServerException(\"The server refuses to be shutdown remotely\");\n+ }\n+ shutdownRegistry();\n+ }\n+\n+ initRegistryPrerequisites();\n+\n+ setRegistry(newAFRegistry(LocateRegistry.createRegistry(registryPort, socketFactory,\n+ socketFactory)));\n+\n+ final AFRMIService service = new AFRMIServiceImpl(this);\n+ UnicastRemoteObject.exportObject(service, servicePort, socketFactory, socketFactory);\n+\n+ rebindRMIService(service);\n+\n+ return registry;\n+ }\n+ }\n+\n+ /**\n+ * Called by {@link #createRegistry()} right before creating/setting the registry.\n+ * \n+ * @throws ServerException on error.\n+ */\n+ protected abstract void initRegistryPrerequisites() throws ServerException;\n+\n+ /**\n+ * Checks if this {@link AFNaming} instance can be shut down remotely.\n+ * \n+ * @return {@code true} if remote shutdown is allowed.\n+ */\n+ public boolean isRemoteShutdownAllowed() {\n+ return remoteShutdownAllowed;\n+ }\n+\n+ /**\n+ * Controls whether this {@link AFNaming} instance can be shut down remotely.\n+ * \n+ * @param remoteShutdownAllowed {@code true} if remote shutdown is allowed.\n+ */\n+ public void setRemoteShutdownAllowed(boolean remoteShutdownAllowed) {\n+ this.remoteShutdownAllowed = remoteShutdownAllowed;\n+ }\n+\n+ /**\n+ * Exports and binds the given Remote object to the given name, using the given {@link AFNaming}\n+ * setup.\n+ * \n+ * @param name The name to use to bind the object in the registry.\n+ * @param obj The object to export and bind.\n+ * @throws RemoteException if the operation fails.\n+ * @throws AlreadyBoundException if there already was something bound at that name\n+ */\n+ public void exportAndBind(String name, Remote obj) throws RemoteException, AlreadyBoundException {\n+ exportObject(obj, getSocketFactory());\n+\n+ getRegistry().bind(name, obj);\n+ }\n+\n+ /**\n+ * Exports and re-binds the given Remote object to the given name, using the given\n+ * {@link AFNaming} setup.\n+ * \n+ * @param name The name to use to bind the object in the registry.\n+ * @param obj The object to export and bind.\n+ * @throws RemoteException if the operation fails.\n+ */\n+ public void exportAndRebind(String name, Remote obj) throws RemoteException {\n+ exportObject(obj, getSocketFactory());\n+\n+ getRegistry().rebind(name, obj);\n+ }\n+\n+ /**\n+ * Forcibly un-exports the given object, if it exists, and unbinds the object from the registry\n+ * (otherwise returns without an error).\n+ *\n+ * @param name The name used to bind the object.\n+ * @param obj The object to un-export.\n+ * @throws RemoteException if the operation fails.\n+ */\n+ public void unexportAndUnbind(String name, Remote obj) throws RemoteException {\n+ unexportObject(obj);\n+ try {\n+ unbind(name);\n+ } catch (MalformedURLException | NotBoundException e) {\n+ // ignore\n+ }\n+ }\n+\n+ /**\n+ * Exports the given Remote object, using the given socket factory and a randomly assigned port.\n+ * \n+ * NOTE: This helper function can also be used for regular RMI servers.\n+ * \n+ * @param obj The object to export.\n+ * @param socketFactory The socket factory to use.\n+ * @return The remote stub.\n+ * @throws RemoteException if the operation fails.\n+ */\n+ public static Remote exportObject(Remote obj, RMISocketFactory socketFactory)\n+ throws RemoteException {\n+ return UnicastRemoteObject.exportObject(obj, 0, socketFactory, socketFactory);\n+ }\n+\n+ /**\n+ * Forcibly un-exports the given object, if it exists (otherwise returns without an error). This\n+ * should be called upon closing a {@link Closeable} {@link Remote} object.\n+ * \n+ * NOTE: This helper function can also be used for regular RMI servers.\n+ * \n+ * @param obj The object to un-export.\n+ */\n+ public static void unexportObject(Remote obj) {\n+ try {\n+ UnicastRemoteObject.unexportObject(obj, true);\n+ } catch (NoSuchObjectException e) {\n+ // ignore\n+ }\n+ }\n+\n+ private void setRegistry(AFRegistry registry) {\n+ synchronized (AFNaming.class) {\n+ this.registry = registry;\n+ if (registry == null) {\n+ rmiService = null;\n+ } else if (registry.isLocal()) {\n+ closeUponRuntimeShutdown();\n+ }\n+ }\n+ }\n+}\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFNamingProvider.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFNamingProvider.java\nnew file mode 100644\nindex 000000000..4f9bab76b\n--- /dev/null\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFNamingProvider.java\n@@ -0,0 +1,46 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.rmi;\n+\n+import java.io.IOException;\n+\n+/**\n+ * The key to accessing to {@link AFNaming} instances.\n+ * \n+ * Implementors must guarantee that {@link #hashCode()} and {@link #equals(Object)} correctly\n+ * identify duplicate providers.\n+ * \n+ * @param The actual {@link AFNaming} subclass.\n+ * @author Christian Kohlschütter\n+ */\n+public interface AFNamingProvider {\n+ /**\n+ * Creates a new {@link AFNaming} instance using the given registry port.\n+ * \n+ * @param registryPort The registry port.\n+ * @return The {@link AFNaming} instance.\n+ * @throws IOException on error.\n+ */\n+ T newInstance(int registryPort) throws IOException;\n+\n+ @Override\n+ int hashCode();\n+\n+ @Override\n+ boolean equals(Object other);\n+}\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFNamingRef.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFNamingRef.java\nnew file mode 100644\nindex 000000000..a3f902891\n--- /dev/null\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFNamingRef.java\n@@ -0,0 +1,53 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.rmi;\n+\n+import java.rmi.RemoteException;\n+import java.util.Objects;\n+\n+/**\n+ * A reference to a {@link AFNaming} instance.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+final class AFNamingRef {\n+ private final AFNamingProvider provider;\n+ private final int port;\n+\n+ AFNamingRef(AFNamingProvider provider, int port) throws RemoteException {\n+ this.provider = provider;\n+ this.port = port;\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return Objects.hash(port, provider);\n+ }\n+\n+ @Override\n+ public boolean equals(Object obj) {\n+ if (this == obj) {\n+ return true;\n+ }\n+ if (!(obj instanceof AFNamingRef)) {\n+ return false;\n+ }\n+ AFNamingRef other = (AFNamingRef) obj;\n+ return port == other.port && Objects.equals(provider, other.provider);\n+ }\n+}\n\\ No newline at end of file\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMIService.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRMIService.java\nsimilarity index 92%\nrename from junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMIService.java\nrename to junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRMIService.java\nindex 8b4e93695..80efae924 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMIService.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRMIService.java\n@@ -24,13 +24,13 @@ import java.rmi.RemoteException;\n import java.util.stream.IntStream;\n \n /**\n- * The {@link AFUNIXRMIService} assigns and keeps track of anonymous ports, among other things.\n+ * The {@link AFRMIService} assigns and keeps track of anonymous ports, among other things.\n * \n- * This feature is to be used by {@link AFUNIXRMISocketFactory} only.\n+ * This feature is to be used by {@link AFRMISocketFactory} only.\n * \n * @author Christian Kohlschütter\n */\n-public interface AFUNIXRMIService extends Remote {\n+public interface AFRMIService extends Remote {\n /**\n * Registers a new anonymous port and returns it. When the port is not required anymore, it must\n * be returned via {@link #returnPort(int)}.\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMIServiceImpl.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRMIServiceImpl.java\nsimilarity index 89%\nrename from junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMIServiceImpl.java\nrename to junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRMIServiceImpl.java\nindex 79256a2da..de3e70f06 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMIServiceImpl.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRMIServiceImpl.java\n@@ -37,16 +37,16 @@ import java.util.stream.IntStream;\n import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n /**\n- * A very simple implementation of a {@link AFUNIXRMIService}.\n+ * A very simple implementation of a {@link AFRMIService}.\n * \n * @author Christian Kohlschütter\n */\n-final class AFUNIXRMIServiceImpl implements AFUNIXRMIService {\n+final class AFRMIServiceImpl implements AFRMIService {\n private final BitSet ports = new BitSet(1000);\n- private final WeakReference naming;\n+ private final WeakReference naming;\n private final List> closeAtShutdown = new ArrayList<>();\n \n- public AFUNIXRMIServiceImpl(AFUNIXNaming naming) {\n+ public AFRMIServiceImpl(AFNaming naming) {\n this.naming = new WeakReference<>(naming);\n }\n \n@@ -75,25 +75,25 @@ final class AFUNIXRMIServiceImpl implements AFUNIXRMIService {\n public synchronized int newPort() throws IOException {\n int port = randomPort();\n ports.set(port);\n- port += AFUNIXRMIPorts.ANONYMOUS_PORT_BASE;\n+ port += RMIPorts.ANONYMOUS_PORT_BASE;\n return port;\n }\n \n @Override\n public synchronized void returnPort(int port) throws IOException {\n- ports.clear(port - AFUNIXRMIPorts.ANONYMOUS_PORT_BASE);\n+ ports.clear(port - RMIPorts.ANONYMOUS_PORT_BASE);\n }\n \n @Override\n public IntStream openPorts() throws RemoteException {\n return ports.stream().map((int v) -> {\n- return v + AFUNIXRMIPorts.ANONYMOUS_PORT_BASE;\n+ return v + RMIPorts.ANONYMOUS_PORT_BASE;\n });\n }\n \n @Override\n public void shutdown() throws RemoteException {\n- AFUNIXNaming namingInstance = naming.get();\n+ AFNaming namingInstance = naming.get();\n if (namingInstance != null) {\n if (!namingInstance.isRemoteShutdownAllowed()) {\n throw new ServerException(\"Remote shutdown is disabled\");\n@@ -108,7 +108,7 @@ final class AFUNIXRMIServiceImpl implements AFUNIXRMIService {\n \n @Override\n public boolean isShutdownAllowed() throws RemoteException {\n- AFUNIXNaming namingInstance = naming.get();\n+ AFNaming namingInstance = naming.get();\n if (namingInstance != null) {\n return namingInstance.isRemoteShutdownAllowed();\n } else {\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRMISocketFactory.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRMISocketFactory.java\nnew file mode 100644\nindex 000000000..0133d319c\n--- /dev/null\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRMISocketFactory.java\n@@ -0,0 +1,349 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.rmi;\n+\n+import java.io.Closeable;\n+import java.io.Externalizable;\n+import java.io.IOException;\n+import java.io.ObjectInput;\n+import java.io.ObjectOutput;\n+import java.net.ServerSocket;\n+import java.net.Socket;\n+import java.rmi.NotBoundException;\n+import java.rmi.server.RMIClientSocketFactory;\n+import java.rmi.server.RMIServerSocketFactory;\n+import java.rmi.server.RMISocketFactory;\n+import java.util.HashMap;\n+import java.util.HashSet;\n+import java.util.Map;\n+import java.util.Set;\n+\n+import org.newsclub.net.unix.AFServerSocket;\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.AFSocketAddress;\n+import org.newsclub.net.unix.rmi.ShutdownHookSupport.ShutdownHook;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * An {@link RMISocketFactory} that supports {@link AFSocket}s.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFRMISocketFactory extends RMISocketFactory implements Externalizable,\n+ Closeable {\n+ private static final long serialVersionUID = 1L;\n+\n+ private RMIClientSocketFactory defaultClientFactory;\n+ private RMIServerSocketFactory defaultServerFactory;\n+\n+ private AFNaming naming;\n+\n+ private AFRMIService rmiService = null;\n+\n+ private final Map> openServerSockets = new HashMap<>();\n+ private final Set> openSockets = new HashSet<>();\n+\n+ /**\n+ * Constructor required per definition.\n+ * \n+ * @see RMISocketFactory\n+ */\n+ public AFRMISocketFactory() {\n+ super();\n+ closeUponRuntimeShutdown();\n+ }\n+\n+ /**\n+ * Creates a new socket factory.\n+ * \n+ * @param naming The {@link AFNaming} instance to use.\n+ * @param defaultClientFactory The default {@link RMIClientSocketFactory}.\n+ * @param defaultServerFactory The default {@link RMIServerSocketFactory}.\n+ * @throws IOException on error.\n+ */\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP2\")\n+ public AFRMISocketFactory(final AFNaming naming,\n+ final RMIClientSocketFactory defaultClientFactory,\n+ final RMIServerSocketFactory defaultServerFactory) throws IOException {\n+ super();\n+ this.naming = naming;\n+ this.defaultClientFactory = defaultClientFactory;\n+ this.defaultServerFactory = defaultServerFactory;\n+\n+ closeUponRuntimeShutdown();\n+ }\n+\n+ // only to be called from the constructor\n+ private void closeUponRuntimeShutdown() {\n+ ShutdownHookSupport.addWeakShutdownHook(new ShutdownHook() {\n+\n+ @Override\n+ public void onRuntimeShutdown(Thread thread) {\n+ try {\n+ close();\n+ } catch (IOException e) {\n+ // ignore\n+ }\n+ }\n+ });\n+ }\n+\n+ /**\n+ * Creates a new socket address for the given RMI port.\n+ * \n+ * @param port The port.\n+ * @return The socket address.\n+ * @throws IOException on error.\n+ */\n+ protected abstract AFSocketAddress newSocketAddress(int port) throws IOException;\n+\n+ /**\n+ * Creates a new socket that is connected to the given socket address.\n+ * \n+ * @param addr The socket address.\n+ * @return The connected socket.\n+ * @throws IOException on error.\n+ */\n+ protected abstract AFSocket newConnectedSocket(AFSocketAddress addr) throws IOException;\n+\n+ @Override\n+ public Socket createSocket(String host, int port) throws IOException {\n+ final RMIClientSocketFactory cf = defaultClientFactory;\n+ if (cf != null && port < RMIPorts.AF_PORT_BASE) {\n+ return cf.createSocket(host, port);\n+ }\n+\n+ final AFSocketAddress addr = newSocketAddress(port);\n+ AFSocket socket = newConnectedSocket(addr);\n+\n+ synchronized (openSockets) {\n+ openSockets.add(socket);\n+ }\n+ socket.addCloseable(() -> {\n+ synchronized (openSockets) {\n+ openSockets.remove(socket);\n+ }\n+ });\n+ return socket;\n+ }\n+\n+ @Override\n+ public void close() throws IOException {\n+ synchronized (naming) {\n+ rmiService = null;\n+ closeServerSockets();\n+ closeSockets();\n+ }\n+ }\n+\n+ private AFRMIService getRmiService() throws IOException {\n+ synchronized (naming) {\n+ if (rmiService == null) {\n+ try {\n+ rmiService = naming.getRMIService();\n+ } catch (NotBoundException e) {\n+ throw (IOException) new IOException(e.getMessage()).initCause(e);\n+ }\n+ }\n+ return rmiService;\n+ }\n+ }\n+\n+ /**\n+ * Returns a new free port.\n+ * \n+ * @return The new port.\n+ * @throws IOException on error.\n+ * @see #returnPort(int)\n+ */\n+ protected int newPort() throws IOException {\n+ return getRmiService().newPort();\n+ }\n+\n+ /**\n+ * Returns a port that was previously returned by {@link #newPort()}.\n+ * \n+ * @param port The port to return.\n+ * @throws IOException on error.\n+ */\n+ protected void returnPort(int port) throws IOException {\n+ getRmiService().returnPort(port);\n+ }\n+\n+ @Override\n+ public ServerSocket createServerSocket(int port) throws IOException {\n+ if (port == 0) {\n+ port = newPort();\n+ final int returnPort = port;\n+ final AFSocketAddress addr = newSocketAddress(port);\n+ AFServerSocket ass = addr.getAddressFamily().newServerSocket();\n+ ass.addCloseable(() -> {\n+ returnPort(returnPort);\n+ });\n+ ass.setReuseAddress(true);\n+ ass.setDeleteOnClose(true);\n+ ass.bind(addr);\n+\n+ if (port >= RMIPorts.AF_PORT_BASE) {\n+ ass.addCloseable(new ServerSocketCloseable(ass, port));\n+ }\n+ return ass;\n+ }\n+\n+ final RMIServerSocketFactory sf = defaultServerFactory;\n+ if (sf != null && port < RMIPorts.AF_PORT_BASE) {\n+ return sf.createServerSocket(port);\n+ }\n+\n+ final AFSocketAddress addr = newSocketAddress(port);\n+ AFServerSocket socket = addr.getAddressFamily().newServerSocket();\n+ socket.setDeleteOnClose(true);\n+ socket.setReuseAddress(true);\n+ socket.bind(addr);\n+ socket.addCloseable(new ServerSocketCloseable(socket, port));\n+ return socket;\n+ }\n+\n+ private void closeServerSockets() throws IOException {\n+ Map> map;\n+ synchronized (openServerSockets) {\n+ map = new HashMap<>(openServerSockets);\n+ }\n+ IOException ex = null;\n+ for (Map.Entry> en : map.entrySet()) {\n+ try {\n+ en.getValue().close();\n+ } catch (ShutdownException e) {\n+ // ignore\n+ } catch (IOException e) {\n+ if (ex == null) {\n+ ex = e;\n+ } else {\n+ ex.addSuppressed(e);\n+ }\n+ }\n+ }\n+ synchronized (openServerSockets) {\n+ openServerSockets.clear();\n+ }\n+ if (ex != null) {\n+ throw ex;\n+ }\n+ }\n+\n+ private void closeSockets() {\n+ Set> set;\n+ synchronized (openSockets) {\n+ set = new HashSet<>(openSockets);\n+ }\n+ for (AFSocket socket : set) {\n+ try {\n+ socket.close();\n+ } catch (IOException e) {\n+ // ignore\n+ }\n+ }\n+ synchronized (openSockets) {\n+ openSockets.clear();\n+ }\n+ }\n+\n+ private final class ServerSocketCloseable implements Closeable {\n+ private final int port;\n+\n+ ServerSocketCloseable(AFServerSocket socket, int port) {\n+ this.port = port;\n+ synchronized (openServerSockets) {\n+ openServerSockets.put(port, socket);\n+ }\n+ }\n+\n+ @Override\n+ public void close() throws IOException {\n+ synchronized (openServerSockets) {\n+ openServerSockets.remove(port);\n+ }\n+ }\n+ }\n+\n+ @Override\n+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {\n+ naming = readNamingInstance(in);\n+ defaultClientFactory = (RMIClientSocketFactory) in.readObject();\n+ defaultServerFactory = (RMIServerSocketFactory) in.readObject();\n+ }\n+\n+ @Override\n+ public void writeExternal(ObjectOutput out) throws IOException {\n+ writeNamingInstance(out, naming);\n+ out.writeObject(defaultClientFactory);\n+ out.writeObject(defaultServerFactory);\n+ }\n+\n+ /**\n+ * Deserializes information necessary to instantiate the {@link AFNaming} instance.\n+ * \n+ * @param in The stream.\n+ * @return The {@link AFNaming} instance.\n+ * @throws IOException on error.\n+ */\n+ protected abstract AFNaming readNamingInstance(ObjectInput in) throws IOException;\n+\n+ /**\n+ * Serializes information necessary to instantiate the given {@link AFNaming} instance.\n+ * \n+ * @param out The stream.\n+ * @param namingInstance The {@link AFNaming} instance.\n+ * @throws IOException on error.\n+ */\n+ protected abstract void writeNamingInstance(ObjectOutput out, AFNaming namingInstance)\n+ throws IOException;\n+\n+ /**\n+ * Checks if the given port refers to a local server port.\n+ * \n+ * @param port The port to check.\n+ * @return {@code true} if the given port is a local server.\n+ */\n+ public boolean isLocalServer(int port) {\n+ if (port < RMIPorts.AF_PORT_BASE) {\n+ return false;\n+ }\n+ synchronized (openServerSockets) {\n+ return openServerSockets.containsKey(port);\n+ }\n+ }\n+\n+ /**\n+ * The naming instance.\n+ * \n+ * @return The instance.\n+ */\n+ protected AFNaming getNaming() {\n+ return naming;\n+ }\n+\n+ /**\n+ * Checks if this socket factory has some knowledge about the given port.\n+ * \n+ * @param port The port.\n+ * @return {@code true} if registered.\n+ */\n+ abstract boolean hasRegisteredPort(int port);\n+}\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRegistry.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRegistry.java\nnew file mode 100644\nindex 000000000..7fa3c85e4\n--- /dev/null\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRegistry.java\n@@ -0,0 +1,275 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.rmi;\n+\n+import java.io.IOException;\n+import java.rmi.AccessException;\n+import java.rmi.AlreadyBoundException;\n+import java.rmi.ConnectIOException;\n+import java.rmi.NoSuchObjectException;\n+import java.rmi.NotBoundException;\n+import java.rmi.Remote;\n+import java.rmi.RemoteException;\n+import java.rmi.registry.Registry;\n+import java.rmi.server.RemoteObject;\n+import java.rmi.server.RemoteServer;\n+import java.util.HashMap;\n+import java.util.Map;\n+import java.util.concurrent.TimeUnit;\n+\n+import org.newsclub.net.unix.rmi.ShutdownHookSupport.ShutdownHook;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * A wrapper for RMI registries, both remote and local, to allow for a clean removal of bound\n+ * resources upon shutdown.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFRegistry implements Registry {\n+ final RemoteCloseable boundCloser;\n+\n+ private final Registry impl;\n+ private final Map bound = new HashMap<>();\n+ private final AFNaming naming;\n+ private boolean boundCloserExported = false;\n+\n+ AFRegistry(AFNaming naming, Registry impl) throws RemoteException {\n+ this.naming = naming;\n+ this.impl = impl;\n+ this.boundCloser = new RemoteCloseable() {\n+ @Override\n+ public Void get() throws IOException {\n+ return null;\n+ }\n+\n+ @Override\n+ public void close() throws IOException {\n+ AFRegistry.this.forceUnexportBound();\n+ }\n+ };\n+\n+ if (isLocal()) {\n+ ShutdownHookSupport.addWeakShutdownHook(new ShutdownHook() {\n+ @Override\n+ public void onRuntimeShutdown(Thread thread) {\n+ forceUnexportBound();\n+ }\n+ });\n+ }\n+ }\n+\n+ /**\n+ * Returns {@code true} if the wrapped Registry instance is a locally created\n+ * {@link RemoteServer}.\n+ * \n+ * @return {@code true} if wrapped instance is a locally created {@link RemoteServer}.\n+ * @see #isLocal()\n+ */\n+ @Deprecated\n+ public boolean isRemoteServer() {\n+ return isLocal();\n+ }\n+\n+ /**\n+ * Returns {@code true} if the wrapped Registry instance is locally created.\n+ * \n+ * @return {@code true} if wrapped instance is locally created.\n+ */\n+ public final boolean isLocal() {\n+ return (impl instanceof RemoteServer);\n+ }\n+\n+ /**\n+ * Returns the {@link AFNaming} instance responsible for this registry.\n+ * \n+ * @return The {@link AFNaming} instance.\n+ */\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n+ public AFNaming getNaming() {\n+ return naming;\n+ }\n+\n+ @Override\n+ public Remote lookup(String name) throws RemoteException, NotBoundException, AccessException {\n+ return impl.lookup(name);\n+ }\n+\n+ @Override\n+ public void bind(String name, Remote obj) throws RemoteException, AlreadyBoundException,\n+ AccessException {\n+ impl.bind(name, RemoteObject.toStub(obj));\n+ synchronized (bound) {\n+ bound.put(name, obj);\n+ }\n+ checkBound();\n+ }\n+\n+ @Override\n+ public void unbind(String name) throws RemoteException, NotBoundException, AccessException {\n+ impl.unbind(name);\n+ synchronized (bound) {\n+ bound.remove(name);\n+ }\n+ checkBound();\n+ }\n+\n+ @Override\n+ public void rebind(String name, Remote obj) throws RemoteException, AccessException {\n+ impl.rebind(name, RemoteObject.toStub(obj));\n+ synchronized (bound) {\n+ bound.put(name, obj);\n+ }\n+ checkBound();\n+ }\n+\n+ @Override\n+ public String[] list() throws RemoteException, AccessException {\n+ return impl == null ? new String[0] : impl.list();\n+ }\n+\n+ /**\n+ * Returns the remote reference bound to the specified name in this registry. If the\n+ * reference has not been bound yet, repeated attempts to resolve it are made until the specified\n+ * time elapses.\n+ *\n+ * @param name the name for the remote reference to look up\n+ * @param timeout The timeout value.\n+ * @param unit The timeout unit.\n+ *\n+ * @return a reference to a remote object\n+ *\n+ * @throws NotBoundException if name is not currently bound and couldn't be resolved\n+ * in the specified time.\n+ *\n+ * @throws RemoteException if remote communication with the registry failed; if exception is a\n+ * ServerException containing an AccessException, then the\n+ * registry denies the caller access to perform this operation\n+ *\n+ * @throws AccessException if this registry is local and it denies the caller access to perform\n+ * this operation\n+ *\n+ * @throws NullPointerException if name is null\n+ */\n+ public Remote lookup(String name, long timeout, TimeUnit unit) throws NotBoundException,\n+ RemoteException {\n+ long timeWait = unit.toMillis(timeout);\n+\n+ Exception exFirst = null;\n+ do {\n+ try {\n+ return impl.lookup(name);\n+ } catch (NotBoundException | ConnectIOException | NoSuchObjectException e) {\n+ if (exFirst == null) {\n+ exFirst = e;\n+ }\n+ }\n+\n+ try {\n+ Thread.sleep(Math.min(timeWait, 50));\n+ } catch (InterruptedException e1) {\n+ exFirst.addSuppressed(e1);\n+ break;\n+ }\n+ timeWait -= 50;\n+ } while (timeWait > 0);\n+\n+ if (exFirst instanceof NotBoundException) {\n+ throw (NotBoundException) exFirst;\n+ } else if (exFirst instanceof RemoteException) {\n+ throw (RemoteException) exFirst;\n+ } else {\n+ throw new RemoteException(\"Lookup timed out\");\n+ }\n+ }\n+\n+ void forceUnexportBound() {\n+ final Map map;\n+ synchronized (bound) {\n+ map = new HashMap<>(bound);\n+ bound.clear();\n+ }\n+ try {\n+ checkBound();\n+ } catch (RemoteException e1) {\n+ // ignore\n+ }\n+ for (Map.Entry en : map.entrySet()) {\n+ String name = en.getKey();\n+ Remote obj = en.getValue();\n+ if (obj == null) {\n+ continue;\n+ }\n+ AFNaming.unexportObject(obj);\n+ try {\n+ unbind(name);\n+ } catch (RemoteException | NotBoundException e) {\n+ // ignore\n+ }\n+\n+ }\n+ try {\n+ for (String list : list()) {\n+ try {\n+ unbind(list);\n+ } catch (RemoteException | NotBoundException e) {\n+ // ignore\n+ }\n+ }\n+ } catch (RemoteException e) {\n+ // ignore\n+ }\n+\n+ AFNaming.unexportObject(this.impl);\n+ AFNaming.unexportObject(this);\n+ }\n+\n+ private void checkBound() throws RemoteException {\n+ boolean empty;\n+ synchronized (bound) {\n+ empty = bound.isEmpty();\n+ }\n+ if (empty) {\n+ if (boundCloserExported) {\n+ boundCloserExported = false;\n+\n+ AFRMIService service;\n+ try {\n+ service = naming.getRMIService(this);\n+ service.unregisterForShutdown(boundCloser);\n+ } catch (NoSuchObjectException | NotBoundException e) {\n+ return;\n+ } finally {\n+ AFNaming.unexportObject(boundCloser);\n+ }\n+ }\n+ } else if (!boundCloserExported) {\n+ AFNaming.exportObject(boundCloser, naming.getSocketFactory());\n+ boundCloserExported = true;\n+\n+ AFRMIService service;\n+ try {\n+ service = naming.getRMIService(this);\n+ } catch (NotBoundException e) {\n+ return;\n+ }\n+ service.registerForShutdown(boundCloser);\n+ }\n+ }\n+}\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRegistryAccess.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRegistryAccess.java\nsimilarity index 89%\nrename from junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRegistryAccess.java\nrename to junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRegistryAccess.java\nindex 670fbdc3e..89c07ecbe 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRegistryAccess.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFRegistryAccess.java\n@@ -25,7 +25,7 @@ import java.rmi.Remote;\n import java.rmi.RemoteException;\n import java.util.concurrent.TimeUnit;\n \n-abstract class AFUNIXRegistryAccess {\n+abstract class AFRegistryAccess {\n /**\n * Returns a reference to the existing RMI registry.\n * \n@@ -34,7 +34,7 @@ abstract class AFUNIXRegistryAccess {\n * @return The registry.\n * @throws RemoteException If there was a problem.\n */\n- public abstract AFUNIXRegistry getRegistry() throws RemoteException;\n+ public abstract AFRegistry getRegistry() throws RemoteException;\n \n /**\n * Convenience method for {@code getRegistry().lookup}.\n@@ -44,7 +44,7 @@ abstract class AFUNIXRegistryAccess {\n * @throws NotBoundException upon error\n * @throws MalformedURLException upon error\n * @throws RemoteException upon error\n- * @see AFUNIXRegistry#lookup(String)\n+ * @see AFRegistry#lookup(String)\n */\n public Remote lookup(String name) throws NotBoundException, MalformedURLException,\n RemoteException {\n@@ -61,7 +61,7 @@ abstract class AFUNIXRegistryAccess {\n * @throws NotBoundException upon error\n * @throws MalformedURLException upon error\n * @throws RemoteException upon error\n- * @see AFUNIXRegistry#lookup(String, long, TimeUnit)\n+ * @see AFRegistry#lookup(String, long, TimeUnit)\n */\n public Remote lookup(String name, long timeout, TimeUnit unit) throws NotBoundException,\n MalformedURLException, RemoteException {\n@@ -75,7 +75,7 @@ abstract class AFUNIXRegistryAccess {\n * @throws RemoteException upon error\n * @throws NotBoundException upon error\n * @throws MalformedURLException upon error\n- * @see AFUNIXRegistry#unbind(String)\n+ * @see AFRegistry#unbind(String)\n */\n public void unbind(String name) throws RemoteException, NotBoundException, MalformedURLException {\n getRegistry().unbind(name);\n@@ -89,7 +89,7 @@ abstract class AFUNIXRegistryAccess {\n * @throws RemoteException upon error\n * @throws AlreadyBoundException upon error\n * @throws MalformedURLException upon error\n- * @see AFUNIXRegistry#bind(String, Remote)\n+ * @see AFRegistry#bind(String, Remote)\n */\n public void bind(String name, Remote obj) throws AlreadyBoundException, MalformedURLException,\n RemoteException {\n@@ -103,7 +103,7 @@ abstract class AFUNIXRegistryAccess {\n * @param obj the remote reference to rebind\n * @throws RemoteException upon error\n * @throws MalformedURLException upon error\n- * @see AFUNIXRegistry#rebind(String, Remote)\n+ * @see AFRegistry#rebind(String, Remote)\n */\n public void rebind(String name, Remote obj) throws MalformedURLException, RemoteException {\n getRegistry().rebind(name, obj);\n@@ -112,7 +112,7 @@ abstract class AFUNIXRegistryAccess {\n /**\n * Convenience method for {@code getRegistry().list}.\n * \n- * Unlike {@link AFUNIXRegistry#list()}, in case the registry has been shut down already, an empty\n+ * Unlike {@link AFRegistry#list()}, in case the registry has been shut down already, an empty\n * array is returned.\n * \n * @return an array of the names bound in this registry\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXNaming.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXNaming.java\nindex 4d56fbda5..f838f0457 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXNaming.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXNaming.java\n@@ -17,34 +17,20 @@\n */\n package org.newsclub.net.unix.rmi;\n \n-import java.io.Closeable;\n import java.io.File;\n import java.io.IOException;\n-import java.net.MalformedURLException;\n import java.nio.file.Files;\n-import java.rmi.AccessException;\n-import java.rmi.AlreadyBoundException;\n-import java.rmi.ConnectIOException;\n import java.rmi.Naming;\n-import java.rmi.NoSuchObjectException;\n-import java.rmi.NotBoundException;\n-import java.rmi.Remote;\n import java.rmi.RemoteException;\n import java.rmi.ServerException;\n-import java.rmi.registry.LocateRegistry;\n import java.rmi.registry.Registry;\n-import java.rmi.server.RMISocketFactory;\n+import java.rmi.server.RMIClientSocketFactory;\n+import java.rmi.server.RMIServerSocketFactory;\n import java.rmi.server.UnicastRemoteObject;\n-import java.util.HashMap;\n-import java.util.Map;\n import java.util.Objects;\n import java.util.concurrent.TimeUnit;\n-import java.util.concurrent.atomic.AtomicBoolean;\n \n import org.newsclub.net.unix.AFUNIXSocket;\n-import org.newsclub.net.unix.rmi.ShutdownHookSupport.ShutdownHook;\n-\n-import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n /**\n * The {@link AFUNIXSocket}-compatible equivalent of {@link Naming}. Use this class for accessing\n@@ -52,41 +38,49 @@ import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n * \n * @author Christian Kohlschütter\n */\n-public final class AFUNIXNaming extends AFUNIXRegistryAccess {\n- private static final String RMI_SERVICE_NAME = AFUNIXRMIService.class.getName();\n+public final class AFUNIXNaming extends AFNaming {\n private static final String PROP_RMI_SOCKET_DIR = \"org.newsclub.net.unix.rmi.socketdir\";\n-\n private static final File DEFAULT_SOCKET_DIRECTORY = new File(System.getProperty(\n PROP_RMI_SOCKET_DIR, \"/tmp\"));\n \n- private static final Map INSTANCES = new HashMap<>();\n-\n- private AFUNIXRegistry registry = null;\n- private AFUNIXRMIService rmiService = null;\n- private final File registrySocketDir;\n- private final int registryPort;\n- private final int servicePort;\n- private final AFUNIXRMISocketFactory socketFactory;\n private boolean deleteRegistrySocketDir = false;\n- private boolean remoteShutdownAllowed = true;\n- private final AtomicBoolean shutdownInProgress = new AtomicBoolean(false);\n- private final AtomicBoolean addedShutdownHook = new AtomicBoolean(false);\n+ private final File registrySocketDir;\n+\n+ private final RMIClientSocketFactory defaultClientSocketFactory;\n+ private final RMIServerSocketFactory defaultServerSocketFactory;\n+\n+ private final String socketPrefix;\n+ private final String socketSuffix;\n \n- private AFUNIXNaming(final File socketDir, final int port, final String socketPrefix,\n- final String socketSuffix) throws IOException {\n- super();\n+ private AFUNIXNaming(File socketDir, int registryPort, String socketPrefix, String socketSuffix)\n+ throws IOException {\n+ super(registryPort, RMIPorts.RMI_SERVICE_PORT);\n+ Objects.requireNonNull(socketDir);\n this.registrySocketDir = socketDir;\n- this.registryPort = port;\n- this.servicePort = AFUNIXRMIPorts.RMI_SERVICE_PORT;\n- this.socketFactory = new AFUNIXRMISocketFactory(this, socketDir, null, null, socketPrefix,\n- socketSuffix);\n+ this.socketPrefix = socketPrefix;\n+ this.socketSuffix = socketSuffix;\n+\n+ this.defaultClientSocketFactory = null; // DefaultRMIClientSocketFactory.getInstance();\n+ this.defaultServerSocketFactory = null; // DefaultRMIServerSocketFactory.getInstance();\n+ }\n+\n+ /**\n+ * Returns the directory where RMI sockets are stored by default.\n+ * \n+ * You can configure this location by setting the System property\n+ * {@code org.newsclub.net.unix.rmi.socketdir} upon start.\n+ * \n+ * @return The directory.\n+ */\n+ public static File getDefaultSocketDirectory() {\n+ return DEFAULT_SOCKET_DIRECTORY;\n }\n \n /**\n * Returns a new private instance that resides in a custom location, to avoid any collisions with\n * existing instances.\n * \n- * @return The private {@link AFUNIXNaming} instance.\n+ * @return The private {@link AFNaming} instance.\n * @throws IOException if the operation fails.\n */\n public static AFUNIXNaming newPrivateInstance() throws IOException {\n@@ -94,8 +88,8 @@ public final class AFUNIXNaming extends AFUNIXRegistryAccess {\n if (!tmpDir.canWrite()) {\n throw new IOException(\"Could not create temporary directory: \" + tmpDir);\n }\n- AFUNIXNaming instance = getInstance(tmpDir, AFUNIXRMIPorts.DEFAULT_REGISTRY_PORT);\n- synchronized (AFUNIXNaming.class) {\n+ AFUNIXNaming instance = getInstance(tmpDir, RMIPorts.DEFAULT_REGISTRY_PORT);\n+ synchronized (instance) {\n instance.deleteRegistrySocketDir = true;\n }\n return instance;\n@@ -109,7 +103,7 @@ public final class AFUNIXNaming extends AFUNIXRegistryAccess {\n * @throws IOException if the operation fails.\n */\n public static AFUNIXNaming getInstance() throws IOException {\n- return getInstance(DEFAULT_SOCKET_DIRECTORY, AFUNIXRMIPorts.DEFAULT_REGISTRY_PORT);\n+ return getInstance(DEFAULT_SOCKET_DIRECTORY, RMIPorts.DEFAULT_REGISTRY_PORT);\n }\n \n /**\n@@ -121,7 +115,7 @@ public final class AFUNIXNaming extends AFUNIXRegistryAccess {\n * @throws RemoteException if the operation fails.\n */\n public static AFUNIXNaming getInstance(final File socketDir) throws RemoteException {\n- return getInstance(socketDir, AFUNIXRMIPorts.DEFAULT_REGISTRY_PORT);\n+ return getInstance(socketDir, RMIPorts.DEFAULT_REGISTRY_PORT);\n }\n \n /**\n@@ -158,24 +152,32 @@ public final class AFUNIXNaming extends AFUNIXRegistryAccess {\n */\n public static AFUNIXNaming getInstance(File socketDir, final int registryPort,\n String socketPrefix, String socketSuffix) throws RemoteException {\n- Objects.requireNonNull(socketDir);\n- final AFUNIXNamingRef sap = new AFUNIXNamingRef(socketDir, registryPort, socketPrefix,\n- socketSuffix);\n- AFUNIXNaming instance;\n- synchronized (AFUNIXNaming.class) {\n- instance = INSTANCES.get(sap);\n- if (instance == null) {\n- try {\n- instance = new AFUNIXNaming(sap.socketDir, registryPort, socketPrefix, socketSuffix);\n- } catch (RemoteException e) {\n- throw e;\n- } catch (IOException e) {\n- throw new RemoteException(e.getMessage(), e);\n- }\n- INSTANCES.put(sap, instance);\n+ return AFNaming.getInstance(registryPort, new AFUNIXNamingProvider(socketDir, socketPrefix,\n+ socketSuffix));\n+ }\n+\n+ private static final class AFUNIXNamingProvider implements AFNamingProvider {\n+ private final File socketDir;\n+ private final String socketPrefix;\n+ private final String socketSuffix;\n+\n+ public AFUNIXNamingProvider(File socketDir, String socketPrefix, String socketSuffix)\n+ throws RemoteException {\n+ try {\n+ this.socketDir = socketDir.getCanonicalFile();\n+ } catch (IOException e) {\n+ throw new RemoteException(e.getMessage(), e);\n }\n+ this.socketPrefix = socketPrefix == null ? AFUNIXRMISocketFactory.DEFAULT_SOCKET_FILE_PREFIX\n+ : socketPrefix;\n+ this.socketSuffix = socketSuffix == null ? AFUNIXRMISocketFactory.DEFAULT_SOCKET_FILE_SUFFIX\n+ : socketSuffix;\n+ }\n+\n+ @Override\n+ public AFUNIXNaming newInstance(int port) throws IOException {\n+ return new AFUNIXNaming(socketDir, port, socketPrefix, socketSuffix); // NOPMD\n }\n- return instance;\n }\n \n /**\n@@ -186,39 +188,33 @@ public final class AFUNIXNaming extends AFUNIXRegistryAccess {\n * @return The instance.\n * @throws IOException if the operation fails.\n */\n- public static AFUNIXNaming getSingleFileInstance(final File socketFile) throws IOException {\n- return getInstance(socketFile, AFUNIXRMIPorts.PLAIN_FILE_SOCKET);\n+ public static AFNaming getSingleFileInstance(final File socketFile) throws IOException {\n+ return getInstance(socketFile, RMIPorts.PLAIN_FILE_SOCKET);\n }\n \n- /**\n- * Returns the directory where RMI sockets are stored by default.\n- * \n- * You can configure this location by setting the System property\n- * {@code org.newsclub.net.unix.rmi.socketdir} upon start.\n- * \n- * @return The directory.\n- */\n- public static File getDefaultSocketDirectory() {\n- return DEFAULT_SOCKET_DIRECTORY;\n+ @Override\n+ public AFUNIXRMISocketFactory getSocketFactory() {\n+ return (AFUNIXRMISocketFactory) super.getSocketFactory();\n }\n \n- /**\n- * Returns the {@link AFUNIXRMISocketFactory} associated with this instance.\n- * \n- * @return The {@link AFUNIXRMISocketFactory}.\n- */\n- @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n- public AFUNIXRMISocketFactory getSocketFactory() {\n- return socketFactory;\n+ @Override\n+ public AFRegistry getRegistry() throws RemoteException {\n+ return getRegistry(0, TimeUnit.SECONDS);\n }\n \n- /**\n- * Returns the directory in which sockets used by this registry are located.\n- * \n- * @return The directory.\n- */\n- public File getRegistrySocketDir() {\n- return registrySocketDir;\n+ @Override\n+ public AFUNIXRegistry getRegistry(long timeout, TimeUnit unit) throws RemoteException {\n+ return (AFUNIXRegistry) super.getRegistry(timeout, unit);\n+ }\n+\n+ @Override\n+ public AFUNIXRegistry getRegistry(boolean create) throws RemoteException {\n+ return (AFUNIXRegistry) super.getRegistry(create);\n+ }\n+\n+ @Override\n+ public AFUNIXRegistry createRegistry() throws RemoteException {\n+ return (AFUNIXRegistry) super.createRegistry();\n }\n \n /**\n@@ -229,94 +225,32 @@ public final class AFUNIXNaming extends AFUNIXRegistryAccess {\n * @return The directory.\n */\n public File getRegistrySocketFile() {\n- return socketFactory.getFile(registryPort);\n- }\n-\n- /**\n- * Returns the registry port.\n- * \n- * @return The port.\n- */\n- public int getRegistryPort() {\n- return registryPort;\n- }\n-\n- AFUNIXRMIService getRMIService() throws RemoteException, NotBoundException {\n- return getRMIService(getRegistry());\n- }\n-\n- AFUNIXRMIService getRMIService(AFUNIXRegistry reg) throws RemoteException, NotBoundException {\n- if (rmiService == null) {\n- this.rmiService = getRMIServiceFromRegistry(reg);\n- }\n- return rmiService;\n- }\n-\n- AFUNIXRMIService getRMIServiceFromRegistry(AFUNIXRegistry reg) throws RemoteException,\n- NotBoundException {\n- AFUNIXRMIService service;\n- service = (AFUNIXRMIService) reg.lookup(RMI_SERVICE_NAME, 5, TimeUnit.SECONDS);\n- this.remoteShutdownAllowed = service.isShutdownAllowed();\n- return service;\n+ return getSocketFactory().getFile(getRegistryPort());\n }\n \n- private void closeUponRuntimeShutdown() {\n- if (addedShutdownHook.compareAndSet(false, true)) {\n- ShutdownHookSupport.addWeakShutdownHook(new ShutdownHook() {\n-\n- @Override\n- public void onRuntimeShutdown(Thread thread) throws IOException {\n- synchronized (AFUNIXNaming.class) {\n- if (registry != null && registry.isLocal()) {\n- shutdownRegistry();\n- }\n- }\n- }\n- });\n- }\n- }\n-\n- private void rebindRMIService(final AFUNIXRMIService assigner) throws RemoteException {\n- rmiService = assigner;\n- getRegistry().rebind(RMI_SERVICE_NAME, assigner);\n+ @Override\n+ protected AFUNIXRMISocketFactory initSocketFactory() throws IOException {\n+ return new AFUNIXRMISocketFactory(this, registrySocketDir, defaultClientSocketFactory,\n+ defaultServerSocketFactory, socketPrefix, socketSuffix);\n }\n \n @Override\n- public AFUNIXRegistry getRegistry() throws RemoteException {\n- return getRegistry(0, TimeUnit.SECONDS);\n+ protected AFUNIXRegistry newAFRegistry(Registry impl) throws RemoteException {\n+ return new AFUNIXRegistry(this, impl);\n }\n \n- /**\n- * Returns a reference to the existing RMI registry.\n- * \n- * If there's no registry running at this port after waiting for up to the given time, an\n- * exception is thrown.\n- * \n- * @param timeout The timeout value.\n- * @param unit The timeout unit.\n- * @return The registry.\n- * @throws RemoteException If there was a problem.\n- */\n- public AFUNIXRegistry getRegistry(long timeout, TimeUnit unit) throws RemoteException {\n- if (shutdownInProgress.get()) {\n- throw new ShutdownException();\n- }\n- synchronized (AFUNIXNaming.class) {\n- AFUNIXRegistry reg = getRegistry(false);\n- if (reg == null) {\n- File socketFile = getRegistrySocketFile();\n- if (!socketFile.exists()) {\n- if (waitUntilFileExists(socketFile, timeout, unit)) {\n- reg = getRegistry(false);\n- if (reg != null) {\n- return reg;\n- }\n- }\n+ @Override\n+ protected AFRegistry openRegistry(long timeout, TimeUnit unit) throws RemoteException {\n+ File socketFile = getRegistrySocketFile();\n+ if (!socketFile.exists()) {\n+ if (waitUntilFileExists(socketFile, timeout, unit)) {\n+ AFRegistry reg = getRegistry(false);\n+ if (reg != null) {\n+ return reg;\n }\n- throw new ShutdownException(\"Could not find registry at \" + getRegistrySocketFile());\n }\n- return reg;\n }\n+ throw new ShutdownException(\"Could not find registry at \" + getRegistrySocketFile());\n }\n \n private boolean waitUntilFileExists(File f, long timeout, TimeUnit unit) {\n@@ -334,131 +268,7 @@ public final class AFUNIXNaming extends AFUNIXRegistryAccess {\n return f.exists();\n }\n \n- /**\n- * Returns a reference to the RMI registry, or {@code null}.\n- *\n- * If there's no registry running at this port, and {@code create} is set to {@code true}, a new\n- * one is created; when {@code create} is set to {@code false}, {@code null} is returned.\n- * \n- * @param create {@code true} if a new register may be created if necessary.\n- * @return The registry, or {@code null}\n- * @throws RemoteException If there was a problem.\n- */\n- public AFUNIXRegistry getRegistry(boolean create) throws RemoteException {\n- if (shutdownInProgress.get()) {\n- throw new ShutdownException();\n- }\n- synchronized (AFUNIXNaming.class) {\n- if (registry != null) {\n- return registry;\n- } else if (!socketFactory.hasSocketFile(registryPort)) {\n- return create ? createRegistry() : null;\n- }\n-\n- AFUNIXRegistry reg = locateRegistry();\n- setRegistry(reg);\n-\n- try {\n- getRMIService(reg);\n- } catch (NotBoundException | NoSuchObjectException | ConnectIOException e) {\n- if (create) {\n- setRegistry(null);\n- return createRegistry();\n- } else {\n- throw new ServerException(\"Could not access \" + AFUNIXRMIService.class.getName(), e);\n- }\n- }\n-\n- return registry;\n- }\n- }\n-\n- private AFUNIXRegistry locateRegistry() throws RemoteException {\n- Registry regImpl = LocateRegistry.getRegistry(null, registryPort, socketFactory);\n- return regImpl == null ? null : new AFUNIXRegistry(this, regImpl);\n- }\n-\n- /**\n- * Shuts this RMI Registry down.\n- * \n- * @throws RemoteException if the operation fails.\n- */\n- public void shutdownRegistry() throws RemoteException {\n- synchronized (AFUNIXNaming.class) {\n- if (registry == null) {\n- return;\n- }\n-\n- AFUNIXRegistry registryToBeClosed = registry;\n- AFUNIXRMIService rmiServiceToBeClosed = rmiService;\n-\n- if (!registryToBeClosed.isLocal()) {\n- if (!isRemoteShutdownAllowed()) {\n- throw new ServerException(\"The server refuses to be shutdown remotely\");\n- }\n- setRegistry(null);\n-\n- try {\n- shutdownViaRMIService(registryToBeClosed, rmiServiceToBeClosed);\n- } catch (Exception e) {\n- // ignore\n- }\n- return;\n- }\n-\n- setRegistry(null);\n-\n- if (!shutdownInProgress.compareAndSet(false, true)) {\n- return;\n- }\n- try {\n- unexportRMIService(registryToBeClosed, (AFUNIXRMIServiceImpl) rmiServiceToBeClosed);\n- forceUnexportBound(registryToBeClosed);\n- closeSocketFactory();\n- deleteSocketDir();\n-\n- } finally {\n- shutdownInProgress.set(false);\n- }\n- }\n- }\n-\n- private void unexportRMIService(AFUNIXRegistry reg, AFUNIXRMIServiceImpl serv)\n- throws AccessException, RemoteException {\n- if (serv != null) {\n- serv.shutdownRegisteredCloseables();\n- }\n-\n- try {\n- if (serv != null) {\n- unexportObject(serv);\n- }\n- reg.unbind(RMI_SERVICE_NAME);\n- } catch (ShutdownException | NotBoundException e) {\n- // ignore\n- }\n- this.rmiService = null;\n- }\n-\n- private void forceUnexportBound(AFUNIXRegistry reg) {\n- try {\n- reg.forceUnexportBound();\n- } catch (Exception e) {\n- // ignore\n- }\n- }\n-\n- private void closeSocketFactory() {\n- if (socketFactory != null) {\n- try {\n- socketFactory.close();\n- } catch (IOException e) {\n- // ignore\n- }\n- }\n- }\n-\n- private void deleteSocketDir() {\n+ private synchronized void deleteSocketDir() {\n if (deleteRegistrySocketDir && registrySocketDir != null) {\n try {\n Files.delete(registrySocketDir.toPath());\n@@ -468,173 +278,25 @@ public final class AFUNIXNaming extends AFUNIXRegistryAccess {\n }\n }\n \n- private void shutdownViaRMIService(AFUNIXRegistry reg, AFUNIXRMIService serv)\n- throws RemoteException {\n- try {\n- if (serv == null) {\n- serv = getRMIService(reg);\n- }\n- if (serv.isShutdownAllowed()) {\n- serv.shutdown();\n- }\n- } catch (ServerException | ConnectIOException | NotBoundException e) {\n- // ignore\n- }\n- }\n-\n- /**\n- * Creates a new RMI {@link Registry}.\n- * \n- * If there already was a registry created previously, it is shut down and replaced by the current\n- * one.\n- * \n- * Use {@link #getRegistry()} to try to reuse an existing registry.\n- * \n- * @return The registry\n- * @throws RemoteException if the operation fails.\n- * @see #getRegistry()\n- */\n- public AFUNIXRegistry createRegistry() throws RemoteException {\n- synchronized (AFUNIXNaming.class) {\n- AFUNIXRegistry existingRegistry = registry;\n- if (existingRegistry == null) {\n- try {\n- existingRegistry = getRegistry(false);\n- } catch (ServerException e) {\n- Throwable cause = e.getCause();\n- if (cause instanceof NotBoundException || cause instanceof ConnectIOException) {\n- existingRegistry = null;\n- } else {\n- throw e;\n- }\n- }\n- }\n- if (existingRegistry != null) {\n- if (!isRemoteShutdownAllowed()) {\n- throw new ServerException(\"The server refuses to be shutdown remotely\");\n- }\n- shutdownRegistry();\n- }\n-\n- if (registrySocketDir != null && !registrySocketDir.mkdirs() && !registrySocketDir\n- .isDirectory()) {\n- throw new ServerException(\"Cannot create socket directory:\" + registrySocketDir);\n- }\n- setRegistry(new AFUNIXRegistry(this, LocateRegistry.createRegistry(registryPort,\n- socketFactory, socketFactory)));\n-\n- final AFUNIXRMIService service = new AFUNIXRMIServiceImpl(this);\n- UnicastRemoteObject.exportObject(service, servicePort, socketFactory, socketFactory);\n-\n- rebindRMIService(service);\n-\n- return registry;\n- }\n- }\n-\n- /**\n- * Checks if this {@link AFUNIXNaming} instance can be shut down remotely.\n- * \n- * @return {@code true} if remote shutdown is allowed.\n- */\n- public boolean isRemoteShutdownAllowed() {\n- return remoteShutdownAllowed;\n- }\n-\n- /**\n- * Controls whether this {@link AFUNIXNaming} instance can be shut down remotely.\n- * \n- * @param remoteShutdownAllowed {@code true} if remote shutdown is allowed.\n- */\n- public void setRemoteShutdownAllowed(boolean remoteShutdownAllowed) {\n- this.remoteShutdownAllowed = remoteShutdownAllowed;\n- }\n-\n- /**\n- * Exports and binds the given Remote object to the given name, using the given\n- * {@link AFUNIXNaming} setup.\n- * \n- * @param name The name to use to bind the object in the registry.\n- * @param obj The object to export and bind.\n- * @throws RemoteException if the operation fails.\n- * @throws AlreadyBoundException if there already was something bound at that name\n- */\n- public void exportAndBind(String name, Remote obj) throws RemoteException, AlreadyBoundException {\n- exportObject(obj, getSocketFactory());\n-\n- getRegistry().bind(name, obj);\n- }\n-\n- /**\n- * Exports and re-binds the given Remote object to the given name, using the given\n- * {@link AFUNIXNaming} setup.\n- * \n- * @param name The name to use to bind the object in the registry.\n- * @param obj The object to export and bind.\n- * @throws RemoteException if the operation fails.\n- */\n- public void exportAndRebind(String name, Remote obj) throws RemoteException {\n- exportObject(obj, getSocketFactory());\n-\n- getRegistry().rebind(name, obj);\n- }\n-\n- /**\n- * Forcibly un-exports the given object, if it exists, and unbinds the object from the registry\n- * (otherwise returns without an error).\n- *\n- * @param name The name used to bind the object.\n- * @param obj The object to un-export.\n- * @throws RemoteException if the operation fails.\n- */\n- public void unexportAndUnbind(String name, Remote obj) throws RemoteException {\n- unexportObject(obj);\n- try {\n- unbind(name);\n- } catch (MalformedURLException | NotBoundException e) {\n- // ignore\n- }\n- }\n-\n- /**\n- * Exports the given Remote object, using the given socket factory and a randomly assigned port.\n- * \n- * NOTE: This helper function can also be used for regular RMI servers.\n- * \n- * @param obj The object to export.\n- * @param socketFactory The socket factory to use.\n- * @return The remote stub.\n- * @throws RemoteException if the operation fails.\n- */\n- public static Remote exportObject(Remote obj, RMISocketFactory socketFactory)\n- throws RemoteException {\n- return UnicastRemoteObject.exportObject(obj, 0, socketFactory, socketFactory);\n+ @Override\n+ protected void shutdownRegistryFinishingTouches() {\n+ deleteSocketDir();\n }\n \n /**\n- * Forcibly un-exports the given object, if it exists (otherwise returns without an error). This\n- * should be called upon closing a {@link Closeable} {@link Remote} object.\n- * \n- * NOTE: This helper function can also be used for regular RMI servers.\n+ * Returns the directory in which sockets used by this registry are located.\n * \n- * @param obj The object to un-export.\n+ * @return The directory.\n */\n- public static void unexportObject(Remote obj) {\n- try {\n- UnicastRemoteObject.unexportObject(obj, true);\n- } catch (NoSuchObjectException e) {\n- // ignore\n- }\n+ public File getRegistrySocketDir() {\n+ return registrySocketDir;\n }\n \n- private void setRegistry(AFUNIXRegistry registry) {\n- synchronized (AFUNIXNaming.class) {\n- this.registry = registry;\n- if (registry == null) {\n- rmiService = null;\n- } else if (registry.isLocal()) {\n- closeUponRuntimeShutdown();\n- }\n+ @Override\n+ protected void initRegistryPrerequisites() throws ServerException {\n+ if (registrySocketDir != null && !registrySocketDir.mkdirs() && !registrySocketDir\n+ .isDirectory()) {\n+ throw new ServerException(\"Cannot create socket directory:\" + registrySocketDir);\n }\n }\n }\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXNamingRef.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXNamingRef.java\ndeleted file mode 100644\nindex e7f1b4cdd..000000000\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXNamingRef.java\n+++ /dev/null\n@@ -1,95 +0,0 @@\n-/*\n- * junixsocket\n- *\n- * Copyright 2009-2021 Christian Kohlschütter\n- *\n- * Licensed under the Apache License, Version 2.0 (the \"License\");\n- * you may not use this file except in compliance with the License.\n- * You may obtain a copy of the License at\n- *\n- * http://www.apache.org/licenses/LICENSE-2.0\n- *\n- * Unless required by applicable law or agreed to in writing, software\n- * distributed under the License is distributed on an \"AS IS\" BASIS,\n- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- * See the License for the specific language governing permissions and\n- * limitations under the License.\n- */\n-package org.newsclub.net.unix.rmi;\n-\n-import java.io.File;\n-import java.io.IOException;\n-import java.rmi.RemoteException;\n-\n-/**\n- * A reference to a AFUNIXNaming instance.\n- * \n- * @author Christian Kohlschütter\n- */\n-final class AFUNIXNamingRef {\n- final File socketDir;\n- private final int port;\n- private final String socketPrefix;\n- private final String socketSuffix;\n-\n- AFUNIXNamingRef(File socketDir, int port, String socketPrefix, String socketSuffix)\n- throws RemoteException {\n- try {\n- this.socketDir = socketDir.getCanonicalFile();\n- } catch (IOException e) {\n- throw new RemoteException(e.getMessage(), e);\n- }\n- this.port = port;\n- this.socketPrefix = socketPrefix == null ? AFUNIXRMISocketFactory.DEFAULT_SOCKET_FILE_PREFIX\n- : socketPrefix;\n- this.socketSuffix = socketSuffix == null ? AFUNIXRMISocketFactory.DEFAULT_SOCKET_FILE_SUFFIX\n- : socketSuffix;\n- }\n-\n- @Override\n- public int hashCode() {\n- final int prime = 31;\n- int result = 1;\n- result = prime * result + port;\n- result = prime * result + ((socketDir == null) ? 0 : socketDir.hashCode());\n- result = prime * result + ((socketPrefix == null) ? 0 : socketPrefix.hashCode());\n- result = prime * result + ((socketSuffix == null) ? 0 : socketSuffix.hashCode());\n- return result;\n- }\n-\n- @Override\n- public boolean equals(Object obj) {\n- if (this == obj) {\n- return true;\n- }\n- if (!(obj instanceof AFUNIXNamingRef)) {\n- return false;\n- }\n- AFUNIXNamingRef other = (AFUNIXNamingRef) obj;\n- if (port != other.port) {\n- return false;\n- }\n- if (socketDir == null) {\n- if (other.socketDir != null) {\n- return false;\n- }\n- } else if (!socketDir.equals(other.socketDir)) {\n- return false;\n- }\n- if (socketPrefix == null) {\n- if (other.socketPrefix != null) {\n- return false;\n- }\n- } else if (!socketPrefix.equals(other.socketPrefix)) {\n- return false;\n- }\n- if (socketSuffix == null) {\n- if (other.socketSuffix != null) {\n- return false;\n- }\n- } else if (!socketSuffix.equals(other.socketSuffix)) {\n- return false;\n- }\n- return true;\n- }\n-}\n\\ No newline at end of file\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMISocketFactory.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMISocketFactory.java\nindex 3925fe3ed..4a96b8ed9 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMISocketFactory.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMISocketFactory.java\n@@ -17,28 +17,23 @@\n */\n package org.newsclub.net.unix.rmi;\n \n-import java.io.Closeable;\n-import java.io.Externalizable;\n import java.io.File;\n import java.io.IOException;\n import java.io.ObjectInput;\n import java.io.ObjectOutput;\n-import java.net.ServerSocket;\n-import java.net.Socket;\n-import java.rmi.NotBoundException;\n import java.rmi.server.RMIClientSocketFactory;\n import java.rmi.server.RMIServerSocketFactory;\n import java.rmi.server.RMISocketFactory;\n import java.util.HashMap;\n-import java.util.HashSet;\n import java.util.Map;\n-import java.util.Set;\n+import java.util.Objects;\n \n-import org.newsclub.net.unix.AFUNIXServerSocket;\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.AFSocketAddress;\n import org.newsclub.net.unix.AFUNIXSocket;\n import org.newsclub.net.unix.AFUNIXSocketAddress;\n import org.newsclub.net.unix.AFUNIXSocketCredentials;\n-import org.newsclub.net.unix.rmi.ShutdownHookSupport.ShutdownHook;\n+import org.newsclub.net.unix.HostAndPort;\n \n import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n@@ -47,26 +42,17 @@ import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n * \n * @author Christian Kohlschütter\n */\n-public class AFUNIXRMISocketFactory extends RMISocketFactory implements Externalizable, Closeable {\n- static final String DEFAULT_SOCKET_FILE_PREFIX = \"\";\n- static final String DEFAULT_SOCKET_FILE_SUFFIX = \".rmi\";\n-\n+public class AFUNIXRMISocketFactory extends AFRMISocketFactory {\n private static final long serialVersionUID = 1L;\n \n- private RMIClientSocketFactory defaultClientFactory;\n- private RMIServerSocketFactory defaultServerFactory;\n+ static final String DEFAULT_SOCKET_FILE_PREFIX = \"\";\n+ static final String DEFAULT_SOCKET_FILE_SUFFIX = \".rmi\";\n \n private File socketDir;\n- private AFUNIXNaming naming;\n-\n private String socketPrefix;\n private String socketSuffix;\n \n- private AFUNIXRMIService rmiService = null;\n-\n private final Map credentials = new HashMap<>();\n- private final Map openServerSockets = new HashMap<>();\n- private final Set openSockets = new HashSet<>();\n \n /**\n * Constructor required per definition.\n@@ -75,83 +61,87 @@ public class AFUNIXRMISocketFactory extends RMISocketFactory implements External\n */\n public AFUNIXRMISocketFactory() {\n super();\n- closeUponRuntimeShutdown();\n }\n \n /**\n * Creates a new socket factory.\n * \n- * @param naming The {@link AFUNIXNaming} instance to use.\n+ * @param naming The {@link AFNaming} instance to use.\n * @param socketDir The directory to store the sockets in.\n+ * @param defaultClientFactory The default {@link RMIClientSocketFactory}.\n+ * @param defaultServerFactory The default {@link RMIServerSocketFactory}.\n+ * @param socketPrefix A string that will be inserted at the beginning of each socket filename, or\n+ * {@code null}.\n+ * @param socketSuffix A string that will be added to the end of each socket filename, or\n+ * {@code null}.\n * @throws IOException on error.\n */\n- public AFUNIXRMISocketFactory(final AFUNIXNaming naming, final File socketDir)\n- throws IOException {\n- this(naming, socketDir, DefaultRMIClientSocketFactory.getInstance(),\n- DefaultRMIServerSocketFactory.getInstance());\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP2\")\n+ public AFUNIXRMISocketFactory(final AFNaming naming, final File socketDir,\n+ final RMIClientSocketFactory defaultClientFactory,\n+ final RMIServerSocketFactory defaultServerFactory, final String socketPrefix,\n+ final String socketSuffix) throws IOException {\n+ super(naming, defaultClientFactory, defaultServerFactory);\n+ Objects.requireNonNull(socketDir);\n+ this.socketDir = socketDir;\n+ this.socketPrefix = socketPrefix == null ? DEFAULT_SOCKET_FILE_PREFIX : socketPrefix;\n+ this.socketSuffix = socketSuffix == null ? DEFAULT_SOCKET_FILE_SUFFIX : socketSuffix;\n }\n \n /**\n * Creates a new socket factory.\n * \n- * @param naming The {@link AFUNIXNaming} instance to use.\n+ * @param naming The {@link AFNaming} instance to use.\n * @param socketDir The directory to store the sockets in.\n * @param defaultClientFactory The default {@link RMIClientSocketFactory}.\n * @param defaultServerFactory The default {@link RMIServerSocketFactory}.\n * @throws IOException on error.\n */\n- public AFUNIXRMISocketFactory(final AFUNIXNaming naming, final File socketDir,\n- final RMIClientSocketFactory defaultClientFactory,\n- final RMIServerSocketFactory defaultServerFactory) throws IOException {\n+ public AFUNIXRMISocketFactory(AFNaming naming, File socketDir,\n+ RMIClientSocketFactory defaultClientFactory, RMIServerSocketFactory defaultServerFactory)\n+ throws IOException {\n this(naming, socketDir, defaultClientFactory, defaultServerFactory, null, null);\n }\n \n /**\n * Creates a new socket factory.\n * \n- * @param naming The {@link AFUNIXNaming} instance to use.\n+ * @param naming The {@link AFNaming} instance to use.\n * @param socketDir The directory to store the sockets in.\n- * @param defaultClientFactory The default {@link RMIClientSocketFactory}.\n- * @param defaultServerFactory The default {@link RMIServerSocketFactory}.\n- * @param socketPrefix A string that will be inserted at the beginning of each socket filename, or\n- * {@code null}.\n- * @param socketSuffix A string that will be added to the end of each socket filename, or\n- * {@code null}.\n * @throws IOException on error.\n */\n- @SuppressFBWarnings(\"EI_EXPOSE_REP2\")\n- public AFUNIXRMISocketFactory(final AFUNIXNaming naming, final File socketDir,\n- final RMIClientSocketFactory defaultClientFactory,\n- final RMIServerSocketFactory defaultServerFactory, final String socketPrefix,\n- final String socketSuffix) throws IOException {\n- super();\n- this.naming = naming;\n- this.socketDir = socketDir;\n- this.defaultClientFactory = defaultClientFactory;\n- this.defaultServerFactory = defaultServerFactory;\n- this.socketPrefix = socketPrefix == null ? DEFAULT_SOCKET_FILE_PREFIX : socketPrefix;\n- this.socketSuffix = socketSuffix == null ? DEFAULT_SOCKET_FILE_SUFFIX : socketSuffix;\n+ public AFUNIXRMISocketFactory(AFNaming naming, File socketDir) throws IOException {\n+ this(naming, socketDir, DefaultRMIClientSocketFactory.getInstance(),\n+ DefaultRMIServerSocketFactory.getInstance());\n+ }\n+\n+ @Override\n+ protected AFNaming readNamingInstance(ObjectInput in) throws IOException {\n+ socketDir = new File(in.readUTF());\n+ int port = in.readInt();\n+ return AFUNIXNaming.getInstance(socketDir, port);\n+ }\n \n- closeUponRuntimeShutdown();\n+ @Override\n+ protected void writeNamingInstance(ObjectOutput out, AFNaming naming) throws IOException {\n+ out.writeUTF(socketDir.getAbsolutePath());\n+ out.writeInt(naming.getRegistryPort());\n }\n \n- private boolean isPlainFileSocket() {\n- return (naming.getRegistryPort() == AFUNIXRMIPorts.PLAIN_FILE_SOCKET);\n+ @Override\n+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {\n+ super.readExternal(in);\n+\n+ socketPrefix = in.readUTF();\n+ socketSuffix = in.readUTF();\n }\n \n- // only to be called from the constructor\n- private void closeUponRuntimeShutdown() {\n- ShutdownHookSupport.addWeakShutdownHook(new ShutdownHook() {\n+ @Override\n+ public void writeExternal(ObjectOutput out) throws IOException {\n+ super.writeExternal(out);\n \n- @Override\n- public void onRuntimeShutdown(Thread thread) {\n- try {\n- close();\n- } catch (IOException e) {\n- // ignore\n- }\n- }\n- });\n+ out.writeUTF(socketPrefix);\n+ out.writeUTF(socketSuffix);\n }\n \n @Override\n@@ -165,45 +155,11 @@ public class AFUNIXRMISocketFactory extends RMISocketFactory implements External\n return false;\n }\n AFUNIXRMISocketFactory sf = (AFUNIXRMISocketFactory) other;\n- return sf.socketDir.equals(socketDir);\n- }\n-\n- @Override\n- public Socket createSocket(String host, int port) throws IOException {\n- final RMIClientSocketFactory cf = defaultClientFactory;\n- if (cf != null && port < AFUNIXRMIPorts.AF_PORT_BASE) {\n- return cf.createSocket(host, port);\n- }\n-\n- final AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(getFile(port), port);\n-\n- final AFUNIXSocket socket = AFUNIXSocket.newInstance();\n- socket.connect(addr);\n- AFUNIXSocketCredentials creds = socket.getPeerCredentials();\n-\n- final HostAndPort hap = new HostAndPort(host, port);\n- synchronized (credentials) {\n- if (credentials.put(hap, creds) != null) {\n- // unexpected\n- }\n- }\n-\n- synchronized (openSockets) {\n- openSockets.add(socket);\n+ if (socketDir == null) {\n+ return sf == this;\n+ } else {\n+ return socketDir.equals(sf.socketDir);\n }\n- socket.addCloseable(new Closeable() {\n- @Override\n- public void close() throws IOException {\n- synchronized (openSockets) {\n- openSockets.remove(socket);\n- }\n-\n- synchronized (credentials) {\n- credentials.remove(hap);\n- }\n- }\n- });\n- return socket;\n }\n \n /**\n@@ -219,6 +175,7 @@ public class AFUNIXRMISocketFactory extends RMISocketFactory implements External\n if (isPlainFileSocket()) {\n return getSocketDir();\n } else {\n+ Objects.requireNonNull(socketDir);\n return new File(socketDir, socketPrefix + port + socketSuffix);\n }\n }\n@@ -227,181 +184,32 @@ public class AFUNIXRMISocketFactory extends RMISocketFactory implements External\n return getFile(port).exists();\n }\n \n- @Override\n- public void close() throws IOException {\n- synchronized (AFUNIXNaming.class) {\n- credentials.clear();\n-\n- rmiService = null;\n- closeServerSockets();\n- closeSockets();\n- }\n- }\n-\n- private AFUNIXRMIService getRmiService() throws IOException {\n- synchronized (AFUNIXNaming.class) {\n- if (rmiService == null) {\n- try {\n- rmiService = naming.getRMIService();\n- } catch (NotBoundException e) {\n- throw (IOException) new IOException(e.getMessage()).initCause(e);\n- }\n- }\n- return rmiService;\n- }\n- }\n-\n- /**\n- * Returns a new free port.\n- * \n- * @return The new port.\n- * @throws IOException on error.\n- * @see #returnPort(int)\n- */\n- protected int newPort() throws IOException {\n- return getRmiService().newPort();\n- }\n-\n- /**\n- * Returns a port that was previously returned by {@link #newPort()}.\n- * \n- * @param port The port to return.\n- * @throws IOException on error.\n- */\n- protected void returnPort(int port) throws IOException {\n- getRmiService().returnPort(port);\n+ private boolean isPlainFileSocket() {\n+ return (getNaming().getRegistryPort() == RMIPorts.PLAIN_FILE_SOCKET);\n }\n \n @Override\n- public ServerSocket createServerSocket(int port) throws IOException {\n- if (port == 0) {\n- port = newPort();\n- final AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(getFile(port), port);\n- final AnonymousServerSocket ass = new AnonymousServerSocket(port);\n- ass.setDeleteOnClose(true);\n- ass.bind(addr);\n-\n- if (port >= AFUNIXRMIPorts.AF_PORT_BASE) {\n- ass.addCloseable(new ServerSocketCloseable(ass, port));\n- }\n- return ass;\n- }\n-\n- final RMIServerSocketFactory sf = defaultServerFactory;\n- if (sf != null && port < AFUNIXRMIPorts.AF_PORT_BASE) {\n- return sf.createServerSocket(port);\n- }\n-\n- final AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(getFile(port), port);\n- AFUNIXServerSocket socket = AFUNIXServerSocket.newInstance();\n- socket.setDeleteOnClose(true);\n- socket.setReuseAddress(true);\n- socket.bind(addr);\n- socket.addCloseable(new ServerSocketCloseable(socket, port));\n- return socket;\n+ protected AFUNIXSocketAddress newSocketAddress(int port) throws IOException {\n+ return AFUNIXSocketAddress.of(getFile(port), port);\n }\n \n- private void closeServerSockets() throws IOException {\n- Map map;\n- synchronized (openServerSockets) {\n- map = new HashMap<>(openServerSockets);\n- }\n- IOException ex = null;\n- for (Map.Entry en : map.entrySet()) {\n- try {\n- en.getValue().close();\n- } catch (ShutdownException e) {\n- // ignore\n- } catch (IOException e) {\n- if (ex == null) {\n- ex = e;\n- } else {\n- ex.addSuppressed(e);\n- }\n- }\n- }\n- synchronized (openServerSockets) {\n- openServerSockets.clear();\n- }\n- if (ex != null) {\n- throw ex;\n- }\n- }\n-\n- private void closeSockets() {\n- Set set;\n- synchronized (openSockets) {\n- set = new HashSet<>(openSockets);\n- }\n- for (AFUNIXSocket socket : set) {\n- try {\n- socket.close();\n- } catch (IOException e) {\n- // ignore\n- }\n- }\n- synchronized (openSockets) {\n- openSockets.clear();\n- }\n- }\n-\n- private final class ServerSocketCloseable implements Closeable {\n- private final int port;\n+ @Override\n+ protected final AFSocket newConnectedSocket(AFSocketAddress addr) throws IOException {\n+ final AFUNIXSocket socket = ((AFUNIXSocketAddress) addr).newConnectedSocket();\n+ AFUNIXSocketCredentials creds = socket.getPeerCredentials();\n \n- ServerSocketCloseable(AFUNIXServerSocket socket, int port) {\n- this.port = port;\n- synchronized (openServerSockets) {\n- openServerSockets.put(port, socket);\n+ final HostAndPort hap = new HostAndPort(addr.getHostString(), addr.getPort());\n+ synchronized (credentials) {\n+ if (credentials.put(hap, creds) != null) {\n+ // unexpected\n }\n }\n-\n- @Override\n- public void close() throws IOException {\n- synchronized (openServerSockets) {\n- openServerSockets.remove(port);\n+ socket.addCloseable(() -> {\n+ synchronized (credentials) {\n+ credentials.remove(hap);\n }\n- }\n- }\n-\n- @Override\n- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {\n- socketDir = new File(in.readUTF());\n- int port = in.readInt();\n- naming = AFUNIXNaming.getInstance(socketDir, port);\n-\n- defaultClientFactory = (RMIClientSocketFactory) in.readObject();\n- defaultServerFactory = (RMIServerSocketFactory) in.readObject();\n-\n- socketPrefix = in.readUTF();\n- socketSuffix = in.readUTF();\n- }\n-\n- @Override\n- public void writeExternal(ObjectOutput out) throws IOException {\n- out.writeUTF(socketDir.getAbsolutePath());\n- out.writeInt(naming.getRegistryPort());\n-\n- out.writeObject(defaultClientFactory);\n- out.writeObject(defaultServerFactory);\n-\n- out.writeUTF(socketPrefix);\n- out.writeUTF(socketSuffix);\n- }\n-\n- private final class AnonymousServerSocket extends AFUNIXServerSocket {\n- private final int returnPort;\n-\n- protected AnonymousServerSocket(int returnPort) throws IOException {\n- super();\n- this.returnPort = returnPort;\n- setReuseAddress(true);\n- }\n-\n- @Override\n- public void close() throws IOException {\n- super.close();\n- returnPort(returnPort);\n- }\n+ });\n+ return socket;\n }\n \n @Override\n@@ -412,63 +220,20 @@ public class AFUNIXRMISocketFactory extends RMISocketFactory implements External\n \";prefix=\" + socketPrefix + \";suffix=\" + socketSuffix) + \"]\";\n }\n \n+ @Override\n+ public void close() throws IOException {\n+ credentials.clear();\n+ super.close();\n+ }\n+\n AFUNIXSocketCredentials peerCredentialsFor(RemotePeerInfo data) {\n synchronized (credentials) {\n return credentials.get(new HostAndPort(data.host, data.port));\n }\n }\n \n- private static final class HostAndPort {\n- final String hostname;\n- final int port;\n-\n- HostAndPort(String hostname, int port) {\n- this.hostname = hostname;\n- this.port = port;\n- }\n-\n- @Override\n- public int hashCode() {\n- final int prime = 31;\n- int result = 1;\n- result = prime * result + ((hostname == null) ? 0 : hostname.hashCode());\n- result = prime * result + port;\n- return result;\n- }\n-\n- @Override\n- public boolean equals(Object obj) {\n- if (this == obj) {\n- return true;\n- }\n- if (!(obj instanceof HostAndPort)) {\n- return false;\n- }\n- HostAndPort other = (HostAndPort) obj;\n- if (hostname == null) {\n- if (other.hostname != null) {\n- return false;\n- }\n- } else if (!hostname.equals(other.hostname)) {\n- return false;\n- }\n-\n- return port == other.port;\n- }\n- }\n-\n- /**\n- * Checks if the given port refers to a local server port.\n- * \n- * @param port The port to check.\n- * @return {@code true} if the given port is a local server.\n- */\n- public boolean isLocalServer(int port) {\n- if (port < AFUNIXRMIPorts.AF_PORT_BASE) {\n- return false;\n- }\n- synchronized (openServerSockets) {\n- return openServerSockets.containsKey(port);\n- }\n+ @Override\n+ boolean hasRegisteredPort(int port) {\n+ return hasSocketFile(port);\n }\n }\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRegistry.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRegistry.java\nindex 3d1c33aa9..a36675590 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRegistry.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRegistry.java\n@@ -17,259 +17,19 @@\n */\n package org.newsclub.net.unix.rmi;\n \n-import java.io.IOException;\n-import java.rmi.AccessException;\n-import java.rmi.AlreadyBoundException;\n-import java.rmi.ConnectIOException;\n-import java.rmi.NoSuchObjectException;\n-import java.rmi.NotBoundException;\n-import java.rmi.Remote;\n import java.rmi.RemoteException;\n import java.rmi.registry.Registry;\n-import java.rmi.server.RemoteObject;\n-import java.rmi.server.RemoteServer;\n-import java.util.HashMap;\n-import java.util.Map;\n-import java.util.concurrent.TimeUnit;\n-\n-import org.newsclub.net.unix.rmi.ShutdownHookSupport.ShutdownHook;\n-\n-import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n /**\n * A wrapper for RMI registries, both remote and local, to allow for a clean removal of bound\n * resources upon shutdown.\n * \n+ * This subclass mostly exists for backwards compatibility.\n+ * \n * @author Christian Kohlschütter\n */\n-public final class AFUNIXRegistry implements Registry {\n- final RemoteCloseable boundCloser;\n-\n- private final Registry impl;\n- private final Map bound = new HashMap<>();\n- private final AFUNIXNaming naming;\n- private boolean boundCloserExported = false;\n-\n- AFUNIXRegistry(AFUNIXNaming naming, Registry impl) throws RemoteException {\n- this.naming = naming;\n- this.impl = impl;\n- this.boundCloser = new RemoteCloseable() {\n- @Override\n- public Void get() throws IOException {\n- return null;\n- }\n-\n- @Override\n- public void close() throws IOException {\n- AFUNIXRegistry.this.forceUnexportBound();\n- }\n- };\n-\n- if (isLocal()) {\n- ShutdownHookSupport.addWeakShutdownHook(new ShutdownHook() {\n- @Override\n- public void onRuntimeShutdown(Thread thread) {\n- forceUnexportBound();\n- }\n- });\n- }\n- }\n-\n- /**\n- * Returns {@code true} if the wrapped Registry instance is a locally created\n- * {@link RemoteServer}.\n- * \n- * @return {@code true} if wrapped instance is a locally created {@link RemoteServer}.\n- * @see #isLocal()\n- */\n- @Deprecated\n- public boolean isRemoteServer() {\n- return isLocal();\n- }\n-\n- /**\n- * Returns {@code true} if the wrapped Registry instance is locally created.\n- * \n- * @return {@code true} if wrapped instance is locally created.\n- */\n- public boolean isLocal() {\n- return (impl instanceof RemoteServer);\n- }\n-\n- /**\n- * Returns the {@link AFUNIXNaming} instance responsible for this registry.\n- * \n- * @return The {@link AFUNIXNaming} instance.\n- */\n- @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n- public AFUNIXNaming getNaming() {\n- return naming;\n- }\n-\n- @Override\n- public Remote lookup(String name) throws RemoteException, NotBoundException, AccessException {\n- return impl.lookup(name);\n- }\n-\n- @Override\n- public void bind(String name, Remote obj) throws RemoteException, AlreadyBoundException,\n- AccessException {\n- impl.bind(name, RemoteObject.toStub(obj));\n- synchronized (bound) {\n- bound.put(name, obj);\n- }\n- checkBound();\n- }\n-\n- @Override\n- public void unbind(String name) throws RemoteException, NotBoundException, AccessException {\n- impl.unbind(name);\n- synchronized (bound) {\n- bound.remove(name);\n- }\n- checkBound();\n- }\n-\n- @Override\n- public void rebind(String name, Remote obj) throws RemoteException, AccessException {\n- impl.rebind(name, RemoteObject.toStub(obj));\n- synchronized (bound) {\n- bound.put(name, obj);\n- }\n- checkBound();\n- }\n-\n- @Override\n- public String[] list() throws RemoteException, AccessException {\n- return impl == null ? new String[0] : impl.list();\n- }\n-\n- /**\n- * Returns the remote reference bound to the specified name in this registry. If the\n- * reference has not been bound yet, repeated attempts to resolve it are made until the specified\n- * time elapses.\n- *\n- * @param name the name for the remote reference to look up\n- * @param timeout The timeout value.\n- * @param unit The timeout unit.\n- *\n- * @return a reference to a remote object\n- *\n- * @throws NotBoundException if name is not currently bound and couldn't be resolved\n- * in the specified time.\n- *\n- * @throws RemoteException if remote communication with the registry failed; if exception is a\n- * ServerException containing an AccessException, then the\n- * registry denies the caller access to perform this operation\n- *\n- * @throws AccessException if this registry is local and it denies the caller access to perform\n- * this operation\n- *\n- * @throws NullPointerException if name is null\n- */\n- public Remote lookup(String name, long timeout, TimeUnit unit) throws NotBoundException,\n- RemoteException {\n- long timeWait = unit.toMillis(timeout);\n-\n- Exception exFirst = null;\n- do {\n- try {\n- return impl.lookup(name);\n- } catch (NotBoundException | ConnectIOException | NoSuchObjectException e) {\n- if (exFirst == null) {\n- exFirst = e;\n- }\n- }\n-\n- try {\n- Thread.sleep(Math.min(timeWait, 50));\n- } catch (InterruptedException e1) {\n- exFirst.addSuppressed(e1);\n- break;\n- }\n- timeWait -= 50;\n- } while (timeWait > 0);\n-\n- if (exFirst instanceof NotBoundException) {\n- throw (NotBoundException) exFirst;\n- } else if (exFirst instanceof RemoteException) {\n- throw (RemoteException) exFirst;\n- } else {\n- throw new RemoteException(\"Lookup timed out\");\n- }\n- }\n-\n- void forceUnexportBound() {\n- final Map map;\n- synchronized (bound) {\n- map = new HashMap<>(bound);\n- bound.clear();\n- }\n- try {\n- checkBound();\n- } catch (RemoteException e1) {\n- // ignore\n- }\n- for (Map.Entry en : map.entrySet()) {\n- String name = en.getKey();\n- Remote obj = en.getValue();\n- if (obj == null) {\n- continue;\n- }\n- AFUNIXNaming.unexportObject(obj);\n- try {\n- unbind(name);\n- } catch (RemoteException | NotBoundException e) {\n- // ignore\n- }\n-\n- }\n- try {\n- for (String list : list()) {\n- try {\n- unbind(list);\n- } catch (RemoteException | NotBoundException e) {\n- // ignore\n- }\n- }\n- } catch (RemoteException e) {\n- // ignore\n- }\n-\n- AFUNIXNaming.unexportObject(this.impl);\n- AFUNIXNaming.unexportObject(this);\n- }\n-\n- private void checkBound() throws RemoteException {\n- boolean empty;\n- synchronized (bound) {\n- empty = bound.isEmpty();\n- }\n- if (empty) {\n- if (boundCloserExported) {\n- boundCloserExported = false;\n-\n- AFUNIXRMIService service;\n- try {\n- service = naming.getRMIService(this);\n- service.unregisterForShutdown(boundCloser);\n- } catch (NoSuchObjectException | NotBoundException e) {\n- return;\n- } finally {\n- AFUNIXNaming.unexportObject(boundCloser);\n- }\n- }\n- } else if (!boundCloserExported) {\n- AFUNIXNaming.exportObject(boundCloser, naming.getSocketFactory());\n- boundCloserExported = true;\n-\n- AFUNIXRMIService service;\n- try {\n- service = naming.getRMIService(this);\n- } catch (NotBoundException e) {\n- return;\n- }\n- service.registerForShutdown(boundCloser);\n- }\n+public class AFUNIXRegistry extends AFRegistry {\n+ AFUNIXRegistry(AFNaming naming, Registry impl) throws RemoteException {\n+ super(naming, impl);\n }\n }\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/DefaultRMIClientSocketFactory.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/DefaultRMIClientSocketFactory.java\nindex a0d595e74..39bc5c364 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/DefaultRMIClientSocketFactory.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/DefaultRMIClientSocketFactory.java\n@@ -22,15 +22,20 @@ import java.io.Serializable;\n import java.net.Socket;\n import java.rmi.server.RMIClientSocketFactory;\n \n+import org.newsclub.net.unix.AFSocket;\n+\n /**\n * An implementation of {@link RMIClientSocketFactory}.\n * \n- * * @see AFUNIXRMISocketFactory where we deal with AF_UNIX sockets.\n+ * @see AFRMISocketFactory where we deal with {@link AFSocket}s.\n */\n public final class DefaultRMIClientSocketFactory implements RMIClientSocketFactory, Serializable {\n private static final long serialVersionUID = 1L;\n private static final DefaultRMIClientSocketFactory INSTANCE = new DefaultRMIClientSocketFactory();\n \n+ private DefaultRMIClientSocketFactory() {\n+ }\n+\n /**\n * Returns the singleton instance for DefaultRMIClientSocketFactory.\n * \ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/DefaultRMIServerSocketFactory.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/DefaultRMIServerSocketFactory.java\nindex 9f7b5a331..8083890c3 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/DefaultRMIServerSocketFactory.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/DefaultRMIServerSocketFactory.java\n@@ -22,15 +22,24 @@ import java.io.Serializable;\n import java.net.ServerSocket;\n import java.rmi.server.RMIServerSocketFactory;\n \n+import org.newsclub.net.unix.AFSocket;\n+\n /**\n * An implementation of {@link RMIServerSocketFactory}.\n * \n- * @see AFUNIXRMISocketFactory where we deal with AF_UNIX sockets.\n+ * @see AFRMISocketFactory where we deal with {@link AFSocket}.\n */\n public class DefaultRMIServerSocketFactory implements RMIServerSocketFactory, Serializable {\n private static final long serialVersionUID = 1L;\n private static final DefaultRMIServerSocketFactory INSTANCE = new DefaultRMIServerSocketFactory();\n \n+ /**\n+ * Creates a new {@link DefaultRMIClientSocketFactory}.\n+ */\n+ public DefaultRMIServerSocketFactory() {\n+ super();\n+ }\n+\n /**\n * Returns the singleton instance for DefaultRMIServerSocketFactory.\n * \ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMIPorts.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RMIPorts.java\nsimilarity index 69%\nrename from junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMIPorts.java\nrename to junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RMIPorts.java\nindex d5c34ccae..534e0d470 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/AFUNIXRMIPorts.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RMIPorts.java\n@@ -17,49 +17,51 @@\n */\n package org.newsclub.net.unix.rmi;\n \n+import org.newsclub.net.unix.AFSocket;\n+\n import com.kohlschutter.annotations.compiletime.ExcludeFromCodeCoverageGeneratedReport;\n \n /**\n- * Contains some default ports used by junixsocket for RMI-over-AFUNIX.\n+ * Contains some default ports used by junixsocket for RMI-over-AF_UNIX etc.\n * \n * @author Christian Kohlschütter\n- * @see AFUNIXRMISocketFactory\n- * @see AFUNIXRMIService\n+ * @see AFRMISocketFactory\n+ * @see AFRMIService\n */\n-final class AFUNIXRMIPorts {\n+final class RMIPorts {\n /**\n- * This is the base for AF_UNIX-related ports To distinguish between TCP/UDP ports and AFUNIX\n- * ports, we use numbers > 65535.\n+ * This is the base for non-inet {@link AFSocket}-related ports To distinguish between TCP/UDP\n+ * ports and these ports, we use numbers > 65535.\n */\n- public static final int AF_PORT_BASE = 100000;\n+ static final int AF_PORT_BASE = 100000;\n \n /**\n * This is the port reserved for the default registry.\n */\n- public static final int DEFAULT_REGISTRY_PORT = 100001;\n+ static final int DEFAULT_REGISTRY_PORT = 100001;\n \n /**\n * This is the port reserved for the port assigner.\n * \n- * @see AFUNIXRMIService\n+ * @see AFRMIService\n */\n- public static final int RMI_SERVICE_PORT = 100002;\n+ static final int RMI_SERVICE_PORT = 100002;\n \n /**\n * This is the base for anonymous ports. Any anonymous port will be higher than this number.\n * \n- * @see AFUNIXRMIService\n+ * @see AFRMIService\n */\n- public static final int ANONYMOUS_PORT_BASE = 110000;\n+ static final int ANONYMOUS_PORT_BASE = 110000;\n \n /**\n- * This port is used to state that the socket path specified in {@link AFUNIXRMISocketFactory}\n- * points to a socket file, not a directory.\n+ * This port is used to state that the socket path specified in {@link AFRMISocketFactory} points\n+ * to a socket file, not a directory.\n */\n static final int PLAIN_FILE_SOCKET = Integer.MAX_VALUE;\n \n @ExcludeFromCodeCoverageGeneratedReport\n- private AFUNIXRMIPorts() {\n+ private RMIPorts() {\n throw new UnsupportedOperationException(\"No instances\");\n }\n }\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemoteCloseableImpl.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemoteCloseableImpl.java\nindex 17bf54c64..a3eede2d7 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemoteCloseableImpl.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemoteCloseableImpl.java\n@@ -40,12 +40,12 @@ public class RemoteCloseableImpl implements RemoteCloseable {\n */\n public RemoteCloseableImpl(RMISocketFactory socketFactory, T obj) throws RemoteException {\n this.remote = obj;\n- AFUNIXNaming.exportObject(this, socketFactory);\n+ AFNaming.exportObject(this, socketFactory);\n }\n \n @Override\n public final void close() throws IOException {\n- AFUNIXNaming.unexportObject(this);\n+ AFNaming.unexportObject(this);\n doClose(remote);\n }\n \ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemoteFileDescriptorBase.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemoteFileDescriptorBase.java\nindex d8ae2bc8e..c0fba56d2 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemoteFileDescriptorBase.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemoteFileDescriptorBase.java\n@@ -29,17 +29,18 @@ import java.io.InputStream;\n import java.io.ObjectInput;\n import java.io.ObjectOutput;\n import java.io.OutputStream;\n-import java.net.Socket;\n import java.net.SocketException;\n import java.util.Objects;\n import java.util.concurrent.ThreadLocalRandom;\n import java.util.concurrent.TimeUnit;\n import java.util.concurrent.atomic.AtomicReference;\n \n-import org.newsclub.net.unix.AFUNIXServerSocket;\n+import org.newsclub.net.unix.AFServerSocket;\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.AFSocketAddress;\n import org.newsclub.net.unix.AFUNIXSocket;\n import org.newsclub.net.unix.FileDescriptorAccess;\n-import org.newsclub.net.unix.server.AFUNIXSocketServer;\n+import org.newsclub.net.unix.server.AFSocketServer;\n \n import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n \n@@ -89,7 +90,7 @@ public abstract class RemoteFileDescriptorBase implements Externalizable, Clo\n * \n * @see #readExternal(ObjectInput)\n */\n- protected RemoteFileDescriptorBase() {\n+ RemoteFileDescriptorBase() {\n }\n \n RemoteFileDescriptorBase(AFUNIXRMISocketFactory socketFactory, T stream, FileDescriptor fd,\n@@ -110,12 +111,12 @@ public abstract class RemoteFileDescriptorBase implements Externalizable, Clo\n \n int localPort;\n try {\n- AFUNIXServerSocket serverSocket = (AFUNIXServerSocket) socketFactory.createServerSocket(0);\n+ AFServerSocket serverSocket = (AFServerSocket) socketFactory.createServerSocket(0);\n localPort = serverSocket.getLocalPort();\n \n- AFUNIXSocketServer server = new AFUNIXSocketServer(serverSocket) {\n+ AFSocketServer server = new AFSocketServer(serverSocket) {\n @Override\n- protected void doServeSocket(Socket socket) throws IOException {\n+ protected void doServeSocket(AFSocket socket) throws IOException {\n AFUNIXSocket unixSocket = (AFUNIXSocket) socket;\n try (DataOutputStream out = new DataOutputStream(socket.getOutputStream());\n InputStream in = socket.getInputStream();) {\n@@ -143,13 +144,14 @@ public abstract class RemoteFileDescriptorBase implements Externalizable, Clo\n }\n \n @Override\n- protected void onServerStopped(java.net.ServerSocket socket) {\n+ protected void onServerStopped(AFServerSocket socket) {\n try {\n serverSocket.close();\n } catch (IOException e) {\n // ignore\n }\n }\n+\n };\n server.startThenStopAfter(SERVER_TIMEOUT, TimeUnit.MILLISECONDS);\n } catch (IOException e) {\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemotePeerInfo.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemotePeerInfo.java\nindex 1b7f75520..92279f84e 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemotePeerInfo.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/RemotePeerInfo.java\n@@ -134,6 +134,8 @@ public final class RemotePeerInfo {\n data.peerCredentials = AFUNIXSocketCredentials.SAME_PROCESS;\n }\n }\n+ } else {\n+ data.peerCredentials = null;\n }\n \n return data;\ndiff --git a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/ShutdownHookSupport.java b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/ShutdownHookSupport.java\nindex 36bb18d49..a4fb5e70d 100644\n--- a/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/ShutdownHookSupport.java\n+++ b/junixsocket-rmi/src/main/java/org/newsclub/net/unix/rmi/ShutdownHookSupport.java\n@@ -84,6 +84,7 @@ final class ShutdownHookSupport {\n * @param thread The current Thread.\n * @throws Exception Most likely ignored\n */\n+ @SuppressFBWarnings(\"THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION\")\n void onRuntimeShutdown(Thread thread) throws Exception;\n }\n \ndiff --git a/junixsocket-selftest/pom.xml b/junixsocket-selftest/pom.xml\nindex 31188bc06..fdbcb0e26 100644\n--- a/junixsocket-selftest/pom.xml\n+++ b/junixsocket-selftest/pom.xml\n@@ -6,7 +6,7 @@\n \n com.kohlschutter.junixsocket\n junixsocket-parent\n- 2.4.1-SNAPSHOT\n+ 2.5.0-SNAPSHOT\n ../pom.xml\n \n junixsocket-selftest\n@@ -49,6 +49,18 @@\n \n \n \n+ \n+ add-sources-from-junixsocket-tipc\n+ generate-sources\n+ \n+ add-source\n+ \n+ \n+ \n+ ${project.parent.basedir}/junixsocket-tipc/src/test/java\n+ \n+ \n+ \n \n add-sources-from-junixsocket-rmi\n generate-sources\n@@ -104,6 +116,18 @@\n **\n \n \n+ \n+ ${project.parent.basedir}/junixsocket-common/src/main/java\n+ \n+ **\n+ \n+ \n+ \n+ ${project.parent.basedir}/junixsocket-common/src/main/java8\n+ \n+ **\n+ \n+ \n \n ${project.parent.basedir}/junixsocket-common/src/test/java\n \n@@ -116,6 +140,18 @@\n **\n \n \n+ \n+ ${project.parent.basedir}/junixsocket-tipc/src/test/java\n+ \n+ **\n+ \n+ \n+ \n+ ${project.parent.basedir}/junixsocket-tipc/src/test/java8\n+ \n+ **\n+ \n+ \n \n ${project.parent.basedir}/junixsocket-rmi/src/test/java\n \n@@ -206,6 +242,16 @@\n \n \n \n+\n+ \n+ \n+ \n+ org.codehaus.mojo\n+ build-helper-maven-plugin\n+ 3.3.0\n+ \n+ \n+ \n \n \n \n@@ -234,16 +280,30 @@\n ${project.version}\n default\n \n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-tipc\n+ ${project.version}\n+ \n \n com.kohlschutter.junixsocket\n junixsocket-rmi\n ${project.version}\n \n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-server\n+ ${project.version}\n+ \n \n \n com.kohlschutter\n kohlschutter-test-util\n \n+ \n+ com.kohlschutter\n+ kohlschutter-util\n+ \n \n \n org.junit.platform\ndiff --git a/junixsocket-selftest/src/main/java-overlay/org/newsclub/net/unix/selftest/SelftestProvider.java b/junixsocket-selftest/src/main/java-overlay/org/newsclub/net/unix/selftest/SelftestProvider.java\nindex eb18af731..d64a75615 100644\n--- a/junixsocket-selftest/src/main/java-overlay/org/newsclub/net/unix/selftest/SelftestProvider.java\n+++ b/junixsocket-selftest/src/main/java-overlay/org/newsclub/net/unix/selftest/SelftestProvider.java\n@@ -1,7 +1,10 @@\n package org.newsclub.net.unix.selftest;\n \n+import java.util.Collections;\n import java.util.LinkedHashMap;\n import java.util.Map;\n+import java.util.Set;\n+import java.util.HashSet;\n \n /**\n * Provides references to all tests that should be included in junixsocket-selftest.\n@@ -9,11 +12,27 @@ import java.util.Map;\n * @author Christian Kohlschütter\n */\n public class SelftestProvider {\n+ private final org.newsclub.net.unix.SelftestProvider commonSelftests =\n+ new org.newsclub.net.unix.SelftestProvider();\n+ private final org.newsclub.net.unix.tipc.SelftestProvider tipcSelftests =\n+ new org.newsclub.net.unix.tipc.SelftestProvider();\n+ private final org.newsclub.net.unix.rmi.SelftestProvider rmiSelftests =\n+ new org.newsclub.net.unix.rmi.SelftestProvider();\n+\n public Map[]> tests() throws Exception {\n Map[]> tests = new LinkedHashMap<>();\n- tests.putAll(new org.newsclub.net.unix.SelftestProvider().tests());\n- tests.putAll(new org.newsclub.net.unix.rmi.SelftestProvider().tests());\n+ tests.putAll(commonSelftests.tests());\n+ tests.putAll(tipcSelftests.tests());\n+ tests.putAll(rmiSelftests.tests());\n \n return tests;\n }\n+\n+ public Set modulesDisabledByDefault() {\n+ Set set = new HashSet<>();\n+ set.addAll(commonSelftests.modulesDisabledByDefault());\n+ set.addAll(tipcSelftests.modulesDisabledByDefault());\n+ set.addAll(rmiSelftests.modulesDisabledByDefault());\n+ return set;\n+ }\n }\ndiff --git a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/Selftest.java b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/Selftest.java\nindex a07d2423b..d4471d369 100644\n--- a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/Selftest.java\n+++ b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/Selftest.java\n@@ -22,6 +22,8 @@ import java.io.FileInputStream;\n import java.io.IOException;\n import java.io.InputStreamReader;\n import java.io.OutputStreamWriter;\n+import java.io.PrintWriter;\n+import java.io.StringWriter;\n import java.lang.annotation.Annotation;\n import java.lang.reflect.InvocationTargetException;\n import java.nio.charset.Charset;\n@@ -35,18 +37,25 @@ import java.util.List;\n import java.util.Locale;\n import java.util.Map;\n import java.util.Map.Entry;\n+import java.util.Objects;\n+import java.util.Optional;\n import java.util.Set;\n import java.util.TreeMap;\n \n import org.junit.jupiter.engine.JupiterTestEngine;\n import org.junit.jupiter.engine.discovery.DiscoverySelectorResolver;\n+import org.junit.platform.engine.TestExecutionResult;\n import org.junit.platform.engine.support.descriptor.EngineDescriptor;\n import org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine;\n+import org.junit.platform.launcher.TestIdentifier;\n import org.junit.platform.launcher.listeners.TestExecutionSummary;\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.AFSocketCapability;\n import org.newsclub.net.unix.AFUNIXSocket;\n-import org.newsclub.net.unix.AFUNIXSocketCapability;\n \n import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+import com.kohlschutter.testutil.TestAbortedWithImportantMessageException;\n+import com.kohlschutter.testutil.TestAbortedWithImportantMessageException.MessageType;\n import com.kohlschutter.util.ConsolePrintStream;\n import com.kohlschutter.util.SystemPropertyUtil;\n \n@@ -60,16 +69,25 @@ import com.kohlschutter.util.SystemPropertyUtil;\n * \n * @author Christian Kohlschütter\n */\n+@SuppressWarnings({\"PMD.CyclomaticComplexity\", \"PMD.CognitiveComplexity\"})\n public class Selftest {\n private static final Class CAP_ANNOTATION_CLASS =\n getAFUNIXSocketCapabilityRequirementClass();\n \n private final ConsolePrintStream out = ConsolePrintStream.wrapSystemOut();\n- private final Map results = new LinkedHashMap<>();\n- private final List supportedCapabilites = new ArrayList<>();\n- private final List unsupportedCapabilites = new ArrayList<>();\n+ private final Map results = new LinkedHashMap<>();\n+ private final List supportedCapabilites = new ArrayList<>();\n+ private final List unsupportedCapabilites = new ArrayList<>();\n private boolean withIssues = false;\n private boolean fail = false;\n+ private boolean modified = false;\n+ private boolean isSupportedAFUNIX = false;\n+ private final List important = new ArrayList<>();\n+ private boolean inconclusive = false;\n+\n+ private enum Result {\n+ SKIP, PASS, DONE, NONE, FAIL\n+ }\n \n /**\n * maven-shade-plugin's minimizeJar isn't perfect, so we give it a little hint by adding static\n@@ -96,8 +114,10 @@ public class Selftest {\n * A zero error code indicates success.\n * \n * @param args Ignored.\n- * @throws Exception on error.\n+ * @throws IOException on error.\n */\n+ @SuppressFBWarnings({\n+ \"THROWS_METHOD_THROWS_CLAUSE_THROWABLE\", \"THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION\"})\n public static void main(String[] args) throws Exception {\n Selftest st = new Selftest();\n \n@@ -107,10 +127,37 @@ public class Selftest {\n st.checkSupported();\n st.checkCapabilities();\n \n- for (Entry[]> en : new SelftestProvider().tests().entrySet()) {\n- st.runTests(en.getKey(), en.getValue());\n+ SelftestProvider sp = new SelftestProvider();\n+ Set disabledModules = sp.modulesDisabledByDefault();\n+\n+ List messagesAtEnd = new ArrayList<>();\n+ for (Entry[]> en : sp.tests().entrySet()) {\n+ String module = en.getKey();\n+ if (disabledModules.contains(module)) {\n+ if (SystemPropertyUtil.getBooleanSystemProperty(\"selftest.enable-module.\" + module,\n+ false)) {\n+ // System.out.println(\"Enabled optional module: \" + module);\n+ st.modified = true;\n+ } else {\n+ messagesAtEnd.add(\"Skipping optional module: \" + module\n+ + \"; enable by launching with -Dselftest.enable-module.\" + module + \"=true\");\n+ continue;\n+ }\n+ } else if (SystemPropertyUtil.getBooleanSystemProperty(\"selftest.disable-module.\" + module,\n+ false)) {\n+ messagesAtEnd.add(\"Skipping required module: \" + module + \"; this taints the test\");\n+ st.withIssues = true;\n+ }\n+ st.runTests(module, en.getValue());\n }\n \n+ if (!messagesAtEnd.isEmpty()) {\n+ for (String m : messagesAtEnd) {\n+ System.out.println(m);\n+ }\n+ }\n+\n+ st.checkInitError();\n st.dumpResults();\n \n int rc = st.isFail() ? 1 : 0;\n@@ -173,10 +220,10 @@ public class Selftest {\n }\n \n public void checkSupported() {\n- out.print(\"AFUNIXSocket.isSupported: \");\n+ out.print(\"AFSocket.isSupported: \");\n out.flush();\n \n- boolean isSupported = AFUNIXSocket.isSupported();\n+ boolean isSupported = AFSocket.isSupported();\n out.println(isSupported);\n out.println();\n out.flush();\n@@ -186,11 +233,25 @@ public class Selftest {\n out.println();\n fail = true;\n }\n+\n+ out.print(\"AFUNIXSocket.isSupported: \");\n+ out.flush();\n+\n+ isSupportedAFUNIX = AFUNIXSocket.isSupported();\n+ out.println(isSupportedAFUNIX);\n+ out.println();\n+ out.flush();\n+\n+ if (!isSupportedAFUNIX) {\n+ out.println(\"WARNING: AF_UNIX sockets are not supported on this platform\");\n+ out.println();\n+ withIssues = true;\n+ }\n }\n \n public void checkCapabilities() {\n- for (AFUNIXSocketCapability cap : AFUNIXSocketCapability.values()) {\n- boolean supported = AFUNIXSocket.supports(cap);\n+ for (AFSocketCapability cap : AFSocketCapability.values()) {\n+ boolean supported = AFSocket.supports(cap);\n (supported ? supportedCapabilites : unsupportedCapabilites).add(cap);\n }\n }\n@@ -204,59 +265,112 @@ public class Selftest {\n return fail;\n }\n \n+ private void checkInitError() {\n+ Throwable t = retrieveInitError();\n+ if (t == null) {\n+ return;\n+ }\n+\n+ important.add(\"The native library failed to load.\");\n+\n+ StringWriter sw = new StringWriter();\n+ PrintWriter pw = new PrintWriter(sw);\n+ t.printStackTrace(pw);\n+ pw.flush();\n+ String ts = sw.toString();\n+ String tsLower = ts.toLowerCase(Locale.ENGLISH);\n+\n+ if (tsLower.contains(\"not permitted\") || ts.contains(\"permission\")) {\n+ important.add(\"It looks like there were some permission errors.\");\n+ }\n+\n+ if (tsLower.contains(\"failed to map segment\")) {\n+ important.add(\"Your temporary directory is probably mounted with \\\"noexec\\\", \"\n+ + \"which prevents the native library from loading.\");\n+ important.add(\"see: https://github.com/kohlschutter/junixsocket/issues/99\");\n+ Object tmpDir = retrieveTempDir();\n+ if (tmpDir == null) {\n+ tmpDir = System.getProperty(\"java.io.tmpdir\");\n+ }\n+ if (tmpDir != null) {\n+ important.add(\"Temp dir: \" + tmpDir);\n+ }\n+ important.add(\n+ \"You can specify a different directory using -Dorg.newsclub.net.unix.library.tmpdir=\");\n+ }\n+ }\n+\n /**\n * Dumps the results of the selftest.\n * \n */\n- public void dumpResults() {\n+ public void dumpResults() { // NOPMD\n+ if (modified) {\n+ important.add(\"Selftest was modified, for example to exclude/include certain tests.\");\n+ inconclusive = true;\n+ }\n+ if (!isSupportedAFUNIX) {\n+ important.add(\n+ \"Environment does not support UNIX sockets, which is an important part of junixsocket.\");\n+ // inconclusive = true;\n+ }\n+ if (inconclusive) {\n+ important.add(\"Selftest results may be inconclusive.\");\n+ }\n+\n+ if (withIssues) {\n+ important.add(\"\\\"With issues\\\": \"\n+ + \"Please carefully check the output above; the software may not be able to do what you want.\");\n+ }\n+\n out.println();\n out.println(\"Selftest results:\");\n \n- for (Map.Entry en : results.entrySet()) {\n- Object res = en.getValue();\n- String result = \"DONE\";\n+ for (Map.Entry en : results.entrySet()) {\n+ ModuleResult res = en.getValue();\n+\n+ String result = res == null ? null : res.result.name();\n String extra;\n if (res == null) {\n result = \"SKIP\";\n extra = \"(skipped by user request)\";\n- } else if (res instanceof Throwable) {\n- result = \"FAIL\";\n- extra = res.toString();\n+ } else if (res.summary == null) {\n+ extra = res.throwable == null ? \"(unknown error)\" : res.throwable.toString();\n fail = true;\n } else {\n- TestExecutionSummary summary = (TestExecutionSummary) en.getValue();\n+ TestExecutionSummary summary = res.summary;\n \n- extra = summary.getTestsSucceededCount() + \"/\" + summary.getTestsFoundCount();\n+ long nSucceeded = (summary.getTestsSucceededCount() + res.getNumAbortedNonIssues());\n+ extra = nSucceeded + \"/\" + summary.getTestsFoundCount();\n long nSkipped = summary.getTestsSkippedCount();\n if (nSkipped > 0) {\n extra += \" (\" + nSkipped + \" skipped)\";\n }\n-\n- if (summary.getTestsFailedCount() > 0) {\n- result = \"FAIL\";\n- fail = true;\n- } else if (summary.getTestsFoundCount() == 0) {\n- result = \"NONE\";\n- fail = true;\n- } else if ((summary.getTestsSucceededCount() + summary.getTestsSkippedCount()) == summary\n- .getTestsFoundCount()) {\n- result = \"PASS\";\n- } else if (summary.getTestsAbortedCount() > 0) {\n- withIssues = true;\n- }\n }\n+\n out.println(result + \"\\t\" + en.getKey() + \"\\t\" + extra);\n }\n out.println();\n \n+ if (!important.isEmpty()) {\n+ for (String l : important) {\n+ out.println(\"IMPORTANT: \" + l);\n+ }\n+ out.println();\n+ }\n+\n out.println(\"Supported capabilities: \" + supportedCapabilites);\n out.println(\"Unsupported capabilities: \" + unsupportedCapabilites);\n out.println();\n \n- if (fail) {\n- out.println(\"Selftest FAILED\");\n- } else if (withIssues) {\n- out.println(\"Selftest PASSED WITH ISSUES\");\n+ if (fail || withIssues) {\n+ if (inconclusive || modified) {\n+ out.println(\"Selftest INCONCLUSIVE\");\n+ } else if (fail) {\n+ out.println(\"Selftest FAILED\");\n+ } else if (withIssues) {\n+ out.println(\"Selftest PASSED WITH ISSUES\");\n+ }\n } else {\n out.println(\"Selftest PASSED\");\n }\n@@ -279,11 +393,11 @@ public class Selftest {\n Annotation annotation = klass.getAnnotation(CAP_ANNOTATION_CLASS);\n if (annotation != null) {\n try {\n- AFUNIXSocketCapability[] caps = (AFUNIXSocketCapability[]) annotation.getClass()\n- .getMethod(\"value\").invoke(annotation);\n+ AFSocketCapability[] caps = (AFSocketCapability[]) annotation.getClass().getMethod(\n+ \"value\").invoke(annotation);\n if (caps != null) {\n- for (AFUNIXSocketCapability cap : caps) {\n- if (!AFUNIXSocket.supports(cap)) {\n+ for (AFSocketCapability cap : caps) {\n+ if (!AFSocket.supports(cap)) {\n out.println(\"Skipping class \" + className + \"; unsupported capability: \" + cap);\n return false;\n }\n@@ -309,6 +423,7 @@ public class Selftest {\n * @param module The module name.\n * @param testClasses The test classes.\n */\n+ @SuppressWarnings({\"PMD.ExcessiveMethodLength\", \"PMD.NcssCount\", \"PMD.NPathComplexity\"})\n public void runTests(String module, Class[] testClasses) {\n String prefix = \"Testing \\\"\" + module + \"\\\"... \";\n out.markPosition();\n@@ -316,12 +431,16 @@ public class Selftest {\n out.flush();\n \n String only = System.getProperty(\"selftest.only\", \"\");\n+ if (!only.isEmpty()) {\n+ modified = true;\n+ }\n \n- Object summary;\n+ final ModuleResult moduleResult;\n if (Boolean.valueOf(System.getProperty(\"selftest.skip.\" + module, \"false\"))) {\n out.println(\"Skipping module \" + module + \"; skipped by request\");\n withIssues = true;\n- summary = null;\n+ modified = true;\n+ moduleResult = new ModuleResult(Result.SKIP, null, null);\n } else {\n List> list = new ArrayList<>(testClasses.length);\n for (Class testClass : testClasses) {\n@@ -343,20 +462,73 @@ public class Selftest {\n if (skipFullyQualified || Boolean.valueOf(System.getProperty(\"selftest.skip.\" + simpleName,\n \"false\"))) {\n out.println(\"Skipping test class \" + className + \"; skipped by request\");\n+ modified = true;\n withIssues = true;\n } else if (checkIfCapabilitiesSupported(className)) {\n list.add(testClass);\n }\n }\n \n+ TestExecutionSummary summary = null;\n+ Exception exception = null;\n+ long numAbortedNonIssues = 0;\n try {\n- summary = new SelftestExecutor(list, prefix).execute(out);\n+ SelftestExecutor ex = new SelftestExecutor(list, prefix);\n+ summary = ex.execute(out);\n+\n+ for (Map.Entry en : ex.getTestsWithWarnings()\n+ .entrySet()) {\n+ TestIdentifier tid = en.getKey();\n+ TestExecutionResult res = en.getValue();\n+ Optional t = res.getThrowable();\n+ if (t.isPresent() && t.get() instanceof TestAbortedWithImportantMessageException) {\n+ String key = module + \": \" + ex.getTestIdentifier(tid.getParentId().get())\n+ .getDisplayName() + \".\" + tid.getDisplayName();\n+ TestAbortedWithImportantMessageException ime =\n+ (TestAbortedWithImportantMessageException) t.get();\n+\n+ MessageType messageType = ime.messageType();\n+ if (messageType.isIncludeTestInfo()) {\n+ important.add(key + \": \" + ime.getMessage());\n+ } else {\n+ important.add(ime.getMessage());\n+ }\n+ if (!messageType.isWithIssues()) {\n+ numAbortedNonIssues++;\n+ }\n+ }\n+ }\n } catch (Exception e) {\n e.printStackTrace(out);\n- summary = e;\n+ exception = e;\n+ }\n+\n+ if (exception != null || summary == null) {\n+ moduleResult = new ModuleResult(Result.FAIL, null, exception);\n+ fail = true;\n+ } else {\n+ final Result result;\n+ if (summary.getTestsFailedCount() > 0) {\n+ result = Result.FAIL;\n+ fail = true;\n+ } else if (summary.getTestsFoundCount() == 0) {\n+ result = Result.NONE;\n+ fail = true;\n+ } else if ((summary.getTestsSucceededCount() + summary.getTestsSkippedCount()\n+ + numAbortedNonIssues) == summary.getTestsFoundCount()) {\n+ result = Result.PASS;\n+ } else if (summary.getTestsAbortedCount() > 0) {\n+ result = Result.DONE;\n+ withIssues = true;\n+ } else {\n+ result = Result.DONE;\n+ }\n+\n+ moduleResult = new ModuleResult(result, summary, null);\n+ moduleResult.numAbortedNonIssues = numAbortedNonIssues;\n }\n }\n- results.put(module, summary);\n+ results.put(module, moduleResult);\n }\n \n private void dumpContentsOfSystemConfigFile(File file) {\n@@ -425,4 +597,40 @@ public class Selftest {\n dumpContentsOfSystemConfigFile(file);\n }\n }\n+\n+ private static Throwable retrieveInitError() {\n+ try {\n+ Class clazz = Class.forName(\"org.newsclub.net.unix.SelftestDiagnosticsHelper\");\n+ return (Throwable) clazz.getMethod(\"initError\").invoke(null);\n+ } catch (Exception e) {\n+ return null;\n+ }\n+ }\n+\n+ private static File retrieveTempDir() {\n+ try {\n+ Class clazz = Class.forName(\"org.newsclub.net.unix.SelftestDiagnosticsHelper\");\n+ return (File) clazz.getMethod(\"tempDir\").invoke(null);\n+ } catch (Exception e) {\n+ return null;\n+ }\n+ }\n+\n+ private static final class ModuleResult {\n+ private final Result result;\n+ private final TestExecutionSummary summary;\n+ private final Throwable throwable;\n+ private long numAbortedNonIssues = 0;\n+\n+ ModuleResult(Result result, TestExecutionSummary summary, Throwable t) {\n+ Objects.requireNonNull(result);\n+ this.result = result;\n+ this.summary = summary;\n+ this.throwable = t;\n+ }\n+\n+ long getNumAbortedNonIssues() {\n+ return numAbortedNonIssues;\n+ }\n+ }\n }\ndiff --git a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestExecutor.java b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestExecutor.java\nindex 81ac1a00c..2af503215 100644\n--- a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestExecutor.java\n+++ b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestExecutor.java\n@@ -23,6 +23,7 @@ import java.io.OutputStreamWriter;\n import java.io.PrintWriter;\n import java.nio.charset.Charset;\n import java.util.HashMap;\n+import java.util.LinkedHashMap;\n import java.util.List;\n import java.util.Map;\n import java.util.Optional;\n@@ -31,6 +32,7 @@ import java.util.stream.Collectors;\n import org.junit.platform.console.options.Theme;\n import org.junit.platform.console.tasks.JuxPackageAccess;\n import org.junit.platform.engine.TestExecutionResult;\n+import org.junit.platform.engine.TestExecutionResult.Status;\n import org.junit.platform.engine.discovery.DiscoverySelectors;\n import org.junit.platform.launcher.Launcher;\n import org.junit.platform.launcher.LauncherDiscoveryRequest;\n@@ -42,11 +44,16 @@ import org.junit.platform.launcher.core.LauncherFactory;\n import org.junit.platform.launcher.listeners.SummaryGeneratingListener;\n import org.junit.platform.launcher.listeners.TestExecutionSummary;\n \n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n import com.kohlschutter.util.ConsolePrintStream;\n \n+@SuppressFBWarnings({\"THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION\"})\n class SelftestExecutor {\n private final List> testClasses;\n private final String prefix;\n+ private final Map tids = new HashMap<>();\n+\n+ private final Map testsWithWarnings = new LinkedHashMap<>();\n \n SelftestExecutor(final List> testClasses, String prefix) {\n this.testClasses = testClasses;\n@@ -67,7 +74,7 @@ class SelftestExecutor {\n // https://junit.org/junit5/docs/5.7.1/api/org.junit.jupiter.api/org/junit/jupiter/api/Timeout.html\n requestBuilder.configurationParameter(\n \"junit.jupiter.execution.timeout.testable.method.default\", System.getProperty(\n- \"selftest.test-timeout\", \"10 s\"));\n+ \"selftest.test-timeout\", \"30 s\"));\n \n requestBuilder.selectors(testClasses.stream().map(DiscoverySelectors::selectClass).collect(\n Collectors.toList()));\n@@ -75,8 +82,8 @@ class SelftestExecutor {\n \n TestPlan testPlan = launcher.discover(discoveryRequest);\n \n+ tids.clear();\n launcher.execute(testPlan, new TestExecutionListener() {\n- final Map tids = new HashMap<>();\n \n @Override\n public void executionStarted(TestIdentifier tid) {\n@@ -90,11 +97,13 @@ class SelftestExecutor {\n \n @Override\n public void executionFinished(TestIdentifier tid, TestExecutionResult testExecutionResult) {\n- tids.remove(tid.getUniqueId());\n-\n if (!tid.getParentId().isPresent()) {\n out0.updateln(prefix + \"done\");\n }\n+\n+ if (testExecutionResult.getStatus() == Status.ABORTED) {\n+ testsWithWarnings.put(tid, testExecutionResult);\n+ }\n }\n });\n \n@@ -107,4 +116,12 @@ class SelftestExecutor {\n out.flush();\n }\n }\n+\n+ Map getTestsWithWarnings() {\n+ return testsWithWarnings;\n+ }\n+\n+ TestIdentifier getTestIdentifier(String id) {\n+ return tids.get(id);\n+ }\n }\ndiff --git a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestProvider.java b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestProvider.java\nindex 7bb659059..862571707 100644\n--- a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestProvider.java\n+++ b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestProvider.java\n@@ -17,8 +17,10 @@\n */\n package org.newsclub.net.unix.selftest;\n \n+import java.util.Collections;\n import java.util.LinkedHashMap;\n import java.util.Map;\n+import java.util.Set;\n \n /**\n * Provides references to all tests that should be included in junixsocket-selftest.\n@@ -38,4 +40,8 @@ public class SelftestProvider {\n \n return tests;\n }\n+\n+ public Set modulesDisabledByDefault() {\n+ return Collections.emptySet();\n+ }\n }\ndiff --git a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestTest.java b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestTest.java\nindex e2fefa821..d5903e496 100644\n--- a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestTest.java\n+++ b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/SelftestTest.java\n@@ -19,22 +19,37 @@ package org.newsclub.net.unix.selftest;\n \n import org.junit.jupiter.api.Test;\n \n+import com.kohlschutter.testutil.TestAbortedWithImportantMessageException;\n+import com.kohlschutter.testutil.TestAbortedWithImportantMessageException.MessageType;\n+\n public class SelftestTest {\n @Test\n- public void testHelloWorld() throws Exception {\n+ public void testHelloWorld() {\n }\n \n @Test\n- public void testFoo() throws Exception {\n+ public void testFoo() {\n // fail();\n }\n \n @Test\n- public void testStdout() throws Exception {\n+ public void testStdout() {\n System.out.println(\"Some interrupting text\");\n }\n \n @Test\n- public void testBar() throws Exception {\n+ public void testBar() {\n+ }\n+\n+ @Test\n+ public void testAbortedInformational() {\n+ throw new TestAbortedWithImportantMessageException(MessageType.TEST_ABORTED_INFORMATIONAL,\n+ \"Some important message with source info\");\n+ }\n+\n+ @Test\n+ public void testAbortedInformationalShort() {\n+ throw new TestAbortedWithImportantMessageException(MessageType.TEST_ABORTED_SHORT_INFORMATIONAL,\n+ \"Some important message\");\n }\n }\ndiff --git a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/EchoServer.java b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/EchoServer.java\nnew file mode 100644\nindex 000000000..839f19dbc\n--- /dev/null\n+++ b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/EchoServer.java\n@@ -0,0 +1,75 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.selftest.apps;\n+\n+import java.io.IOException;\n+import java.util.concurrent.ExecutionException;\n+import java.util.concurrent.TimeUnit;\n+\n+import org.newsclub.net.unix.AFAddressFamily;\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.AFSocketAddress;\n+import org.newsclub.net.unix.server.AFSocketServer;\n+\n+// CPD-OFF\n+public class EchoServer {\n+ private static void printHelp() {\n+ System.err.println(\"Syntax: java \" + EchoServer.class.getName() + \" \");\n+ System.err.println();\n+ System.err.println(\"Supported schemes: \" + AFAddressFamily.uriSchemes());\n+ }\n+\n+ public static void main(String[] args) throws IOException, InterruptedException,\n+ ExecutionException {\n+ if (args.length == 0) {\n+ printHelp();\n+ System.exit(1);\n+ return;\n+ }\n+\n+ AFSocketAddress address;\n+ try {\n+ address = SocketAddressUtil.parseAddress(args[0]);\n+ } catch (Exception e) {\n+ printHelp();\n+ System.err.println();\n+ e.printStackTrace();\n+ System.exit(1);\n+ return;\n+ }\n+\n+ if (new AFSocketServer(address) {\n+ @Override\n+ protected void doServeSocket(AFSocket sock) throws IOException {\n+ System.out.println(\"Connected: \" + sock);\n+ long numBytes = -1;\n+ long time = System.currentTimeMillis();\n+ try {\n+ numBytes = sock.getInputStream().transferTo(sock.getOutputStream()); // NOPMD\n+ } finally {\n+ time = System.currentTimeMillis() - time;\n+ System.out.println(\"Disconnected: \" + sock + \"; echoed bytes: \" + (numBytes == -1\n+ ? \"unknown\" : numBytes) + \"; speed: \" + ((numBytes == -1 || time == 0) ? \"unknown\"\n+ : (numBytes * 1000L / time) + \"/s\"));\n+ }\n+ }\n+ }.startAndWaitToBecomeReady(10, TimeUnit.SECONDS)) {\n+ System.out.println(\"Server ready, listening on \" + address);\n+ }\n+ }\n+}\ndiff --git a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/SocketAddressUtil.java b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/SocketAddressUtil.java\nnew file mode 100644\nindex 000000000..c7cc172de\n--- /dev/null\n+++ b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/SocketAddressUtil.java\n@@ -0,0 +1,37 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.selftest.apps;\n+\n+import java.io.File;\n+import java.net.SocketException;\n+import java.net.URI;\n+\n+import org.newsclub.net.unix.AFSocketAddress;\n+import org.newsclub.net.unix.AFUNIXSocketAddress;\n+\n+public class SocketAddressUtil {\n+ public static AFSocketAddress parseAddress(String addr) throws SocketException {\n+ if (addr.startsWith(\"/\")) {\n+ return AFUNIXSocketAddress.of(new File(addr));\n+ } else if (addr.startsWith(\"file:\")) {\n+ return AFUNIXSocketAddress.of(URI.create(addr));\n+ } else {\n+ return AFSocketAddress.of(URI.create(addr));\n+ }\n+ }\n+}\ndiff --git a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/StreamClient.java b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/StreamClient.java\nnew file mode 100644\nindex 000000000..759459c39\n--- /dev/null\n+++ b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/StreamClient.java\n@@ -0,0 +1,76 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.selftest.apps;\n+\n+import java.io.FileDescriptor;\n+import java.io.FileInputStream;\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.util.concurrent.ExecutionException;\n+import java.util.concurrent.ExecutorService;\n+import java.util.concurrent.Executors;\n+import java.util.concurrent.Future;\n+\n+import org.newsclub.net.unix.AFAddressFamily;\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.AFSocketAddress;\n+\n+// CPD-OFF\n+\n+public class StreamClient {\n+ private static void printHelp() {\n+ System.err.println(\"Syntax: java \" + StreamClient.class.getName() + \" \");\n+ System.err.println();\n+ System.err.println(\"Supported schemes: \" + AFAddressFamily.uriSchemes());\n+ }\n+\n+ public static void main(String[] args) throws IOException, InterruptedException,\n+ ExecutionException {\n+ if (args.length == 0) {\n+ printHelp();\n+ System.exit(1);\n+ return;\n+ }\n+\n+ AFSocketAddress address;\n+ try {\n+ address = SocketAddressUtil.parseAddress(args[0]);\n+ } catch (Exception e) {\n+ printHelp();\n+ System.err.println();\n+ e.printStackTrace();\n+ System.exit(1);\n+ return;\n+ }\n+\n+ ExecutorService exc = Executors.newCachedThreadPool();\n+ try (AFSocket sock = address.newConnectedSocket();) {\n+ sock.setReceiveBufferSize(8192);\n+\n+ Future sentFuture = exc.submit(() -> {\n+ // System.in may be a BufferedInputStream, so let's pass the proper stream\n+ try (InputStream in = new FileInputStream(FileDescriptor.in)) {\n+ return sock.getOutputStream().transferFrom(in);\n+ }\n+ });\n+ /* long received = */ sock.getInputStream().transferTo(System.out);\n+ /* long sent = */ sentFuture.get();\n+ exc.shutdown();\n+ }\n+ }\n+}\ndiff --git a/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/ZeroServer.java b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/ZeroServer.java\nnew file mode 100644\nindex 000000000..2f865ab57\n--- /dev/null\n+++ b/junixsocket-selftest/src/main/java/org/newsclub/net/unix/selftest/apps/ZeroServer.java\n@@ -0,0 +1,99 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.selftest.apps;\n+\n+import java.io.File;\n+import java.io.FileInputStream;\n+import java.io.IOException;\n+import java.nio.ByteBuffer;\n+import java.nio.channels.ClosedChannelException;\n+import java.nio.channels.SocketChannel;\n+import java.util.concurrent.ExecutionException;\n+import java.util.concurrent.TimeUnit;\n+\n+import org.newsclub.net.unix.AFAddressFamily;\n+import org.newsclub.net.unix.AFOutputStream;\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.AFSocketAddress;\n+import org.newsclub.net.unix.server.AFSocketServer;\n+\n+public class ZeroServer {\n+ private static void printHelp() {\n+ System.err.println(\"Syntax: java \" + ZeroServer.class.getName() + \" \");\n+ System.err.println();\n+ System.err.println(\"Supported schemes: \" + AFAddressFamily.uriSchemes());\n+ }\n+\n+ public static void main(String[] args) throws IOException, InterruptedException,\n+ ExecutionException {\n+ if (args.length == 0) {\n+ printHelp();\n+ System.exit(1);\n+ return;\n+ }\n+\n+ AFSocketAddress address;\n+ try {\n+ address = SocketAddressUtil.parseAddress(args[0]);\n+ } catch (Exception e) {\n+ printHelp();\n+ System.err.println();\n+ e.printStackTrace();\n+ System.exit(1);\n+ return;\n+ }\n+\n+ if (new AFSocketServer(address) {\n+ @Override\n+ protected void doServeSocket(AFSocket sock) throws IOException {\n+ System.out.println(\"Connected: \" + sock);\n+ long numBytes = -1;\n+ try {\n+\n+ File devZeroFile = new File(\"/dev/zero\");\n+ if (devZeroFile.exists() && Boolean.valueOf(System.getProperty(\"useDevZero\", \"true\"))) {\n+ System.out.println(\"Streaming /dev/zero\");\n+ try (FileInputStream fin = new FileInputStream(devZeroFile);\n+ AFOutputStream out = sock.getOutputStream()) {\n+ numBytes = out.transferFrom(fin); // NOPMD\n+ }\n+ } else {\n+ System.out.println(\"Streaming empty ByteBuffer\");\n+ ByteBuffer buf = ByteBuffer.allocate(8192);\n+ sock.setSendBufferSize(8192);\n+ sock.setSoTimeout(1);\n+ numBytes = 0;\n+ try (SocketChannel out = sock.getChannel()) {\n+ while (!Thread.interrupted()) {\n+ numBytes += out.write(buf);\n+ buf.rewind();\n+ }\n+ } catch (ClosedChannelException e) {\n+ // ignore\n+ }\n+ }\n+ } finally {\n+ System.out.println(\"Disconnected: \" + sock + \"; written bytes: \" + (numBytes == -1\n+ ? \"unknown\" : numBytes));\n+ }\n+ }\n+ }.startAndWaitToBecomeReady(10, TimeUnit.SECONDS)) {\n+ System.out.println(\"Server ready, listening on \" + address);\n+ }\n+ }\n+}\ndiff --git a/junixsocket-server/pom.xml b/junixsocket-server/pom.xml\nindex 8581fd5ef..a5ac1e561 100644\n--- a/junixsocket-server/pom.xml\n+++ b/junixsocket-server/pom.xml\n@@ -6,7 +6,7 @@\n \n com.kohlschutter.junixsocket\n junixsocket-parent\n- 2.4.1-SNAPSHOT\n+ 2.5.0-SNAPSHOT\n ../pom.xml\n \n junixsocket-server\ndiff --git a/junixsocket-server/src/main/java/module-info.java b/junixsocket-server/src/main/java/module-info.java\nindex 25c9e0c2d..2c826f8cf 100644\n--- a/junixsocket-server/src/main/java/module-info.java\n+++ b/junixsocket-server/src/main/java/module-info.java\n@@ -4,6 +4,7 @@\n module org.newsclub.net.unix.server {\n exports org.newsclub.net.unix.server;\n \n- requires org.newsclub.net.unix;\n+ requires transitive org.newsclub.net.unix;\n requires static com.kohlschutter.annotations.compiletime;\n+ requires org.eclipse.jdt.annotation;\n }\ndiff --git a/junixsocket-server/src/main/java/org/newsclub/net/unix/server/AFSocketServer.java b/junixsocket-server/src/main/java/org/newsclub/net/unix/server/AFSocketServer.java\nnew file mode 100644\nindex 000000000..a230f4cb0\n--- /dev/null\n+++ b/junixsocket-server/src/main/java/org/newsclub/net/unix/server/AFSocketServer.java\n@@ -0,0 +1,58 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.server;\n+\n+import java.io.IOException;\n+import java.net.ServerSocket;\n+import java.net.SocketAddress;\n+\n+import org.newsclub.net.unix.AFServerSocket;\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.AFSocketAddress;\n+\n+/**\n+ * A base implementation for a simple, multi-threaded socket server using {@link AFSocket}s.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public abstract class AFSocketServer extends\n+ SocketServer, AFServerSocket> {\n+ /**\n+ * Creates a server using the given, bound {@link ServerSocket}.\n+ * \n+ * @param serverSocket The server socket to use (must be bound).\n+ */\n+ public AFSocketServer(AFServerSocket serverSocket) {\n+ super(serverSocket);\n+ }\n+\n+ /**\n+ * Creates a server using the given {@link SocketAddress}.\n+ * \n+ * @param listenAddress The address to bind the socket on.\n+ */\n+ public AFSocketServer(A listenAddress) {\n+ super(listenAddress);\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ @Override\n+ protected AFServerSocket newServerSocket() throws IOException {\n+ return (AFServerSocket) getListenAddress().getAddressFamily().newServerSocket();\n+ }\n+}\ndiff --git a/junixsocket-server/src/main/java/org/newsclub/net/unix/server/AFUNIXSocketServer.java b/junixsocket-server/src/main/java/org/newsclub/net/unix/server/AFUNIXSocketServer.java\nindex fb147aeb0..b36f8d02f 100644\n--- a/junixsocket-server/src/main/java/org/newsclub/net/unix/server/AFUNIXSocketServer.java\n+++ b/junixsocket-server/src/main/java/org/newsclub/net/unix/server/AFUNIXSocketServer.java\n@@ -18,27 +18,12 @@\n package org.newsclub.net.unix.server;\n \n import java.io.IOException;\n-import java.io.InterruptedIOException;\n import java.net.ServerSocket;\n import java.net.Socket;\n import java.net.SocketAddress;\n-import java.net.SocketException;\n-import java.net.SocketTimeoutException;\n-import java.util.Objects;\n-import java.util.concurrent.Callable;\n-import java.util.concurrent.ExecutorService;\n-import java.util.concurrent.Executors;\n-import java.util.concurrent.ForkJoinPool;\n-import java.util.concurrent.Future;\n-import java.util.concurrent.ScheduledExecutorService;\n-import java.util.concurrent.ScheduledFuture;\n import java.util.concurrent.TimeUnit;\n-import java.util.concurrent.atomic.AtomicBoolean;\n \n-import org.newsclub.net.unix.AFUNIXServerSocket;\n-import org.newsclub.net.unix.AFUNIXSocketAddress;\n-\n-import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+import org.newsclub.net.unix.AFSocketAddress;\n \n /**\n * A base implementation for a simple, multi-threaded socket server.\n@@ -46,182 +31,25 @@ import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n * This class supports both AF_UNIX and \"regular\" sockets.\n * \n * @author Christian Kohlschütter\n+ * @deprecated Use {@link SocketServer} or {@link AFSocketServer}\n */\n-public abstract class AFUNIXSocketServer {\n- private static final ScheduledExecutorService TIMEOUTS = Executors.newScheduledThreadPool(1);\n-\n- private final SocketAddress listenAddress;\n-\n- private int maxConcurrentConnections = Runtime.getRuntime().availableProcessors();\n- private int serverTimeout = 0; // by default, the server doesn't timeout.\n- private int socketTimeout = (int) TimeUnit.SECONDS.toMillis(60);\n- private int serverBusyTimeout = (int) TimeUnit.SECONDS.toMillis(1);\n-\n- private Thread listenThread = null;\n- private ServerSocket serverSocket;\n- private final AtomicBoolean stopRequested = new AtomicBoolean(false);\n- private final AtomicBoolean ready = new AtomicBoolean(false);\n-\n- private final Object connectionsMonitor = new Object();\n- private ForkJoinPool connectionPool;\n-\n- private ScheduledFuture timeoutFuture;\n- private final ServerSocket reuseSocket;\n-\n- /**\n- * Creates a server using the given {@link SocketAddress}.\n- * \n- * @param listenAddress The address to bind the socket on.\n- */\n- public AFUNIXSocketServer(SocketAddress listenAddress) {\n- this(listenAddress, null);\n- }\n-\n+public abstract class AFUNIXSocketServer extends SocketServer {\n /**\n * Creates a server using the given, bound {@link ServerSocket}.\n * \n * @param serverSocket The server socket to use (must be bound).\n */\n public AFUNIXSocketServer(ServerSocket serverSocket) {\n- this(serverSocket.getLocalSocketAddress(), serverSocket);\n- }\n-\n- private AFUNIXSocketServer(SocketAddress listenAddress, ServerSocket preboundSocket) {\n- this.reuseSocket = preboundSocket;\n- Objects.requireNonNull(listenAddress, \"listenAddress\");\n-\n- this.listenAddress = listenAddress;\n+ super(serverSocket);\n }\n \n /**\n- * Returns the maximum number of concurrent connections.\n- * \n- * @return The maximum number of concurrent connections.\n- */\n- public int getMaxConcurrentConnections() {\n- return maxConcurrentConnections;\n- }\n-\n- /**\n- * Sets the maximum number of concurrent connections.\n- * \n- * @param maxConcurrentConnections The new maximum.\n- */\n- public void setMaxConcurrentConnections(int maxConcurrentConnections) {\n- if (connectionPool != null) {\n- throw new IllegalStateException(\"Already configured\");\n- }\n- this.maxConcurrentConnections = maxConcurrentConnections;\n- }\n-\n- /**\n- * Returns the server timeout (in milliseconds).\n- * \n- * @return The server timeout in milliseconds (0 = no timeout).\n- */\n- public int getServerTimeout() {\n- return serverTimeout;\n- }\n-\n- /**\n- * Sets the server timeout (in milliseconds).\n- * \n- * @param timeout The new timeout in milliseconds (0 = no timeout).\n- */\n- public void setServerTimeout(int timeout) {\n- synchronized (this) {\n- if (serverSocket != null) {\n- throw new IllegalStateException(\"Already configured\");\n- }\n- this.serverTimeout = timeout;\n- }\n- }\n-\n- /**\n- * Returns the socket timeout (in milliseconds).\n- * \n- * @return The socket timeout in milliseconds (0 = no timeout).\n- */\n- public int getSocketTimeout() {\n- return socketTimeout;\n- }\n-\n- /**\n- * Sets the socket timeout (in milliseconds).\n- * \n- * @param timeout The new timeout in milliseconds (0 = no timeout).\n- */\n- public void setSocketTimeout(int timeout) {\n- this.socketTimeout = timeout;\n- }\n-\n- /**\n- * Returns the server-busy timeout (in milliseconds).\n- * \n- * @return The server-busy timeout in milliseconds (0 = no timeout).\n- */\n- public int getServerBusyTimeout() {\n- return serverBusyTimeout;\n- }\n-\n- /**\n- * Sets the server-busy timeout (in milliseconds).\n- * \n- * @param timeout The new timeout in milliseconds (0 = no timeout).\n- */\n- public void setServerBusyTimeout(int timeout) {\n- this.serverBusyTimeout = timeout;\n- }\n-\n- /**\n- * Checks if the server is running.\n- * \n- * @return {@code true} if the server is alive.\n- */\n- public boolean isRunning() {\n- synchronized (this) {\n- return (listenThread != null && listenThread.isAlive());\n- }\n- }\n-\n- /**\n- * Checks if the server is running and accepting new connections.\n- * \n- * @return {@code true} if the server is alive and ready to accept new connections.\n- */\n- public boolean isReady() {\n- return ready.get() && !stopRequested.get() && isRunning();\n- }\n-\n- /**\n- * Starts the server, and returns immediately.\n+ * Creates a server using the given {@link SocketAddress}.\n * \n- * @see #startAndWait\n+ * @param listenAddress The address to bind the socket on.\n */\n- public void start() {\n- synchronized (this) {\n- if (isRunning()) {\n- return;\n- }\n- if (connectionPool == null) {\n- connectionPool = new ForkJoinPool(maxConcurrentConnections,\n- ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);\n- }\n-\n- Thread t = new Thread(AFUNIXSocketServer.this.toString() + \" listening thread\") {\n- @Override\n- public void run() {\n- try {\n- listen();\n- } catch (Exception e) {\n- onListenException(e);\n- }\n- }\n- };\n- t.start();\n-\n- listenThread = t;\n- }\n+ public AFUNIXSocketServer(SocketAddress listenAddress) {\n+ super(listenAddress);\n }\n \n /**\n@@ -231,344 +59,19 @@ public abstract class AFUNIXSocketServer {\n * @param unit The duration's time unit.\n * @return {@code true} if the server is ready to serve requests.\n * @throws InterruptedException If the wait was interrupted.\n+ * @deprecated @see #startAndWaitToBecomeReady(long, TimeUnit)\n */\n public boolean startAndWait(long duration, TimeUnit unit) throws InterruptedException {\n- synchronized (this) {\n- start();\n- long timeStart = System.currentTimeMillis();\n- while (duration > 0) {\n- if (isReady()) {\n- return true;\n- }\n- this.wait(unit.toMillis(duration));\n- duration -= (System.currentTimeMillis() - timeStart);\n- }\n- return isReady();\n- }\n+ return startAndWaitToBecomeReady(duration, unit);\n }\n \n- /**\n- * Returns a new server socket.\n- * \n- * @return The new socket (an {@link AFUNIXServerSocket} if the listen address is an\n- * {@link AFUNIXSocketAddress}).\n- * @throws IOException on error.\n- */\n+ @Override\n protected ServerSocket newServerSocket() throws IOException {\n- if (listenAddress instanceof AFUNIXSocketAddress) {\n- return AFUNIXServerSocket.newInstance();\n+ SocketAddress listenAddress = getListenAddress();\n+ if (listenAddress instanceof AFSocketAddress) {\n+ return ((AFSocketAddress) listenAddress).getAddressFamily().newServerSocket();\n } else {\n return new ServerSocket();\n }\n }\n-\n- private void listen() throws IOException {\n- ServerSocket server;\n-\n- synchronized (this) {\n- if (reuseSocket != null) {\n- serverSocket = reuseSocket;\n- } else {\n- if (serverSocket != null) {\n- throw new IllegalStateException(\"The server is already listening\");\n- }\n- serverSocket = newServerSocket();\n- }\n- server = serverSocket;\n- }\n- onServerStarting();\n-\n- try {\n- if (!server.isBound()) {\n- server.bind(listenAddress);\n- onServerBound(listenAddress);\n- }\n- server.setSoTimeout(serverTimeout);\n-\n- acceptLoop(server);\n- } catch (SocketException e) {\n- onSocketExceptionDuringAccept(e);\n- } finally {\n- stop();\n- onServerStopped(server);\n- }\n- }\n-\n- @SuppressWarnings(\"PMD.CognitiveComplexity\")\n- @SuppressFBWarnings(\"NN_NAKED_NOTIFY\")\n- private void acceptLoop(ServerSocket server) throws IOException {\n- long busyStartTime = 0;\n- acceptLoop : while (!stopRequested.get() && !Thread.interrupted()) {\n- try {\n- while (!stopRequested.get() && connectionPool\n- .getActiveThreadCount() >= maxConcurrentConnections) {\n- if (busyStartTime == 0) {\n- busyStartTime = System.currentTimeMillis();\n- }\n- onServerBusy(busyStartTime);\n-\n- synchronized (connectionsMonitor) {\n- try {\n- connectionsMonitor.wait(serverBusyTimeout);\n- } catch (InterruptedException e) {\n- throw (InterruptedIOException) new InterruptedIOException(\n- \"Interrupted while waiting on server resources\").initCause(e);\n- }\n- }\n- }\n- busyStartTime = 0;\n-\n- if (stopRequested.get() || server == null) {\n- break;\n- }\n-\n- synchronized (AFUNIXSocketServer.this) {\n- AFUNIXSocketServer.this.notifyAll();\n- }\n- ready.set(true);\n- onServerReady(connectionPool.getActiveThreadCount());\n-\n- final Socket socket;\n- try {\n- Socket theSocket = server.accept();\n- socket = theSocket;\n- } catch (SocketException e) {\n- if (server.isClosed()) {\n- // already closed, ignore\n- break acceptLoop;\n- } else {\n- throw e;\n- }\n- }\n- try {\n- socket.setSoTimeout(socketTimeout);\n- } catch (SocketException e) {\n- // Connection closed before we could do anything\n- onSocketExceptionAfterAccept(socket, e);\n- socket.close();\n-\n- continue acceptLoop;\n- }\n-\n- onSubmitted(socket, submit(socket, connectionPool));\n- } catch (SocketTimeoutException e) {\n- if (!connectionPool.isQuiescent()) {\n- continue acceptLoop;\n- } else {\n- onServerShuttingDown();\n- connectionPool.shutdown();\n- break acceptLoop;\n- }\n- }\n- }\n- }\n-\n- /**\n- * Stops the server.\n- * \n- * @throws IOException If there was an error.\n- */\n- @SuppressFBWarnings(\"NN_NAKED_NOTIFY\")\n- public void stop() throws IOException {\n- stopRequested.set(true);\n- ready.set(false);\n-\n- synchronized (this) {\n- ServerSocket theServerSocket = serverSocket;\n- serverSocket = null;\n- try {\n- if (theServerSocket == null) {\n- return;\n- }\n- ScheduledFuture future = this.timeoutFuture;\n- if (future != null) {\n- future.cancel(false);\n- this.timeoutFuture = null;\n- }\n-\n- theServerSocket.close();\n- } finally {\n- AFUNIXSocketServer.this.notifyAll();\n- }\n- }\n- }\n-\n- private Future submit(final Socket socket, ExecutorService executor) {\n- return executor.submit(new Runnable() {\n- @Override\n- public void run() {\n- onBeforeServingSocket(socket);\n-\n- try { // NOPMD\n- doServeSocket(socket);\n- } catch (Exception e) {\n- onServingException(socket, e);\n- } finally {\n- // Notify the server's accept thread that we handled the connection\n- synchronized (connectionsMonitor) {\n- connectionsMonitor.notifyAll();\n- }\n- try {\n- socket.close();\n- } catch (IOException e) {\n- // ignore\n- }\n- onAfterServingSocket(socket);\n- }\n- }\n- });\n- }\n-\n- /**\n- * Requests that the server will be stopped after the given time delay. If the server is not\n- * started yet (and {@link #stop()} was not called yet, it will be started first.\n- * \n- * @param delay The delay.\n- * @param unit The time unit for the delay.\n- * @return A scheduled future that can be used to monitor progress / cancel the request. If there\n- * was a problem with stopping, an IOException is returned as the value (not thrown). If\n- * stop was already requested, {@code null} is returned.\n- */\n- public ScheduledFuture startThenStopAfter(long delay, TimeUnit unit) {\n- if (stopRequested.get()) {\n- return null;\n- }\n- synchronized (this) {\n- start();\n- ScheduledFuture existingFuture = this.timeoutFuture;\n- if (existingFuture != null) {\n- existingFuture.cancel(false);\n- this.timeoutFuture = null;\n- }\n-\n- return (this.timeoutFuture = TIMEOUTS.schedule(new Callable() {\n- @Override\n- public IOException call() throws Exception {\n- try {\n- stop();\n- return null;\n- } catch (IOException e) {\n- return e;\n- }\n- }\n- }, delay, unit));\n- }\n- }\n-\n- /**\n- * Called when a socket is ready to be served.\n- * \n- * @param socket The socket to serve.\n- * @throws IOException If there was an error.\n- */\n- protected abstract void doServeSocket(Socket socket) throws IOException;\n-\n- /**\n- * Called when the server is starting up.\n- */\n- protected void onServerStarting() {\n- }\n-\n- /**\n- * Called when the server has been bound to a socket.\n- * \n- * This is not called when you instantiated the server with a pre-bound socket.\n- * \n- * @param address The bound address.\n- */\n- protected void onServerBound(SocketAddress address) {\n- }\n-\n- /**\n- * Called when the server is ready to accept a new connection.\n- * \n- * @param activeCount The current number of active tasks (= serving sockets).\n- */\n- protected void onServerReady(int activeCount) {\n- }\n-\n- /**\n- * Called when the server is busy / not ready to accept a new connection.\n- * \n- * The frequency on how often this method is called when the server is busy is determined by\n- * {@link #getServerBusyTimeout()}.\n- * \n- * @param busyStartTime The time stamp since the server became busy.\n- */\n- protected void onServerBusy(long busyStartTime) {\n- }\n-\n- /**\n- * Called when the server has been stopped.\n- * \n- * @param socket The server's socket that stopped.\n- */\n- protected void onServerStopped(ServerSocket socket) {\n- }\n-\n- /**\n- * Called when a socket gets submitted into the process queue.\n- * \n- * @param socket The socket.\n- * @param submission The {@link Future} referencing the submission; it's \"done\" after the socket\n- * has been served.\n- */\n- protected void onSubmitted(Socket socket, Future submission) {\n- }\n-\n- /**\n- * Called when the server is shutting down.\n- */\n- protected void onServerShuttingDown() {\n- }\n-\n- /**\n- * Called when a {@link SocketException} was thrown during \"accept\".\n- * \n- * @param e The exception.\n- */\n- protected void onSocketExceptionDuringAccept(SocketException e) {\n- }\n-\n- /**\n- * Called when a {@link SocketException} was thrown during \"accept\".\n- * \n- * @param socket The socket.\n- * @param e The exception.\n- */\n- protected void onSocketExceptionAfterAccept(Socket socket, SocketException e) {\n- }\n-\n- /**\n- * Called before serving the socket.\n- * \n- * @param socket The socket.\n- */\n- protected void onBeforeServingSocket(Socket socket) {\n- }\n-\n- /**\n- * Called when an exception was thrown while serving a socket.\n- * \n- * @param socket The socket.\n- * @param e The exception.\n- */\n- protected void onServingException(Socket socket, Exception e) {\n- }\n-\n- /**\n- * Called after the socket has been served.\n- * \n- * @param socket The socket.\n- */\n- protected void onAfterServingSocket(Socket socket) {\n- }\n-\n- /**\n- * Called when an exception was thrown while listening on the server socket.\n- * \n- * @param e The exception.\n- */\n- protected void onListenException(Exception e) {\n- }\n }\ndiff --git a/junixsocket-server/src/main/java/org/newsclub/net/unix/server/SocketServer.java b/junixsocket-server/src/main/java/org/newsclub/net/unix/server/SocketServer.java\nnew file mode 100644\nindex 000000000..beba52017\n--- /dev/null\n+++ b/junixsocket-server/src/main/java/org/newsclub/net/unix/server/SocketServer.java\n@@ -0,0 +1,586 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.server;\n+\n+import java.io.IOException;\n+import java.io.InterruptedIOException;\n+import java.net.ServerSocket;\n+import java.net.Socket;\n+import java.net.SocketAddress;\n+import java.net.SocketException;\n+import java.net.SocketTimeoutException;\n+import java.util.Objects;\n+import java.util.concurrent.Callable;\n+import java.util.concurrent.ExecutorService;\n+import java.util.concurrent.Executors;\n+import java.util.concurrent.ForkJoinPool;\n+import java.util.concurrent.Future;\n+import java.util.concurrent.ScheduledExecutorService;\n+import java.util.concurrent.ScheduledFuture;\n+import java.util.concurrent.TimeUnit;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.newsclub.net.unix.AFServerSocket;\n+import org.newsclub.net.unix.AFSocketAddress;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * A base implementation for a simple, multi-threaded socket server.\n+ * \n+ * @author Christian Kohlschütter\n+ * @see AFSocketServer\n+ */\n+public abstract class SocketServer {\n+ private static final ScheduledExecutorService TIMEOUTS = Executors.newScheduledThreadPool(1);\n+\n+ private final @NonNull A listenAddress;\n+\n+ private int maxConcurrentConnections = Runtime.getRuntime().availableProcessors();\n+ private int serverTimeout = 0; // by default, the server doesn't timeout.\n+ private int socketTimeout = (int) TimeUnit.SECONDS.toMillis(60);\n+ private int serverBusyTimeout = (int) TimeUnit.SECONDS.toMillis(1);\n+\n+ private Thread listenThread = null;\n+ private V serverSocket;\n+ private final AtomicBoolean stopRequested = new AtomicBoolean(false);\n+ private final AtomicBoolean ready = new AtomicBoolean(false);\n+\n+ private final Object connectionsMonitor = new Object();\n+ private ForkJoinPool connectionPool;\n+\n+ private ScheduledFuture timeoutFuture;\n+ private final V reuseSocket;\n+\n+ /**\n+ * Creates a server using the given, bound {@link ServerSocket}.\n+ * \n+ * @param serverSocket The server socket to use (must be bound).\n+ */\n+ @SuppressWarnings({\"null\", \"unchecked\"})\n+ public SocketServer(V serverSocket) {\n+ this((A) Objects.requireNonNull(serverSocket).getLocalSocketAddress(), serverSocket);\n+ }\n+\n+ /**\n+ * Creates a server using the given {@link SocketAddress}.\n+ * \n+ * @param listenAddress The address to bind the socket on.\n+ */\n+ @SuppressWarnings(\"null\")\n+ public SocketServer(A listenAddress) {\n+ this(listenAddress, null);\n+ }\n+\n+ @SuppressWarnings(\"null\")\n+ private SocketServer(A listenAddress, V preboundSocket) {\n+ Objects.requireNonNull(listenAddress, \"listenAddress\");\n+ this.reuseSocket = preboundSocket;\n+\n+ this.listenAddress = listenAddress;\n+ }\n+\n+ /**\n+ * Returns the maximum number of concurrent connections.\n+ * \n+ * @return The maximum number of concurrent connections.\n+ */\n+ public int getMaxConcurrentConnections() {\n+ return maxConcurrentConnections;\n+ }\n+\n+ /**\n+ * Sets the maximum number of concurrent connections.\n+ * \n+ * @param maxConcurrentConnections The new maximum.\n+ */\n+ public void setMaxConcurrentConnections(int maxConcurrentConnections) {\n+ if (connectionPool != null) {\n+ throw new IllegalStateException(\"Already configured\");\n+ }\n+ this.maxConcurrentConnections = maxConcurrentConnections;\n+ }\n+\n+ /**\n+ * Returns the server timeout (in milliseconds).\n+ * \n+ * @return The server timeout in milliseconds (0 = no timeout).\n+ */\n+ public int getServerTimeout() {\n+ return serverTimeout;\n+ }\n+\n+ /**\n+ * Sets the server timeout (in milliseconds).\n+ * \n+ * @param timeout The new timeout in milliseconds (0 = no timeout).\n+ */\n+ public void setServerTimeout(int timeout) {\n+ synchronized (this) {\n+ if (serverSocket != null) {\n+ throw new IllegalStateException(\"Already configured\");\n+ }\n+ this.serverTimeout = timeout;\n+ }\n+ }\n+\n+ /**\n+ * Returns the socket timeout (in milliseconds).\n+ * \n+ * @return The socket timeout in milliseconds (0 = no timeout).\n+ */\n+ public int getSocketTimeout() {\n+ return socketTimeout;\n+ }\n+\n+ /**\n+ * Sets the socket timeout (in milliseconds).\n+ * \n+ * @param timeout The new timeout in milliseconds (0 = no timeout).\n+ */\n+ public void setSocketTimeout(int timeout) {\n+ this.socketTimeout = timeout;\n+ }\n+\n+ /**\n+ * Returns the server-busy timeout (in milliseconds).\n+ * \n+ * @return The server-busy timeout in milliseconds (0 = no timeout).\n+ */\n+ public int getServerBusyTimeout() {\n+ return serverBusyTimeout;\n+ }\n+\n+ /**\n+ * Sets the server-busy timeout (in milliseconds).\n+ * \n+ * @param timeout The new timeout in milliseconds (0 = no timeout).\n+ */\n+ public void setServerBusyTimeout(int timeout) {\n+ this.serverBusyTimeout = timeout;\n+ }\n+\n+ /**\n+ * Checks if the server is running.\n+ * \n+ * @return {@code true} if the server is alive.\n+ */\n+ public boolean isRunning() {\n+ synchronized (this) {\n+ return (listenThread != null && listenThread.isAlive());\n+ }\n+ }\n+\n+ /**\n+ * Checks if the server is running and accepting new connections.\n+ * \n+ * @return {@code true} if the server is alive and ready to accept new connections.\n+ */\n+ public boolean isReady() {\n+ return ready.get() && !stopRequested.get() && isRunning();\n+ }\n+\n+ /**\n+ * Starts the server, and returns immediately.\n+ * \n+ * @see #startAndWaitToBecomeReady(long, TimeUnit)\n+ */\n+ public void start() {\n+ synchronized (this) {\n+ if (isRunning()) {\n+ return;\n+ }\n+ if (connectionPool == null) {\n+ connectionPool = new ForkJoinPool(maxConcurrentConnections,\n+ ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);\n+ }\n+\n+ Thread t = new Thread(SocketServer.this.toString() + \" listening thread\") {\n+ @Override\n+ public void run() {\n+ try {\n+ listen();\n+ } catch (Exception e) {\n+ onListenException(e);\n+ }\n+ }\n+ };\n+ t.start();\n+\n+ listenThread = t;\n+ }\n+ }\n+\n+ /**\n+ * Starts the server and waits until it is ready or had to shop due to an error.\n+ * \n+ * @param duration The duration wait.\n+ * @param unit The duration's time unit.\n+ * @return {@code true} if the server is ready to serve requests.\n+ * @throws InterruptedException If the wait was interrupted.\n+ */\n+ public boolean startAndWaitToBecomeReady(long duration, TimeUnit unit)\n+ throws InterruptedException {\n+ synchronized (this) {\n+ start();\n+ long timeStart = System.currentTimeMillis();\n+ while (duration > 0) {\n+ if (isReady()) {\n+ return true;\n+ }\n+ this.wait(unit.toMillis(duration));\n+ duration -= (System.currentTimeMillis() - timeStart);\n+ }\n+ return isReady();\n+ }\n+ }\n+\n+ /**\n+ * Returns a new server socket.\n+ * \n+ * @return The new socket (an {@link AFServerSocket} if the listen address is an\n+ * {@link AFSocketAddress}).\n+ * @throws IOException on error.\n+ */\n+ protected abstract V newServerSocket() throws IOException;\n+\n+ @SuppressWarnings(\"null\")\n+ private void listen() throws IOException {\n+ V server;\n+\n+ synchronized (this) {\n+ if (reuseSocket != null) {\n+ serverSocket = reuseSocket;\n+ } else {\n+ if (serverSocket != null) {\n+ throw new IllegalStateException(\"The server is already listening\");\n+ }\n+ serverSocket = newServerSocket();\n+ }\n+ server = serverSocket;\n+ }\n+ onServerStarting();\n+\n+ try {\n+ if (!server.isBound()) {\n+ server.bind(listenAddress);\n+ onServerBound(listenAddress);\n+ }\n+ server.setSoTimeout(serverTimeout);\n+\n+ acceptLoop(server);\n+ } catch (SocketException e) {\n+ onSocketExceptionDuringAccept(e);\n+ } finally {\n+ stop();\n+ onServerStopped(server);\n+ }\n+ }\n+\n+ @SuppressWarnings(\"PMD.CognitiveComplexity\")\n+ @SuppressFBWarnings(\"NN_NAKED_NOTIFY\")\n+ private void acceptLoop(V server) throws IOException {\n+ long busyStartTime = 0;\n+ acceptLoop : while (!stopRequested.get() && !Thread.interrupted()) {\n+ try {\n+ while (!stopRequested.get() && connectionPool\n+ .getActiveThreadCount() >= maxConcurrentConnections) {\n+ if (busyStartTime == 0) {\n+ busyStartTime = System.currentTimeMillis();\n+ }\n+ onServerBusy(busyStartTime);\n+\n+ synchronized (connectionsMonitor) {\n+ try {\n+ connectionsMonitor.wait(serverBusyTimeout);\n+ } catch (InterruptedException e) {\n+ throw (InterruptedIOException) new InterruptedIOException(\n+ \"Interrupted while waiting on server resources\").initCause(e);\n+ }\n+ }\n+ }\n+ busyStartTime = 0;\n+\n+ if (stopRequested.get() || server == null) {\n+ break;\n+ }\n+\n+ synchronized (SocketServer.this) {\n+ SocketServer.this.notifyAll();\n+ }\n+ ready.set(true);\n+ onServerReady(connectionPool.getActiveThreadCount());\n+\n+ final S socket;\n+ try {\n+ @SuppressWarnings(\"unchecked\")\n+ S theSocket = (S) server.accept();\n+ socket = theSocket;\n+ } catch (SocketException e) {\n+ if (server.isClosed()) {\n+ // already closed, ignore\n+ break acceptLoop;\n+ } else {\n+ throw e;\n+ }\n+ }\n+ try {\n+ socket.setSoTimeout(socketTimeout);\n+ } catch (SocketException e) {\n+ // Connection closed before we could do anything\n+ onSocketExceptionAfterAccept(socket, e);\n+ socket.close();\n+\n+ continue acceptLoop;\n+ }\n+\n+ onSubmitted(socket, submit(socket, connectionPool));\n+ } catch (SocketTimeoutException e) {\n+ if (!connectionPool.isQuiescent()) {\n+ continue acceptLoop;\n+ } else {\n+ onServerShuttingDown();\n+ connectionPool.shutdown();\n+ break acceptLoop;\n+ }\n+ }\n+ }\n+ }\n+\n+ /**\n+ * Stops the server.\n+ * \n+ * @throws IOException If there was an error.\n+ */\n+ @SuppressWarnings(\"null\")\n+ @SuppressFBWarnings(\"NN_NAKED_NOTIFY\")\n+ public void stop() throws IOException {\n+ stopRequested.set(true);\n+ ready.set(false);\n+\n+ synchronized (this) {\n+ V theServerSocket = serverSocket;\n+ serverSocket = null;\n+ try {\n+ if (theServerSocket == null) {\n+ return;\n+ }\n+ ScheduledFuture future = this.timeoutFuture;\n+ if (future != null) {\n+ future.cancel(false);\n+ this.timeoutFuture = null;\n+ }\n+\n+ theServerSocket.close();\n+ } finally {\n+ SocketServer.this.notifyAll();\n+ }\n+ }\n+ }\n+\n+ private Future submit(final S socket, ExecutorService executor) {\n+ Objects.requireNonNull(socket);\n+ return executor.submit(new Runnable() {\n+ @Override\n+ public void run() {\n+ onBeforeServingSocket(socket);\n+\n+ try { // NOPMD\n+ doServeSocket(socket);\n+ } catch (Exception e) {\n+ onServingException(socket, e);\n+ } finally {\n+ // Notify the server's accept thread that we handled the connection\n+ synchronized (connectionsMonitor) {\n+ connectionsMonitor.notifyAll();\n+ }\n+ try {\n+ socket.close();\n+ } catch (IOException e) {\n+ // ignore\n+ }\n+ onAfterServingSocket(socket);\n+ }\n+ }\n+ });\n+ }\n+\n+ /**\n+ * Requests that the server will be stopped after the given time delay. If the server is not\n+ * started yet (and {@link #stop()} was not called yet, it will be started first.\n+ * \n+ * @param delay The delay.\n+ * @param unit The time unit for the delay.\n+ * @return A scheduled future that can be used to monitor progress / cancel the request. If there\n+ * was a problem with stopping, an IOException is returned as the value (not thrown). If\n+ * stop was already requested, {@code null} is returned.\n+ */\n+ public ScheduledFuture startThenStopAfter(long delay, TimeUnit unit) {\n+ if (stopRequested.get()) {\n+ return null;\n+ }\n+ synchronized (this) {\n+ start();\n+ ScheduledFuture existingFuture = this.timeoutFuture;\n+ if (existingFuture != null) {\n+ existingFuture.cancel(false);\n+ this.timeoutFuture = null;\n+ }\n+\n+ return (this.timeoutFuture = TIMEOUTS.schedule(new Callable() {\n+ @SuppressFBWarnings(\"THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION\")\n+ @Override\n+ public IOException call() throws Exception {\n+ try {\n+ stop();\n+ return null;\n+ } catch (IOException e) {\n+ return e;\n+ }\n+ }\n+ }, delay, unit));\n+ }\n+ }\n+\n+ /**\n+ * Called when a socket is ready to be served.\n+ * \n+ * @param socket The socket to serve.\n+ * @throws IOException If there was an error.\n+ */\n+ protected abstract void doServeSocket(S socket) throws IOException;\n+\n+ /**\n+ * Called when the server is starting up.\n+ */\n+ protected void onServerStarting() {\n+ }\n+\n+ /**\n+ * Called when the server has been bound to a socket.\n+ * \n+ * This is not called when you instantiated the server with a pre-bound socket.\n+ * \n+ * @param address The bound address.\n+ */\n+ protected void onServerBound(A address) {\n+ }\n+\n+ /**\n+ * Called when the server is ready to accept a new connection.\n+ * \n+ * @param activeCount The current number of active tasks (= serving sockets).\n+ */\n+ protected void onServerReady(int activeCount) {\n+ }\n+\n+ /**\n+ * Called when the server is busy / not ready to accept a new connection.\n+ * \n+ * The frequency on how often this method is called when the server is busy is determined by\n+ * {@link #getServerBusyTimeout()}.\n+ * \n+ * @param busyStartTime The time stamp since the server became busy.\n+ */\n+ protected void onServerBusy(long busyStartTime) {\n+ }\n+\n+ /**\n+ * Called when the server has been stopped.\n+ * \n+ * @param socket The server's socket that stopped.\n+ */\n+ protected void onServerStopped(V socket) {\n+ }\n+\n+ /**\n+ * Called when a socket gets submitted into the process queue.\n+ * \n+ * @param socket The socket.\n+ * @param submission The {@link Future} referencing the submission; it's \"done\" after the socket\n+ * has been served.\n+ */\n+ protected void onSubmitted(S socket, Future submission) {\n+ }\n+\n+ /**\n+ * Called when the server is shutting down.\n+ */\n+ protected void onServerShuttingDown() {\n+ }\n+\n+ /**\n+ * Called when a {@link SocketException} was thrown during \"accept\".\n+ * \n+ * @param e The exception.\n+ */\n+ protected void onSocketExceptionDuringAccept(SocketException e) {\n+ }\n+\n+ /**\n+ * Called when a {@link SocketException} was thrown during \"accept\".\n+ * \n+ * @param socket The socket.\n+ * @param e The exception.\n+ */\n+ protected void onSocketExceptionAfterAccept(S socket, SocketException e) {\n+ }\n+\n+ /**\n+ * Called before serving the socket.\n+ * \n+ * @param socket The socket.\n+ */\n+ protected void onBeforeServingSocket(S socket) {\n+ }\n+\n+ /**\n+ * Called when an exception was thrown while serving a socket.\n+ * \n+ * @param socket The socket.\n+ * @param e The exception.\n+ */\n+ protected void onServingException(S socket, Exception e) {\n+ }\n+\n+ /**\n+ * Called after the socket has been served.\n+ * \n+ * @param socket The socket.\n+ */\n+ protected void onAfterServingSocket(S socket) {\n+ }\n+\n+ /**\n+ * Called when an exception was thrown while listening on the server socket.\n+ * \n+ * @param e The exception.\n+ */\n+ protected void onListenException(Exception e) {\n+ }\n+\n+ /**\n+ * Returns the address the server listens to.\n+ * \n+ * @return The listen address.\n+ */\n+ protected @NonNull A getListenAddress() {\n+ return listenAddress;\n+ }\n+}\ndiff --git a/junixsocket-tipc/junixsocket-common b/junixsocket-tipc/junixsocket-common\nnew file mode 120000\nindex 000000000..827c6ce52\n--- /dev/null\n+++ b/junixsocket-tipc/junixsocket-common\n@@ -0,0 +1 @@\n+../junixsocket-common\n\\ No newline at end of file\ndiff --git a/junixsocket-tipc/pom.xml b/junixsocket-tipc/pom.xml\nnew file mode 100644\nindex 000000000..3f39bafc6\n--- /dev/null\n+++ b/junixsocket-tipc/pom.xml\n@@ -0,0 +1,79 @@\n+\n+\n+ 4.0.0\n+ junixsocket-tipc\n+ jar\n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-parent\n+ 2.5.0-SNAPSHOT\n+ ../pom.xml\n+ \n+ junixsocket-tipc\n+ \n+ ${project.parent.basedir}\n+\n+ 8\n+\n+ org.newsclub.net.unix=${project.basedir}/../junixsocket-common/${kohlschutter.target.name}/test-classes:${settings.localRepository}/com/kohlschutter/junixsocket/junixsocket-common/${project.version}/junixsocket-common-${project.version}-tests.jar\n+\n+ \n+ \n+ --patch-module ${patchArgs.org.newsclub.net.unix}\n+ \n+\n+ The junixsocket implementation for AF_TIPC sockets\n+\n+ \n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-common\n+ ${project.version}\n+ test-jar\n+ test\n+ tests\n+ \n+ \n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-common\n+ ${project.version}\n+ \n+\n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-native-common\n+ ${project.version}\n+ test\n+ \n+ \n+ com.kohlschutter.junixsocket\n+ junixsocket-native-custom\n+ ${project.version}\n+ test\n+ default\n+ \n+ \n+ \n+ \n+ \n+ maven-compiler-plugin\n+ \n+ \n+ default-testCompile\n+ test-compile\n+ \n+ \n+ --patch-module\n+ ${patchArgs.org.newsclub.net.unix}\n+ \n+ \n+ \n+ \n+ \n+ \n+ \n+\n\\ No newline at end of file\ndiff --git a/junixsocket-tipc/src/main/java/module-info.java b/junixsocket-tipc/src/main/java/module-info.java\nnew file mode 100644\nindex 000000000..5c88ee1f5\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/module-info.java\n@@ -0,0 +1,10 @@\n+/**\n+ * The junixsocket implementation for AF_TIPC sockets.\n+ */\n+module org.newsclub.net.unix.tipc {\n+ exports org.newsclub.net.unix.tipc;\n+\n+ requires transitive org.newsclub.net.unix;\n+ requires static com.kohlschutter.annotations.compiletime;\n+ requires static org.eclipse.jdt.annotation;\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDatagramChannel.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDatagramChannel.java\nnew file mode 100644\nindex 000000000..9b3fcedb0\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDatagramChannel.java\n@@ -0,0 +1,70 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.IOException;\n+import java.net.ProtocolFamily;\n+import java.nio.channels.DatagramChannel;\n+\n+import org.newsclub.net.unix.AFDatagramChannel;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+\n+/**\n+ * A {@link DatagramChannel} implementation that works with {@code AF_TIPC} sockets.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public final class AFTIPCDatagramChannel extends AFDatagramChannel implements\n+ AFTIPCSocketExtensions {\n+ AFTIPCDatagramChannel(AFTIPCDatagramSocket socket) {\n+ super(AFTIPCSelectorProvider.getInstance(), socket);\n+ }\n+\n+ /**\n+ * Opens a datagram channel.\n+ *\n+ * @return The new channel\n+ * @throws IOException if an I/O error occurs\n+ */\n+ public static AFTIPCDatagramChannel open() throws IOException {\n+ return AFTIPCSelectorProvider.provider().openDatagramChannel();\n+ }\n+\n+ /**\n+ * Opens a datagram channel.\n+ *\n+ * @param family The protocol family\n+ * @return A new datagram channel\n+ *\n+ * @throws UnsupportedOperationException if the specified protocol family is not supported\n+ * @throws IOException if an I/O error occurs\n+ */\n+ public static AFTIPCDatagramChannel open(ProtocolFamily family) throws IOException {\n+ return AFTIPCSelectorProvider.provider().openDatagramChannel(family);\n+ }\n+\n+ @Override\n+ public AFTIPCErrInfo getErrInfo() {\n+ return ((AFTIPCSocketExtensions) getAFSocket()).getErrInfo();\n+ }\n+\n+ @Override\n+ public AFTIPCDestName getDestName() {\n+ return ((AFTIPCSocketExtensions) getAFSocket()).getDestName();\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDatagramSocket.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDatagramSocket.java\nnew file mode 100644\nindex 000000000..37824d301\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDatagramSocket.java\n@@ -0,0 +1,92 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.net.DatagramSocket;\n+\n+import org.newsclub.net.unix.AFDatagramSocket;\n+import org.newsclub.net.unix.AFSocketType;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+import org.newsclub.net.unix.AFTIPCSocketImplExtensions;\n+\n+/**\n+ * A {@link DatagramSocket} implementation that works with {@code AF_TIPC} sockets.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public final class AFTIPCDatagramSocket extends AFDatagramSocket implements\n+ AFTIPCSocketExtensions {\n+ /**\n+ * The maximum size for user messages.\n+ */\n+ public static final int TIPC_MAX_USER_MSG_SIZE = 66000;\n+\n+ AFTIPCDatagramSocket(FileDescriptor fd) throws IOException {\n+ this(fd, AFSocketType.SOCK_DGRAM);\n+ }\n+\n+ AFTIPCDatagramSocket(FileDescriptor fd, AFSocketType socketType) throws IOException {\n+ super(new AFTIPCDatagramSocketImpl(fd, socketType));\n+ }\n+\n+ @Override\n+ protected AFTIPCDatagramChannel newChannel() {\n+ return new AFTIPCDatagramChannel(this);\n+ }\n+\n+ /**\n+ * Returns a new {@link AFTIPCDatagramSocket} instance, using the default\n+ * {@link AFSocketType#SOCK_DGRAM} socket type.\n+ * \n+ * @return The new instance.\n+ * @throws IOException on error.\n+ */\n+ public static AFTIPCDatagramSocket newInstance() throws IOException {\n+ return (AFTIPCDatagramSocket) newInstance(AFTIPCDatagramSocket::new);\n+ }\n+\n+ /**\n+ * Returns a new {@link AFTIPCDatagramSocket} instance for the given socket type.\n+ * \n+ * @param socketType The socket type.\n+ * @return The new instance.\n+ * @throws IOException on error.\n+ */\n+ public static AFTIPCDatagramSocket newInstance(AFSocketType socketType) throws IOException {\n+ return (AFTIPCDatagramSocket) newInstance((fd) -> {\n+ return new AFTIPCDatagramSocket(fd, socketType);\n+ });\n+ }\n+\n+ @Override\n+ public AFTIPCDatagramChannel getChannel() {\n+ return (AFTIPCDatagramChannel) super.getChannel();\n+ }\n+\n+ @Override\n+ public AFTIPCErrInfo getErrInfo() {\n+ return AFTIPCErrInfo.of(((AFTIPCSocketImplExtensions) getImplExtensions()).getTIPCErrInfo());\n+ }\n+\n+ @Override\n+ public AFTIPCDestName getDestName() {\n+ return AFTIPCDestName.of(((AFTIPCSocketImplExtensions) getImplExtensions()).getTIPCDestName());\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDatagramSocketImpl.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDatagramSocketImpl.java\nnew file mode 100644\nindex 000000000..2ae3768d4\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDatagramSocketImpl.java\n@@ -0,0 +1,32 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+\n+import org.newsclub.net.unix.AFDatagramSocketImpl;\n+import org.newsclub.net.unix.AFSocketType;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+\n+final class AFTIPCDatagramSocketImpl extends AFDatagramSocketImpl {\n+ protected AFTIPCDatagramSocketImpl(FileDescriptor fd, AFSocketType socketType)\n+ throws IOException {\n+ super(AFTIPCSelectorProvider.AF_TIPC, fd, socketType);\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDestName.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDestName.java\nnew file mode 100644\nindex 000000000..e4fe275d8\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCDestName.java\n@@ -0,0 +1,133 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.Serializable;\n+import java.net.SocketException;\n+\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+import org.newsclub.net.unix.AFTIPCSocketAddress.Scope;\n+\n+/**\n+ * The TIPC-specific DestName response that may be included as ancillary data.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public final class AFTIPCDestName implements Serializable {\n+ private static final long serialVersionUID = 1L;\n+ /**\n+ * Type value.\n+ */\n+ private final int type;\n+\n+ /**\n+ * Lower service range value.\n+ */\n+ private final int lower;\n+\n+ /**\n+ * Upper service range value.\n+ */\n+ private final int upper;\n+\n+ /**\n+ * Creates a new instance.\n+ * \n+ * @param type The \"type\" value.\n+ * @param lower The \"lower\" service range value (or the service \"instance\" if {@code lower} and\n+ * {@code upper} are the same).\n+ * @param upper The \"upper\" service range value (or the service \"instance\" if {@code lower} and\n+ * {@code upper} are the same).\n+ */\n+ public AFTIPCDestName(int type, int lower, int upper) {\n+ this.type = type;\n+ this.lower = lower;\n+ this.upper = upper;\n+ }\n+\n+ /**\n+ * Returns the \"type\" value.\n+ * \n+ * @return The type.\n+ */\n+ public int getType() {\n+ return type;\n+ }\n+\n+ /**\n+ * Returns the \"lower\" value of the service range (or the service \"instance\" if identical to the\n+ * upper value).\n+ * \n+ * @return The lower value.\n+ */\n+ public int getLower() {\n+ return lower;\n+ }\n+\n+ /**\n+ * Returns the \"upper\" value of the service range (or the service \"instance\" if identical to the\n+ * lower value).\n+ * \n+ * @return The upper value.\n+ */\n+ public int getUpper() {\n+ return upper;\n+ }\n+\n+ /**\n+ * Checks if this DestName describes a service range (as opposed to a service) address.\n+ * \n+ * @return {@code true} if the {@link #getLower()} value is different from the {@link #getUpper()}\n+ * value.\n+ */\n+ public boolean isServiceRange() {\n+ return lower != upper;\n+ }\n+\n+ /**\n+ * Converts this DestName to a proper {@link AFTIPCSocketAddress}, by using the given\n+ * {@link Scope} (which is otherwise not included).\n+ * \n+ * @param scope The scope to use.\n+ * @param alwaysRange If {@code true}, a service range address is even returned when a service\n+ * address would suffice.\n+ * @return The address.\n+ */\n+ public AFTIPCSocketAddress toSocketAddress(Scope scope, boolean alwaysRange) {\n+ try {\n+ if (alwaysRange || isServiceRange()) {\n+ return AFTIPCSocketAddress.ofServiceRange(scope, type, lower, upper);\n+ } else {\n+ return AFTIPCSocketAddress.ofService(scope, type, lower);\n+ }\n+ } catch (SocketException e) {\n+ throw new IllegalStateException(e);\n+ }\n+ }\n+\n+ @SuppressWarnings(\"PMD.ShortMethodName\")\n+ static AFTIPCDestName of(int[] tipcDestName) {\n+ if (tipcDestName == null) {\n+ return null;\n+ }\n+ if (tipcDestName.length != 3) {\n+ throw new IllegalArgumentException();\n+ }\n+ return new AFTIPCDestName(tipcDestName[0], tipcDestName[1], tipcDestName[2]);\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCErrInfo.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCErrInfo.java\nnew file mode 100644\nindex 000000000..ae1677c3f\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCErrInfo.java\n@@ -0,0 +1,174 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.Serializable;\n+import java.util.Objects;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.NonNullByDefault;\n+import org.newsclub.net.unix.NamedInteger;\n+\n+/**\n+ * The TIPC-specific error info response that may be included as ancillary data.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public final class AFTIPCErrInfo implements Serializable {\n+ private static final long serialVersionUID = 1L;\n+\n+ /**\n+ * Error code.\n+ */\n+ private final ErrorCode errorCode;\n+\n+ /**\n+ * The length of the returned data.\n+ */\n+ private final int dataLength;\n+\n+ /**\n+ * Some TIPC error code.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+ @NonNullByDefault\n+ public static final class ErrorCode extends NamedInteger {\n+ private static final long serialVersionUID = 1L;\n+\n+ /**\n+ * No error.\n+ */\n+ public static final ErrorCode TIPC_OK;\n+\n+ /**\n+ * Destination port name is unknown.\n+ */\n+ public static final ErrorCode TIPC_ERR_NO_NAME;\n+\n+ /**\n+ * Destination port id does not exist.\n+ */\n+ public static final ErrorCode TIPC_ERR_NO_PORT;\n+\n+ /**\n+ * Destination node is unreachable.\n+ */\n+ public static final ErrorCode TIPC_ERR_NO_NODE;\n+\n+ /**\n+ * Destination is congested.\n+ */\n+ public static final ErrorCode TIPC_ERR_OVERLOAD;\n+\n+ /**\n+ * Normal connection shutdown occurred.\n+ */\n+ public static final ErrorCode TIPC_ERR_CONN_SHUTDOWN;\n+\n+ private static final @NonNull ErrorCode[] VALUES = init(new @NonNull ErrorCode[] {\n+ TIPC_OK = new ErrorCode(\"TIPC_OK\", 0), //\n+ TIPC_ERR_NO_NAME = new ErrorCode(\"TIPC_ERR_NO_NAME\", 1), //\n+ TIPC_ERR_NO_PORT = new ErrorCode(\"TIPC_ERR_NO_PORT\", 2), //\n+ TIPC_ERR_NO_NODE = new ErrorCode(\"TIPC_ERR_NO_NODE\", 3), //\n+ TIPC_ERR_OVERLOAD = new ErrorCode(\"TIPC_ERR_OVERLOAD\", 4), //\n+ TIPC_ERR_CONN_SHUTDOWN = new ErrorCode(\"TIPC_ERR_CONN_SHUTDOWN\", 5), //\n+ });\n+\n+ private ErrorCode(int id) {\n+ super(id);\n+ }\n+\n+ private ErrorCode(String name, int id) {\n+ super(name, id);\n+ }\n+\n+ /**\n+ * Returns an {@link ErrorCode} instance given an integer.\n+ * \n+ * @param v The value.\n+ * @return The instance.\n+ */\n+ public static ErrorCode ofValue(int v) {\n+ return ofValue(VALUES, ErrorCode::new, v);\n+ }\n+ }\n+\n+ /**\n+ * Creates a new instance.\n+ * \n+ * @param errorCode The error code.\n+ * @param dataLength The length of the returned data.\n+ */\n+ public AFTIPCErrInfo(ErrorCode errorCode, int dataLength) {\n+ this.errorCode = errorCode;\n+ this.dataLength = dataLength;\n+ }\n+\n+ /**\n+ * Returns the error code.\n+ * \n+ * @return The error code.\n+ */\n+ public ErrorCode getErrorCode() {\n+ return errorCode;\n+ }\n+\n+ /**\n+ * The length of the corresponding data.\n+ * \n+ * @return The length in bytes.\n+ */\n+ public int getDataLength() {\n+ return dataLength;\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return getClass().getName() + \"(\" + errorCode + \";dataLength=\" + dataLength + \")\";\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return Objects.hash(dataLength, errorCode);\n+ }\n+\n+ @Override\n+ public boolean equals(Object obj) {\n+ if (this == obj) {\n+ return true;\n+ } else if (obj == null) {\n+ return false;\n+ } else if (getClass() != obj.getClass()) {\n+ return false;\n+ }\n+ AFTIPCErrInfo other = (AFTIPCErrInfo) obj;\n+ return dataLength == other.dataLength && errorCode.equals(other.errorCode);\n+ }\n+\n+ @SuppressWarnings(\"PMD.ShortMethodName\")\n+ static AFTIPCErrInfo of(int[] tipcErrInfo) {\n+ if (tipcErrInfo == null) {\n+ return null;\n+ }\n+ if (tipcErrInfo.length != 2) {\n+ throw new IllegalArgumentException();\n+ }\n+ return new AFTIPCErrInfo(ErrorCode.ofValue(tipcErrInfo[0]), tipcErrInfo[1]);\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCGroupRequest.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCGroupRequest.java\nnew file mode 100644\nindex 000000000..bf88aaefc\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCGroupRequest.java\n@@ -0,0 +1,200 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.NonNullByDefault;\n+import org.eclipse.jdt.annotation.Nullable;\n+import org.newsclub.net.unix.AFTIPCSocketAddress.Scope;\n+import org.newsclub.net.unix.NamedIntegerBitmask;\n+\n+/**\n+ * A TIPC group request.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+@NonNullByDefault\n+public final class AFTIPCGroupRequest {\n+ /**\n+ * \"No group\".\n+ */\n+ public static final AFTIPCGroupRequest NONE = new AFTIPCGroupRequest(0, 0,\n+ Scope.SCOPE_NOT_SPECIFIED, GroupRequestFlags.NONE);\n+\n+ private final int type;\n+ private final int instance;\n+ private final Scope scope;\n+ private final GroupRequestFlags flags;\n+\n+ /**\n+ * Some flags used in the group request.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+ public static final class GroupRequestFlags extends NamedIntegerBitmask {\n+ private static final long serialVersionUID = 1L;\n+\n+ /**\n+ * No flags set.\n+ */\n+ public static final GroupRequestFlags NONE = new GroupRequestFlags(\"NONE\", 0);\n+\n+ /**\n+ * Receive copies of sent messages.\n+ */\n+ public static final GroupRequestFlags GROUP_LOOPBACK;\n+\n+ /**\n+ * Receive membership events.\n+ */\n+ public static final GroupRequestFlags GROUP_MEMBER_EVTS;\n+\n+ private static final @NonNull GroupRequestFlags[] VALUES = {\n+ GROUP_LOOPBACK = new GroupRequestFlags(\"GROUP_LOOPBACK\", 1), //\n+ GROUP_MEMBER_EVTS = new GroupRequestFlags(\"GROUP_MEMBER_EVTS\", 2), //\n+ };\n+\n+ private GroupRequestFlags(@Nullable String name, int flags) {\n+ super(name, flags);\n+ }\n+\n+ /**\n+ * Returns a {@link GroupRequestFlags} instance given an integer value.\n+ * \n+ * @param v The value.\n+ * @return The instance.\n+ */\n+ public static GroupRequestFlags ofValue(int v) {\n+ return resolve(VALUES, NONE, GroupRequestFlags::new, v);\n+ }\n+\n+ /**\n+ * Returns a {@link GroupRequestFlags} instance representing the combination of the given list\n+ * of {@link GroupRequestFlags} flags.\n+ * \n+ * @param flags The flags (zero or more values).\n+ * @return The instance.\n+ */\n+ public static GroupRequestFlags withFlags(@NonNull GroupRequestFlags... flags) {\n+ return resolve(VALUES, NONE, GroupRequestFlags::new, flags);\n+ }\n+\n+ /**\n+ * Combines the given {@link GroupRequestFlags} instance with another one.\n+ * \n+ * @param other The other instance.\n+ * @return The combined instance.\n+ */\n+ @Override\n+ public GroupRequestFlags combineWith(GroupRequestFlags other) {\n+ return combineWith(VALUES, NONE, GroupRequestFlags::new, other);\n+ }\n+ }\n+\n+ private AFTIPCGroupRequest(int type, int instance, Scope scope, GroupRequestFlags flags) {\n+ this.type = type;\n+ this.instance = instance;\n+ this.scope = scope;\n+ this.flags = flags;\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCGroupRequest} instance using the given parameters.\n+ * \n+ * @param type The group type.\n+ * @param instance The group instance.\n+ * @param scope The group scope.\n+ * @param flags The request flags.\n+ * @return The instance.\n+ */\n+ public static AFTIPCGroupRequest with(int type, int instance, Scope scope,\n+ GroupRequestFlags flags) {\n+ if (type == 0 && instance == 0 && scope.value() == 0 && flags.value() == 0) {\n+ return NONE;\n+ } else {\n+ return new AFTIPCGroupRequest(type, instance, scope, flags);\n+ }\n+ }\n+\n+ /**\n+ * Returns an {@link AFTIPCGroupRequest} instance using the given parameters, implying cluster\n+ * scope.\n+ * \n+ * @param type The group type.\n+ * @param instance The group instance.\n+ * @param flags The request flags.\n+ * @return The instance.\n+ */\n+ public static AFTIPCGroupRequest with(int type, int instance, GroupRequestFlags flags) {\n+ return with(type, instance, Scope.SCOPE_CLUSTER, flags);\n+ }\n+\n+ static AFTIPCGroupRequest fromNative(int type, int instance, int scopeId, int flags) {\n+ return with(type, instance, Scope.ofValue(scopeId), GroupRequestFlags.ofValue(flags));\n+ }\n+\n+ /**\n+ * Returns the group type.\n+ * \n+ * @return The group type.\n+ */\n+ public int getType() {\n+ return type;\n+ }\n+\n+ /**\n+ * Returns the group instance.\n+ * \n+ * @return The group instance.\n+ */\n+ public int getInstance() {\n+ return instance;\n+ }\n+\n+ /**\n+ * Returns the group scope.\n+ * \n+ * @return The group scope.\n+ */\n+ public Scope getScope() {\n+ return scope;\n+ }\n+\n+ int getScopeId() {\n+ return scope.value();\n+ }\n+\n+ int getFlagsValue() {\n+ return flags.value();\n+ }\n+\n+ /**\n+ * Returns the group request flags.\n+ * \n+ * @return The group request flags.\n+ */\n+ public GroupRequestFlags getFlags() {\n+ return flags;\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return getClass().getName() + ((this == NONE) ? \"(no group)\" : \"(type=\" + type + \";instance=\"\n+ + instance + \";scope=\" + scope + \";flags=\" + flags + \")\");\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCProtocolFamily.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCProtocolFamily.java\nnew file mode 100644\nindex 000000000..9d859d1d5\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCProtocolFamily.java\n@@ -0,0 +1,32 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.net.ProtocolFamily;\n+\n+/**\n+ * Describes the protocol families supported by junixsocket-tipc.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public enum AFTIPCProtocolFamily implements ProtocolFamily {\n+ /**\n+ * TIPC.\n+ */\n+ TIPC;\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSelectorProvider.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSelectorProvider.java\nnew file mode 100644\nindex 000000000..f15a24e34\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSelectorProvider.java\n@@ -0,0 +1,187 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.IOException;\n+import java.net.ProtocolFamily;\n+import java.net.SocketAddress;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.newsclub.net.unix.AFAddressFamily;\n+import org.newsclub.net.unix.AFAddressFamilyConfig;\n+import org.newsclub.net.unix.AFDatagramChannel;\n+import org.newsclub.net.unix.AFDatagramSocket;\n+import org.newsclub.net.unix.AFSelectorProvider;\n+import org.newsclub.net.unix.AFServerSocket;\n+import org.newsclub.net.unix.AFServerSocketChannel;\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.AFSocketChannel;\n+import org.newsclub.net.unix.AFSocketPair;\n+import org.newsclub.net.unix.AFSomeSocket;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * Service-provider class for junixsocket selectors and selectable channels.\n+ */\n+public final class AFTIPCSelectorProvider extends AFSelectorProvider {\n+ private static final AFTIPCSelectorProvider INSTANCE = new AFTIPCSelectorProvider();\n+ @SuppressWarnings(\"null\")\n+ static final AFAddressFamily<@NonNull AFTIPCSocketAddress> AF_TIPC = AFAddressFamily\n+ .registerAddressFamilyImpl(\"tipc\", AFTIPCSocketAddress.addressFamily(),\n+ new AFAddressFamilyConfig() {\n+\n+ @Override\n+ protected Class> socketClass() {\n+ return AFTIPCSocket.class;\n+ }\n+\n+ @Override\n+ protected AFSocket.Constructor socketConstructor() {\n+ return AFTIPCSocket::new;\n+ }\n+\n+ @Override\n+ protected Class> serverSocketClass() {\n+ return AFTIPCServerSocket.class;\n+ }\n+\n+ @Override\n+ protected AFServerSocket.Constructor serverSocketConstructor() {\n+ return AFTIPCServerSocket::new;\n+ }\n+\n+ @Override\n+ protected Class> socketChannelClass() {\n+ return AFTIPCSocketChannel.class;\n+ }\n+\n+ @Override\n+ protected Class> serverSocketChannelClass() {\n+ return AFTIPCServerSocketChannel.class;\n+ }\n+\n+ @Override\n+ protected Class> datagramSocketClass() {\n+ return AFTIPCDatagramSocket.class;\n+ }\n+\n+ @Override\n+ protected AFDatagramSocket.Constructor datagramSocketConstructor() {\n+ return AFTIPCDatagramSocket::new;\n+ }\n+\n+ @Override\n+ protected Class> datagramChannelClass() {\n+ return AFTIPCDatagramChannel.class;\n+ }\n+ });\n+\n+ private AFTIPCSelectorProvider() {\n+ super();\n+ }\n+\n+ /**\n+ * Returns the singleton instance.\n+ * \n+ * @return The instance.\n+ */\n+ @SuppressFBWarnings(\"MS_EXPOSE_REP\")\n+ public static AFTIPCSelectorProvider getInstance() {\n+ return INSTANCE;\n+ }\n+\n+ /**\n+ * Returns the singleton instance.\n+ * \n+ * @return The instance.\n+ */\n+ public static AFTIPCSelectorProvider provider() {\n+ return getInstance();\n+ }\n+\n+ /**\n+ * Constructs a new socket pair from two sockets.\n+ * \n+ * @param s1 Some socket, the first one.\n+ * @param s2 Some socket, the second one.\n+ * @return The pair.\n+ */\n+ @Override\n+ protected

AFSocketPair

newSocketPair(P s1, P s2) {\n+ return new AFTIPCSocketPair

(s1, s2);\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ @Override\n+ public AFTIPCSocketPair openSocketChannelPair() throws IOException {\n+ return (AFTIPCSocketPair) super.openSocketChannelPair();\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ @Override\n+ public AFTIPCSocketPair openDatagramChannelPair() throws IOException {\n+ return (AFTIPCSocketPair) super.openDatagramChannelPair();\n+ }\n+\n+ @Override\n+ protected AFTIPCSocket newSocket() throws IOException {\n+ return AFTIPCSocket.newInstance();\n+ }\n+\n+ @Override\n+ public AFTIPCDatagramChannel openDatagramChannel() throws IOException {\n+ return AFTIPCDatagramSocket.newInstance().getChannel();\n+ }\n+\n+ @Override\n+ public AFTIPCDatagramChannel openDatagramChannel(ProtocolFamily family) throws IOException {\n+ return (AFTIPCDatagramChannel) super.openDatagramChannel(family);\n+ }\n+\n+ @Override\n+ public AFTIPCServerSocketChannel openServerSocketChannel() throws IOException {\n+ return AFTIPCServerSocket.newInstance().getChannel();\n+ }\n+\n+ @Override\n+ public AFTIPCServerSocketChannel openServerSocketChannel(SocketAddress sa) throws IOException {\n+ return AFTIPCServerSocket.bindOn(AFTIPCSocketAddress.unwrap(sa)).getChannel();\n+ }\n+\n+ @Override\n+ public AFTIPCSocketChannel openSocketChannel() throws IOException {\n+ return (AFTIPCSocketChannel) super.openSocketChannel();\n+ }\n+\n+ @Override\n+ public AFTIPCSocketChannel openSocketChannel(SocketAddress sa) throws IOException {\n+ return AFTIPCSocket.connectTo(AFTIPCSocketAddress.unwrap(sa)).getChannel();\n+ }\n+\n+ @Override\n+ protected ProtocolFamily protocolFamily() {\n+ return AFTIPCProtocolFamily.TIPC;\n+ }\n+\n+ @Override\n+ protected AFAddressFamily<@NonNull AFTIPCSocketAddress> addressFamily() {\n+ return AF_TIPC;\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCServerSocket.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCServerSocket.java\nnew file mode 100644\nindex 000000000..23e4c43b7\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCServerSocket.java\n@@ -0,0 +1,120 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.net.ServerSocket;\n+import java.net.SocketException;\n+\n+import org.newsclub.net.unix.AFServerSocket;\n+import org.newsclub.net.unix.AFServerSocketChannel;\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.AFSocketAddress;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+\n+/**\n+ * The server part of an {@code AF_TIPC} socket.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public class AFTIPCServerSocket extends AFServerSocket {\n+ AFTIPCServerSocket(FileDescriptor fdObj) throws IOException {\n+ super(fdObj);\n+ }\n+\n+ @Override\n+ protected AFServerSocketChannel newChannel() {\n+ return new AFTIPCServerSocketChannel(this);\n+ }\n+\n+ @Override\n+ public AFTIPCServerSocketChannel getChannel() {\n+ return (AFTIPCServerSocketChannel) super.getChannel();\n+ }\n+\n+ /**\n+ * Returns a new, unbound AF_TIPC {@link ServerSocket}.\n+ * \n+ * @return The new, unbound {@link AFServerSocket}.\n+ * @throws IOException if the operation fails.\n+ */\n+ public static AFTIPCServerSocket newInstance() throws IOException {\n+ return (AFTIPCServerSocket) AFServerSocket.newInstance(AFTIPCServerSocket::new);\n+ }\n+\n+ static AFTIPCServerSocket newInstance(FileDescriptor fdObj, int localPort, int remotePort)\n+ throws IOException {\n+ return (AFTIPCServerSocket) AFServerSocket.newInstance(AFTIPCServerSocket::new, fdObj,\n+ localPort, remotePort);\n+ }\n+\n+ /**\n+ * Returns a new AF_TIPC {@link ServerSocket} that is bound to the given\n+ * {@link AFTIPCSocketAddress}.\n+ * \n+ * @param addr The socket file to bind to.\n+ * @return The new, bound {@link AFServerSocket}.\n+ * @throws IOException if the operation fails.\n+ */\n+ public static AFTIPCServerSocket bindOn(final AFTIPCSocketAddress addr) throws IOException {\n+ return (AFTIPCServerSocket) AFServerSocket.bindOn(AFTIPCServerSocket::new, addr);\n+ }\n+\n+ /**\n+ * Returns a new AF_TIPC {@link ServerSocket} that is bound to the given {@link AFSocketAddress}.\n+ * \n+ * @param addr The socket file to bind to.\n+ * @param deleteOnClose If {@code true}, the socket file (if the address points to a file) will be\n+ * deleted upon {@link #close}.\n+ * @return The new, bound {@link AFServerSocket}.\n+ * @throws IOException if the operation fails.\n+ */\n+ public static AFTIPCServerSocket bindOn(final AFTIPCSocketAddress addr, boolean deleteOnClose)\n+ throws IOException {\n+ return (AFTIPCServerSocket) AFServerSocket.bindOn(AFTIPCServerSocket::new, addr, deleteOnClose);\n+ }\n+\n+ /**\n+ * Returns a new, unbound AF_TIPC {@link ServerSocket} that will always bind to the given\n+ * address, regardless of any socket address used in a call to bind.\n+ * \n+ * @param forceAddr The address to use.\n+ * @return The new, yet unbound {@link AFServerSocket}.\n+ * @throws IOException if an exception occurs.\n+ */\n+ public static AFTIPCServerSocket forceBindOn(final AFTIPCSocketAddress forceAddr)\n+ throws IOException {\n+ return (AFTIPCServerSocket) AFServerSocket.forceBindOn(AFTIPCServerSocket::new, forceAddr);\n+ }\n+\n+ @Override\n+ protected AFTIPCSocketImpl newImpl(FileDescriptor fdObj) throws SocketException {\n+ return new AFTIPCSocketImpl(fdObj);\n+ }\n+\n+ @Override\n+ protected AFSocket newSocketInstance() throws IOException {\n+ return AFTIPCSocket.newInstance();\n+ }\n+\n+ @Override\n+ public AFTIPCSocket accept() throws IOException {\n+ return (AFTIPCSocket) super.accept();\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCServerSocketChannel.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCServerSocketChannel.java\nnew file mode 100644\nindex 000000000..1560078ca\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCServerSocketChannel.java\n@@ -0,0 +1,44 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.IOException;\n+\n+import org.newsclub.net.unix.AFServerSocketChannel;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+\n+/**\n+ * A selectable channel for stream-oriented listening sockets.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public final class AFTIPCServerSocketChannel extends AFServerSocketChannel {\n+ AFTIPCServerSocketChannel(AFTIPCServerSocket socket) {\n+ super(socket, AFTIPCSelectorProvider.getInstance());\n+ }\n+\n+ /**\n+ * Opens a server-socket channel.\n+ *\n+ * @return The new channel\n+ * @throws IOException on error.\n+ */\n+ public static AFTIPCServerSocketChannel open() throws IOException {\n+ return AFTIPCServerSocket.newInstance().getChannel();\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocket.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocket.java\nnew file mode 100644\nindex 000000000..feb14846a\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocket.java\n@@ -0,0 +1,195 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.FileDescriptor;\n+import java.io.IOException;\n+import java.math.BigInteger;\n+import java.net.Socket;\n+import java.net.SocketException;\n+\n+import org.newsclub.net.unix.AFSocket;\n+import org.newsclub.net.unix.AFSocketCapability;\n+import org.newsclub.net.unix.AFSocketFactory;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+import org.newsclub.net.unix.AFTIPCSocketImplExtensions;\n+\n+/**\n+ * Implementation of an {@code AF_TIPC} socket.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public final class AFTIPCSocket extends AFSocket implements\n+ AFTIPCSocketExtensions {\n+ private static AFTIPCSocketImplExtensions staticExtensions = null;\n+\n+ AFTIPCSocket(FileDescriptor fdObj, AFSocketFactory factory)\n+ throws SocketException {\n+ super(new AFTIPCSocketImpl(fdObj), factory);\n+ }\n+\n+ private static synchronized AFTIPCSocketImplExtensions getStaticImplExtensions()\n+ throws IOException {\n+ if (staticExtensions == null) {\n+ try (AFTIPCSocket socket = new AFTIPCSocket(null, null)) {\n+ staticExtensions = (AFTIPCSocketImplExtensions) socket.getImplExtensions();\n+ }\n+ }\n+ return staticExtensions;\n+ }\n+\n+ /**\n+ * Returns true iff {@link AFTIPCSocket}s (sockets of type \"AF_TIPC\") are supported\n+ * by the current Java VM and the kernel.\n+ * \n+ * To support {@link AFTIPCSocket}s, a custom JNI library must be loaded that is supplied with\n+ * junixsocket, and the system must support AF_TIPC sockets.\n+ * \n+ * This call is equivalent to checking {@link AFSocket#isSupported()} and\n+ * {@link AFSocket#supports(AFSocketCapability)} with {@link AFSocketCapability#CAPABILITY_TIPC}.\n+ * \n+ * @return {@code true} iff supported.\n+ */\n+ public static boolean isSupported() {\n+ return AFSocket.isSupported() && AFSocket.supports(AFSocketCapability.CAPABILITY_TIPC);\n+ }\n+\n+ @Override\n+ protected AFTIPCSocketChannel newChannel() {\n+ return new AFTIPCSocketChannel(this);\n+ }\n+\n+ /**\n+ * Creates a new, unbound {@link AFSocket}.\n+ * \n+ * This \"default\" implementation is a bit \"lenient\" with respect to the specification.\n+ * \n+ * In particular, we ignore calls to {@link Socket#getTcpNoDelay()} and\n+ * {@link Socket#setTcpNoDelay(boolean)}.\n+ * \n+ * @return A new, unbound socket.\n+ * @throws IOException if the operation fails.\n+ */\n+ public static AFTIPCSocket newInstance() throws IOException {\n+ return (AFTIPCSocket) AFSocket.newInstance(AFTIPCSocket::new, (AFTIPCSocketFactory) null);\n+ }\n+\n+ static AFTIPCSocket newInstance(AFTIPCSocketFactory factory) throws SocketException {\n+ return (AFTIPCSocket) AFSocket.newInstance(AFTIPCSocket::new, factory);\n+ }\n+\n+ /**\n+ * Creates a new, unbound, \"strict\" {@link AFSocket}.\n+ * \n+ * This call uses an implementation that tries to be closer to the specification than\n+ * {@link #newInstance()}, at least for some cases.\n+ * \n+ * @return A new, unbound socket.\n+ * @throws IOException if the operation fails.\n+ */\n+ public static AFTIPCSocket newStrictInstance() throws IOException {\n+ return (AFTIPCSocket) AFSocket.newInstance(AFTIPCSocket::new, (AFTIPCSocketFactory) null);\n+ }\n+\n+ /**\n+ * Creates a new {@link AFSocket} and connects it to the given {@link AFTIPCSocketAddress}.\n+ * \n+ * @param addr The address to connect to.\n+ * @return A new, connected socket.\n+ * @throws IOException if the operation fails.\n+ */\n+ public static AFTIPCSocket connectTo(AFTIPCSocketAddress addr) throws IOException {\n+ return (AFTIPCSocket) AFSocket.connectTo(AFTIPCSocket::new, addr);\n+ }\n+\n+ @Override\n+ public AFTIPCSocketChannel getChannel() {\n+ return (AFTIPCSocketChannel) super.getChannel();\n+ }\n+\n+ /**\n+ * Very basic self-test function.\n+ * \n+ * Prints \"supported\" and \"capabilities\" status to System.out.\n+ * \n+ * @param args ignored.\n+ */\n+ public static void main(String[] args) {\n+ // If you want to run this directly from within Eclipse, see\n+ // org.newsclub.net.unix.tipc.SocketTest#testMain.\n+ System.out.print(AFTIPCSocket.class.getName() + \".isSupported(): \");\n+ System.out.flush();\n+ System.out.println(AFTIPCSocket.isSupported());\n+ }\n+\n+ @Override\n+ public AFTIPCErrInfo getErrInfo() {\n+ return AFTIPCErrInfo.of(((AFTIPCSocketImplExtensions) getImplExtensions()).getTIPCErrInfo());\n+ }\n+\n+ @Override\n+ public AFTIPCDestName getDestName() {\n+ return AFTIPCDestName.of(((AFTIPCSocketImplExtensions) getImplExtensions()).getTIPCDestName());\n+ }\n+\n+ /**\n+ * Retrieves the 16-byte node ID given a node hash.\n+ * \n+ * @param peerId The node hash.\n+ * @return The node ID, or {@code null} if unsupported.\n+ * @throws IOException on error.\n+ */\n+ public static byte[] getNodeIdentity(int peerId) throws IOException {\n+ return getStaticImplExtensions().getTIPCNodeId(peerId);\n+ }\n+\n+ /**\n+ * Retrieves the TIPC node identity given the node hash of the given address.\n+ *\n+ * @param address The address.\n+ * @return The node identity, or {@code null} if unsupported.\n+ * @throws IOException on error.\n+ */\n+ public byte[] getNodeIdentity(AFTIPCSocketAddress address) throws IOException {\n+ return AFTIPCSocket.getNodeIdentity(address.getTIPCNodeHash());\n+ }\n+\n+ /**\n+ * Retrieves the node ID given a node hash, as a hexadecimal string.\n+ * \n+ * @param peerId The node hash.\n+ * @return The node ID, or {@code null} if unsupported.\n+ * @throws IOException on error.\n+ */\n+ public static String getNodeIdHexString(int peerId) throws IOException {\n+ byte[] id = getNodeIdentity(peerId);\n+ return id == null ? null : new BigInteger(1, id).toString(16);\n+ }\n+\n+ /**\n+ * Retrieves the link name given a node hash and a bearer ID.\n+ * \n+ * @param peerId The node hash.\n+ * @param bearerId The bearer Id.\n+ * @return The link name, or {@code null} if unsupported.\n+ * @throws IOException on error.\n+ */\n+ public static String getLinkName(int peerId, int bearerId) throws IOException {\n+ return getStaticImplExtensions().getTIPCLinkName(peerId, bearerId);\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketChannel.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketChannel.java\nnew file mode 100644\nindex 000000000..3d9701b02\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketChannel.java\n@@ -0,0 +1,43 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import org.newsclub.net.unix.AFSocketChannel;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+\n+/**\n+ * A selectable channel for stream-oriented connecting sockets.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public final class AFTIPCSocketChannel extends AFSocketChannel implements\n+ AFTIPCSocketExtensions {\n+ AFTIPCSocketChannel(AFTIPCSocket socket) {\n+ super(socket, AFTIPCSelectorProvider.getInstance());\n+ }\n+\n+ @Override\n+ public AFTIPCErrInfo getErrInfo() {\n+ return ((AFTIPCSocketExtensions) getAFSocket()).getErrInfo();\n+ }\n+\n+ @Override\n+ public AFTIPCDestName getDestName() {\n+ return ((AFTIPCSocketExtensions) getAFSocket()).getDestName();\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketExtensions.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketExtensions.java\nnew file mode 100644\nindex 000000000..61f653627\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketExtensions.java\n@@ -0,0 +1,45 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import org.newsclub.net.unix.AFSocketExtensions;\n+\n+/**\n+ * Defines certain methods that all junixsocket AF_TIPC socket implementations share and extend\n+ * beyond the standard socket API.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public interface AFTIPCSocketExtensions extends AFSocketExtensions {\n+ /**\n+ * Returns the TIPC \"ErrInfo\" information from the ancillary receive buffer (if any was set), or\n+ * {@code null} if no error was retrieved.\n+ * \n+ * @return The ErrInfo.\n+ */\n+ AFTIPCErrInfo getErrInfo();\n+\n+ /**\n+ * Returns the TIPC \"DestName\" information from the ancillary receive buffer (if any was set), or\n+ * {@code null} if no DestName was retrieved.\n+ * \n+ * @return The service address or range (without scope) that was specified by the sender of the\n+ * message.\n+ */\n+ AFTIPCDestName getDestName();\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketFactory.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketFactory.java\nnew file mode 100644\nindex 000000000..c7cdb6622\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketFactory.java\n@@ -0,0 +1,90 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.IOException;\n+import java.net.Socket;\n+import java.net.SocketException;\n+\n+import org.newsclub.net.unix.AFSocketFactory;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+import org.newsclub.net.unix.AFTIPCSocketAddress.Scope;\n+\n+/**\n+ * The base for a SocketFactory that connects to TIPC sockets.\n+ * \n+ * Typically, the \"hostname\" is used as a reference to a socketFile on the file system. The actual\n+ * mapping is left to the implementor.\n+ */\n+public abstract class AFTIPCSocketFactory extends AFSocketFactory {\n+ /**\n+ * Creates a {@link AFTIPCSocketFactory}.\n+ */\n+ protected AFTIPCSocketFactory() {\n+ super();\n+ }\n+\n+ @Override\n+ public final Socket createSocket() throws SocketException {\n+ return configure(AFTIPCSocket.newInstance(this));\n+ }\n+\n+ @Override\n+ protected final AFTIPCSocket connectTo(AFTIPCSocketAddress addr) throws IOException {\n+ return configure(AFTIPCSocket.connectTo(addr));\n+ }\n+\n+ /**\n+ * Performs some optional configuration on a newly created socket.\n+ * \n+ * @param sock The socket.\n+ * @return The very socket.\n+ * @throws SocketException on error.\n+ */\n+ protected AFTIPCSocket configure(AFTIPCSocket sock) throws SocketException {\n+ return sock;\n+ }\n+\n+ /**\n+ * Always connects sockets to the given TIPC type and instance.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+ public static class ServiceAddress extends AFTIPCSocketFactory {\n+ private final int type;\n+ private final int instance;\n+\n+ /**\n+ * Creates an {@link AFTIPCSocketFactory} that always uses the given TIPC service type and\n+ * instance, implying cluster scope.\n+ * \n+ * @param type The service type.\n+ * @param instance The service instance.\n+ */\n+ public ServiceAddress(int type, int instance) {\n+ super();\n+ this.type = type;\n+ this.instance = instance;\n+ }\n+\n+ @Override\n+ public final AFTIPCSocketAddress addressFromHost(String host, int port) throws SocketException {\n+ return AFTIPCSocketAddress.ofService(port, Scope.SCOPE_CLUSTER, type, instance, 0);\n+ }\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketImpl.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketImpl.java\nnew file mode 100644\nindex 000000000..d0a8366da\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketImpl.java\n@@ -0,0 +1,40 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.FileDescriptor;\n+import java.net.SocketException;\n+\n+import org.newsclub.net.unix.AFSocketImpl;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+\n+final class AFTIPCSocketImpl extends AFSocketImpl {\n+ protected AFTIPCSocketImpl(FileDescriptor fdObj) throws SocketException {\n+ super(AFTIPCSelectorProvider.AF_TIPC, fdObj);\n+ }\n+\n+ @Override\n+ public Object getOption(int optID) throws SocketException {\n+ return getOptionLenient(optID);\n+ }\n+\n+ @Override\n+ public void setOption(int optID, Object value) throws SocketException {\n+ setOptionLenient(optID, value);\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketOptions.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketOptions.java\nnew file mode 100644\nindex 000000000..277eb598a\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketOptions.java\n@@ -0,0 +1,193 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.net.SocketOption;\n+import java.net.StandardSocketOptions;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.NonNullByDefault;\n+import org.newsclub.net.unix.AFSocketOption;\n+import org.newsclub.net.unix.NamedInteger;\n+\n+/**\n+ * TIPC-specific socket options.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+@NonNullByDefault\n+public final class AFTIPCSocketOptions {\n+ /**\n+ * Use as value for {@link SocketOption}s of type {@link Void}.\n+ * \n+ * @see #TIPC_GROUP_LEAVE\n+ */\n+ @SuppressWarnings({\"null\"})\n+ public static final Void VOID = (@NonNull Void) null;\n+\n+ /**\n+ * This option governs how likely a message sent by the socket is to be affected by congestion. A\n+ * message with higher importance is less likely to be delayed due to link congestion and less\n+ * likely to be rejected due to receiver congestion.\n+ * \n+ * @see MessageImportance\n+ */\n+ public static final AFSocketOption TIPC_IMPORTANCE = new AFSocketOption<>(\n+ \"TIPC_IMPORTANCE\", MessageImportance.class, 271, 127);\n+\n+ /**\n+ * Controls whether a message should be discarded when link congestion occurs.\n+ */\n+ public static final AFSocketOption TIPC_SRC_DROPPABLE = new AFSocketOption<>(\n+ \"TIPC_SRC_DROPPABLE\", Boolean.class, 271, 128);\n+\n+ /**\n+ * This option governs the handling of a sent message if it cannot be delivered to its\n+ * destination. If set, the message is discarded; otherwise it is returned to the sender.\n+ * \n+ * By default, this option is enabled for SOCK_RDM and SOCK_DGRAM sockets, and disabled otherwise.\n+ */\n+ public static final AFSocketOption TIPC_DEST_DROPPABLE = new AFSocketOption<>(\n+ \"TIPC_DEST_DROPPABLE\", Boolean.class, 271, 129);\n+\n+ /**\n+ * Specifies the number of milliseconds connect() will wait before giving up because of lack of\n+ * response. The default value is 8000 ms.\n+ */\n+ public static final AFSocketOption TIPC_CONN_TIMEOUT = new AFSocketOption<>(\n+ \"TIPC_CONN_TIMEOUT\", Integer.class, 271, 130);\n+\n+ /**\n+ * Returns the number of messages in the node's receive queue (get only).\n+ */\n+ public static final AFSocketOption TIPC_NODE_RECVQ_DEPTH = new AFSocketOption<>(\n+ \"TIPC_NODE_RECVQ_DEPTH\", Integer.class, 271, 131);\n+\n+ /**\n+ * Returns the number of messages in the socket's receive queue (get only).\n+ */\n+ public static final AFSocketOption TIPC_SOCK_RECVQ_DEPTH = new AFSocketOption<>(\n+ \"TIPC_SOCK_RECVQ_DEPTH\", Integer.class, 271, 132);\n+\n+ /**\n+ * Force datagram multicasts from this socket to be transmitted as bearer broadcast/multicast\n+ * (instead of replicated unicast) whenever possible..\n+ */\n+ public static final AFSocketOption TIPC_MCAST_BROADCAST = new AFSocketOption<>(\n+ \"TIPC_MCAST_BROADCAST\", Boolean.class, 271, 133);\n+\n+ /**\n+ * Force datagram multicasts from this socket to be transmitted as replicated unicast instead of\n+ * bearer broadcast/multicast..\n+ */\n+ public static final AFSocketOption TIPC_MCAST_REPLICAST = new AFSocketOption<>(\n+ \"TIPC_MCAST_REPLICAST\", Boolean.class, 271, 134);\n+\n+ /**\n+ * Join a communication group.\n+ */\n+ public static final AFSocketOption TIPC_GROUP_JOIN = new AFSocketOption<>(\n+ \"TIPC_GROUP_JOIN\", AFTIPCGroupRequest.class, 271, 135);\n+\n+ /**\n+ * Leave the previously joined communication group.\n+ * \n+ * Only valid for setOption. The value is ignored. Use {@link #VOID}.\n+ */\n+ public static final AFSocketOption TIPC_GROUP_LEAVE = new AFSocketOption<>(\n+ \"TIPC_GROUP_LEAVE\", Void.class, 271, 136);\n+\n+ /**\n+ * When using TIPC_SOCK_RECVQ_DEPTH for getsockopt(), it returns the number of buffers in the\n+ * receive socket buffer which is not so helpful for user space applications.\n+ * \n+ * TIPC_SOCK_RECVQ_USED returns the current allocated bytes of the receive socket buffer. This\n+ * helps user space applications dimension its buffer usage to avoid buffer overload issue.\n+ */\n+ public static final AFSocketOption TIPC_SOCK_RECVQ_USED = new AFSocketOption<>(\n+ \"TIPC_SOCK_RECVQ_USED\", Integer.class, 271, 137);\n+\n+ /**\n+ * If enabled, the Nagle algorithm is disabled. Similar to\n+ * {@link StandardSocketOptions#TCP_NODELAY}.\n+ */\n+ public static final AFSocketOption TIPC_NODELAY = new AFSocketOption<>(\"TIPC_NODELAY\",\n+ Boolean.class, 271, 138);\n+\n+ private AFTIPCSocketOptions() {\n+ throw new IllegalStateException();\n+ }\n+\n+ /**\n+ * The TIPC message importance.\n+ * \n+ * Messages with a higher importance have a lower chance of being dropped when congestion occurs.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+ public static final class MessageImportance extends NamedInteger implements\n+ NamedInteger.HasOfValue {\n+ private static final long serialVersionUID = 1L;\n+\n+ /**\n+ * Low importance (the default).\n+ */\n+ public static final MessageImportance LOW;\n+\n+ /**\n+ * Medium importance.\n+ */\n+ public static final MessageImportance MEDIUM;\n+\n+ /**\n+ * High importance.\n+ */\n+ public static final MessageImportance HIGH;\n+\n+ /**\n+ * Critical importance.\n+ */\n+ public static final MessageImportance CRITICAL;\n+\n+ private static final @NonNull MessageImportance[] VALUES = init(\n+ new @NonNull MessageImportance[] {\n+ LOW = new MessageImportance(\"LOW\", 0), //\n+ MEDIUM = new MessageImportance(\"MEDIUM\", 1), //\n+ HIGH = new MessageImportance(\"HIGH\", 2), //\n+ CRITICAL = new MessageImportance(\"CRITICAL\", 3) //\n+ });\n+\n+ private MessageImportance(int id) {\n+ super(id);\n+ }\n+\n+ private MessageImportance(String name, int id) {\n+ super(name, id);\n+ }\n+\n+ /**\n+ * Returns a {@link MessageImportance} instance for the given value.\n+ * \n+ * @param v The value.\n+ * @return The instance.\n+ */\n+ public static MessageImportance ofValue(int v) {\n+ return ofValue(VALUES, MessageImportance::new, v);\n+ }\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketPair.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketPair.java\nnew file mode 100644\nindex 000000000..367a9cb58\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCSocketPair.java\n@@ -0,0 +1,61 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.IOException;\n+\n+import org.newsclub.net.unix.AFSocketPair;\n+import org.newsclub.net.unix.AFSomeSocket;\n+\n+/**\n+ * A pair of sockets.\n+ * \n+ * @param The socket type.\n+ * @author Christian Kohlschütter\n+ */\n+public final class AFTIPCSocketPair extends AFSocketPair {\n+ /**\n+ * Creates a new socket pair.\n+ * \n+ * @param socket1 The first socket.\n+ * @param socket2 The second socket.\n+ */\n+ protected AFTIPCSocketPair(T socket1, T socket2) {\n+ super(socket1, socket2);\n+ }\n+\n+ /**\n+ * Opens a socket pair of interconnected channels.\n+ * \n+ * @return The new channel pair.\n+ * @throws IOException on error.\n+ */\n+ public static AFTIPCSocketPair open() throws IOException {\n+ return AFTIPCSelectorProvider.provider().openSocketChannelPair();\n+ }\n+\n+ /**\n+ * Opens a socket pair of interconnected datagram channels.\n+ * \n+ * @return The new channel pair.\n+ * @throws IOException on error.\n+ */\n+ public static AFTIPCSocketPair openDatagram() throws IOException {\n+ return AFTIPCSelectorProvider.provider().openDatagramChannelPair();\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCTopologyEvent.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCTopologyEvent.java\nnew file mode 100644\nindex 000000000..f948ec276\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCTopologyEvent.java\n@@ -0,0 +1,302 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import static org.newsclub.net.unix.AFTIPCSocketAddress.AddressType.formatTIPCInt;\n+\n+import java.io.IOException;\n+import java.net.SocketException;\n+import java.nio.ByteBuffer;\n+import java.nio.ByteOrder;\n+import java.util.Objects;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.NonNullByDefault;\n+import org.eclipse.jdt.annotation.Nullable;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+import org.newsclub.net.unix.NamedInteger;\n+\n+import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;\n+\n+/**\n+ * A TIPC topology event received by the {@link AFTIPCTopologyWatcher} as a result of an\n+ * {@link AFTIPCTopologySubscription}.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+@NonNullByDefault\n+public final class AFTIPCTopologyEvent {\n+ private static final int MESSAGE_LENGTH = 48;\n+ private final Type type;\n+ private final int foundLower;\n+ private final int foundUpper;\n+ private final AFTIPCSocketAddress address;\n+ private final AFTIPCTopologySubscription subscription;\n+\n+ /**\n+ * Some TIPC error code.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+ @SuppressWarnings(\"PMD.ShortClassName\")\n+ public static final class Type extends NamedInteger {\n+ private static final long serialVersionUID = 1L;\n+\n+ /**\n+ * Publication event.\n+ */\n+ public static final Type TIPC_PUBLISHED;\n+\n+ /**\n+ * Withdrawal event.\n+ */\n+ public static final Type TIPC_WITHDRAWN;\n+\n+ /**\n+ * Subscription timeout event.\n+ */\n+ public static final Type TIPC_SUBSCR_TIMEOUT;\n+\n+ /**\n+ * Undefined.\n+ */\n+ public static final Type UNDEFINED;\n+\n+ private static final @NonNull Type[] VALUES = init(new @NonNull Type[] {\n+ UNDEFINED = new Type(\"UNDEFINED\", 0), //\n+ TIPC_PUBLISHED = new Type(\"TIPC_PUBLISHED\", 1), //\n+ TIPC_WITHDRAWN = new Type(\"TIPC_WITHDRAWN\", 2), //\n+ TIPC_SUBSCR_TIMEOUT = new Type(\"TIPC_SUBSCR_TIMEOUT\", 3), //\n+ });\n+\n+ private Type(int id) {\n+ super(id);\n+ }\n+\n+ private Type(String name, int id) {\n+ super(name, id);\n+ }\n+\n+ /**\n+ * Returns an {@link Type} instance given an integer.\n+ * \n+ * @param v The value.\n+ * @return The instance.\n+ */\n+ public static Type ofValue(int v) {\n+ return ofValue(VALUES, Type::new, v);\n+ }\n+ }\n+\n+ private AFTIPCTopologyEvent(Type type, int foundLower, int foundUpper,\n+ AFTIPCSocketAddress address, AFTIPCTopologySubscription subscription) {\n+ this.type = type;\n+ this.foundLower = foundLower;\n+ this.foundUpper = foundUpper;\n+ this.address = address;\n+ this.subscription = subscription;\n+ }\n+\n+ @SuppressWarnings(\"null\")\n+ static AFTIPCTopologyEvent readFromBuffer(ByteBuffer buf) throws SocketException {\n+ buf = buf.order(ByteOrder.BIG_ENDIAN);\n+ Type type = Type.ofValue(buf.getInt());\n+ int foundLower = buf.getInt();\n+ int foundUpper = buf.getInt();\n+ AFTIPCSocketAddress address = AFTIPCSocketAddress.ofSocket(buf.getInt(), buf.getInt());\n+ AFTIPCTopologySubscription sub = AFTIPCTopologySubscription.readFromBuffer(buf);\n+\n+ return new AFTIPCTopologyEvent(type, foundLower, foundUpper, address, sub);\n+ }\n+\n+ @Override\n+ public String toString() {\n+ int lower = getFoundLower();\n+ int upper = getFoundUpper();\n+ String found;\n+ if (lower == upper) {\n+ found = formatTIPCInt(lower);\n+ } else {\n+ found = formatTIPCInt(lower) + \"-\" + formatTIPCInt(upper);\n+ }\n+ return super.toString() + \"[\" + getType() + \";found:\" + found + \";addr=\" + getAddress()\n+ + \";sub=\" + getSubscription() + \"]\";\n+ }\n+\n+ @SuppressWarnings(\"null\")\n+ ByteBuffer writeToBuffer(ByteBuffer buf) throws IOException {\n+ buf = buf.order(ByteOrder.BIG_ENDIAN);\n+ buf.putInt(getType().value());\n+ buf.putInt(getFoundLower());\n+ buf.putInt(getFoundUpper());\n+ getAddress().writeNativeAddressTo(buf);\n+ getSubscription().writeToBuffer(buf);\n+ return buf;\n+ }\n+\n+ /**\n+ * Converts this event message to a new {@link ByteBuffer}.\n+ * \n+ * @return The new buffer, ready to read from.\n+ * @throws IOException on error.\n+ */\n+ @SuppressWarnings({\"null\", \"cast\"})\n+ public ByteBuffer toBuffer() throws IOException {\n+ return (ByteBuffer) writeToBuffer(ByteBuffer.allocate(MESSAGE_LENGTH)).flip();\n+ }\n+\n+ /**\n+ * The event type.\n+ * \n+ * @return The type.\n+ */\n+ public Type getType() {\n+ return type;\n+ }\n+\n+ /**\n+ * The found range's lower value.\n+ * \n+ * @return The lower value.\n+ */\n+ public int getFoundLower() {\n+ return foundLower;\n+ }\n+\n+ /**\n+ * The found range's upper value.\n+ * \n+ * @return The upper value.\n+ */\n+ public int getFoundUpper() {\n+ return foundUpper;\n+ }\n+\n+ /**\n+ * The corresponding socket address.\n+ * \n+ * @return The socket address.\n+ */\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n+ public AFTIPCSocketAddress getAddress() {\n+ return address;\n+ }\n+\n+ /**\n+ * The corresponding subscription that found this event.\n+ * \n+ * @return The subscription.\n+ */\n+ @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n+ public AFTIPCTopologySubscription getSubscription() {\n+ return subscription;\n+ }\n+\n+ /**\n+ * Returns {@code true} iff the event type is {@link Type#TIPC_PUBLISHED}.\n+ * \n+ * @return {@code true} if this a \"published\" event.\n+ */\n+ public boolean isPublished() {\n+ return type == Type.TIPC_PUBLISHED; // NOPMD.CompareObjectsWithEquals\n+ }\n+\n+ /**\n+ * Returns {@code true} iff the event type is {@link Type#TIPC_WITHDRAWN}.\n+ * \n+ * @return {@code true} if this a \"withdrawn\" event.\n+ */\n+ public boolean isWithdrawn() {\n+ return type == Type.TIPC_WITHDRAWN; // NOPMD.CompareObjectsWithEquals\n+ }\n+\n+ /**\n+ * Returns {@code true} iff the event type is {@link Type#TIPC_SUBSCR_TIMEOUT}.\n+ * \n+ * @return {@code true} if this a \"timeout\" event.\n+ */\n+ public boolean isTimeout() {\n+ return type == Type.TIPC_SUBSCR_TIMEOUT; // NOPMD.CompareObjectsWithEquals\n+ }\n+\n+ /**\n+ * Returns {@code true} iff the corresponding subscription has the\n+ * {@link AFTIPCTopologySubscription.Flags#TIPC_SUB_PORTS} flag set.\n+ * \n+ * @return {@code true} if this a event referring to a \"port\" subscription.\n+ */\n+ public boolean isPort() {\n+ return subscription.isPort();\n+ }\n+\n+ /**\n+ * Returns {@code true} iff the corresponding subscription has the\n+ * {@link AFTIPCTopologySubscription.Flags#TIPC_SUB_SERVICE} flag set.\n+ * \n+ * @return {@code true} if this a event referring to a \"service\" subscription.\n+ */\n+ public boolean isService() {\n+ return subscription.isService();\n+ }\n+\n+ /**\n+ * Returns {@code true} iff the corresponding subscription has the\n+ * {@link AFTIPCTopologySubscription.Flags#TIPC_SUB_CANCEL} flag set.\n+ * \n+ * @return {@code true} if this a event referring to a \"cancellation\" subscription request.\n+ */\n+ public boolean isCancellationRequest() {\n+ return subscription.isCancellation();\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return Objects.hash(address, foundLower, foundUpper, subscription, type);\n+ }\n+\n+ @Override\n+ public boolean equals(@Nullable Object obj) {\n+ if (this == obj) {\n+ return true;\n+ }\n+ if (!(obj instanceof AFTIPCTopologyEvent)) {\n+ return false;\n+ }\n+ AFTIPCTopologyEvent other = (AFTIPCTopologyEvent) obj;\n+ return Objects.equals(address, other.address) && foundLower == other.foundLower\n+ && foundUpper == other.foundUpper && Objects.equals(subscription, other.subscription)\n+ && Objects.equals(type, other.type);\n+ }\n+\n+ /**\n+ * Returns the link name for a link state event requested by\n+ * {@link AFTIPCTopologySubscription#TIPC_LINK_STATE} or\n+ * {@link AFTIPCTopologyWatcher#addLinkStateSubscription()}.\n+ * \n+ * A link name is something like \"f875a40e707d:eth0-8c1645f2ce27:eth0\"\n+ * \n+ * @return The link name, or {@code null} if unsupported.\n+ * @throws IOException on error.\n+ */\n+ public @Nullable String getLinkName() throws IOException {\n+ // this only works if getSubscription().getType() == AFTIPCSubscription.TIPC_LINK_STATE\n+ int node = getFoundLower();\n+ int ref = getAddress().getTIPCRef();\n+ return AFTIPCSocket.getLinkName(node, ref & 0xFFFF);\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCTopologySubscription.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCTopologySubscription.java\nnew file mode 100644\nindex 000000000..80eb3e464\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCTopologySubscription.java\n@@ -0,0 +1,379 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import static org.newsclub.net.unix.AFTIPCSocketAddress.AddressType.formatTIPCInt;\n+\n+import java.math.BigInteger;\n+import java.nio.ByteBuffer;\n+import java.nio.ByteOrder;\n+import java.util.Arrays;\n+import java.util.Locale;\n+import java.util.Objects;\n+import java.util.WeakHashMap;\n+\n+import org.eclipse.jdt.annotation.NonNull;\n+import org.eclipse.jdt.annotation.NonNullByDefault;\n+import org.eclipse.jdt.annotation.Nullable;\n+import org.newsclub.net.unix.NamedIntegerBitmask;\n+\n+/**\n+ * An \"event subscription\" to be used with {@link AFTIPCTopologyWatcher}.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+@NonNullByDefault\n+public final class AFTIPCTopologySubscription {\n+ static final byte[] USR_EMPTY = new byte[8];\n+\n+ private static final WeakHashMap SUBSCRIPTIONS =\n+ new WeakHashMap<>();\n+\n+ /**\n+ * Special timeout value meaning \"never timeout\".\n+ */\n+ public static final int TIPC_WAIT_FOREVER = -1;\n+\n+ /**\n+ * The \"node state\" cluster topology monitor mode.\n+ * \n+ * When TIPC establishes contact with another node, it does internally create a binding {type =\n+ * TIPC_NODE_STATE, instance = peer node hash number} in the binding table. This makes it possible\n+ * for applications on a node to keep track of reachable peer nodes at any time. *\n+ */\n+ public static final int TIPC_NODE_STATE = 0;\n+\n+ /**\n+ * The \"link state\" cluster connectivity monitor mode.\n+ * \n+ * When TIPC establishes a new link to another node, it does internally create a binding {type =\n+ * TIPC_LINK_STATE, instance = peer node hash number} in the binding table. This makes it possible\n+ * for applications on a node to keep track of working links to peer nodes at any time.\n+ * \n+ * This type of binding differs from the topology subscription binding ({@link #TIPC_NODE_STATE})\n+ * in that there may be two links, and hence two bindings, to keep track of for each peer node.\n+ * Although this binding type only is published with node visibility, it is possible to combine it\n+ * with remote node topology subscriptions to obtain a full and continuous matrix view of the\n+ * connectivity in the cluster.\n+ */\n+ public static final int TIPC_LINK_STATE = 2;\n+\n+ private static final int MESSAGE_LENGTH = 28;\n+\n+ private final int type;\n+ private final int lower;\n+ private final int upper;\n+ private final Flags flags;\n+ private final int timeout;\n+ private final byte[] usrHandle;\n+\n+ /**\n+ * Some flags used in the subscription request.\n+ */\n+ public static final class Flags extends NamedIntegerBitmask {\n+ private static final long serialVersionUID = 1L;\n+\n+ /**\n+ * No flags set.\n+ */\n+ public static final Flags NONE = new Flags(\"NONE\", 0);\n+\n+ /**\n+ * Event at each match.\n+ */\n+ public static final Flags TIPC_SUB_PORTS;\n+\n+ /**\n+ * Event at first up/last down.\n+ */\n+ public static final Flags TIPC_SUB_SERVICE;\n+\n+ /**\n+ * Cancel a subscription.\n+ */\n+ public static final Flags TIPC_SUB_CANCEL;\n+\n+ private static final @NonNull Flags[] VALUES = {\n+ TIPC_SUB_PORTS = new Flags(\"TIPC_SUB_PORTS\", 1), //\n+ TIPC_SUB_SERVICE = new Flags(\"TIPC_SUB_SERVICE\", 2), //\n+ TIPC_SUB_CANCEL = new Flags(\"TIPC_SUB_CANCEL\", 4), //\n+ };\n+\n+ private Flags(@Nullable String name, int flags) {\n+ super(name, flags);\n+ }\n+\n+ /**\n+ * Returns a {@link Flags} instance given an integer value.\n+ * \n+ * @param v The value.\n+ * @return The instance.\n+ */\n+ public static Flags ofValue(int v) {\n+ return resolve(VALUES, NONE, Flags::new, v);\n+ }\n+\n+ /**\n+ * Returns a {@link Flags} instance representing the combination of the given list of\n+ * {@link Flags} flags.\n+ * \n+ * @param flags The flags (zero or more values).\n+ * @return The instance.\n+ */\n+ public static Flags withFlags(@NonNull Flags... flags) {\n+ return resolve(VALUES, NONE, Flags::new, flags);\n+ }\n+\n+ /**\n+ * Combines the given {@link Flags} instance with another one.\n+ * \n+ * @param other The other instance.\n+ * @return The combined instance.\n+ */\n+ @Override\n+ public Flags combineWith(Flags other) {\n+ return combineWith(VALUES, NONE, Flags::new, other);\n+ }\n+ }\n+\n+ /**\n+ * Creates a new subscription message that does not time out.\n+ * \n+ * @param type The service type (any service, particularly {@link #TIPC_NODE_STATE} and\n+ * {@link #TIPC_LINK_STATE}.\n+ * @param lower The lower instance.\n+ * @param upper The upper instance.\n+ * @param flags Any flaas (use {@link Flags#NONE} if you don't have any).\n+ */\n+ public AFTIPCTopologySubscription(int type, int lower, int upper, Flags flags) {\n+ this(type, lower, upper, flags, TIPC_WAIT_FOREVER, USR_EMPTY);\n+ }\n+\n+ /**\n+ * Creates a new subscription message.\n+ * \n+ * @param type The service type (any service, particularly {@link #TIPC_NODE_STATE} and\n+ * {@link #TIPC_LINK_STATE}.\n+ * @param lower The lower instance.\n+ * @param upper The upper instance.\n+ * @param flags Any flaas (use {@link Flags#NONE} if you don't have any).\n+ * @param timeoutSeconds The timeout (in seconds), or {@value #TIPC_WAIT_FOREVER} if this should\n+ * never time out.\n+ */\n+ public AFTIPCTopologySubscription(int type, int lower, int upper, Flags flags,\n+ int timeoutSeconds) {\n+ this(type, lower, upper, flags, timeoutSeconds, USR_EMPTY);\n+ }\n+\n+ /**\n+ * Creates a new subscription message.\n+ * \n+ * @param type The service type (any service, particularly {@link #TIPC_NODE_STATE} and\n+ * {@link #TIPC_LINK_STATE}.\n+ * @param lower The lower instance.\n+ * @param upper The upper instance.\n+ * @param flags Any flaas (use {@link Flags#NONE} if you don't have any).\n+ * @param timeoutSeconds The timeout (in seconds), or {@value #TIPC_WAIT_FOREVER} if this should\n+ * never time out.\n+ * @param usrHandle A custom 8-byte message that is included in {@link AFTIPCTopologyEvent}\n+ * messages.\n+ */\n+ public AFTIPCTopologySubscription(int type, int lower, int upper, Flags flags, int timeoutSeconds,\n+ byte[] usrHandle) {\n+ this.type = type;\n+ this.lower = lower;\n+ this.upper = upper;\n+ this.flags = flags == null ? Flags.NONE : flags;\n+ this.timeout = timeoutSeconds;\n+ this.usrHandle = new byte[8];\n+ if (usrHandle != null) {\n+ if (usrHandle.length > 8) {\n+ throw new IllegalArgumentException(\"User handle too long\");\n+ } else {\n+ System.arraycopy(usrHandle, 0, this.usrHandle, 0, usrHandle.length);\n+ }\n+ }\n+ }\n+\n+ @SuppressWarnings({\"null\", \"cast\"})\n+ static AFTIPCTopologySubscription readFromBuffer(ByteBuffer buf) {\n+ buf = (ByteBuffer) buf.slice().limit(MESSAGE_LENGTH);\n+ AFTIPCTopologySubscription sub = SUBSCRIPTIONS.get(buf);\n+ if (sub != null) {\n+ return sub;\n+ }\n+ int type = buf.getInt();\n+ int lower = buf.getInt();\n+ int upper = buf.getInt();\n+ int timeout = buf.getInt();\n+ Flags flags = Flags.ofValue(buf.getInt());\n+ byte[] usrHandle = new byte[8];\n+ buf.get(usrHandle, 0, 8);\n+ buf.flip();\n+ sub = new AFTIPCTopologySubscription(type, lower, upper, flags, timeout, usrHandle);\n+ SUBSCRIPTIONS.put(buf, sub);\n+ return sub;\n+ }\n+\n+ @SuppressWarnings(\"null\")\n+ ByteBuffer writeToBuffer(ByteBuffer buf) {\n+ buf = buf.order(ByteOrder.BIG_ENDIAN);\n+ buf.putInt(type);\n+ buf.putInt(lower);\n+ buf.putInt(upper);\n+ buf.putInt(timeout);\n+ buf.putInt(flags.value());\n+ buf.put(usrHandle);\n+ return buf;\n+ }\n+\n+ /**\n+ * Converts this subscription message to a new {@link ByteBuffer}.\n+ * \n+ * @return The new buffer, ready to read from.\n+ */\n+ @SuppressWarnings({\"null\", \"cast\"})\n+ public ByteBuffer toBuffer() {\n+ return (ByteBuffer) writeToBuffer(ByteBuffer.allocate(MESSAGE_LENGTH)).flip();\n+ }\n+\n+ @Override\n+ public String toString() {\n+ return super.toString() + \"[\" + type + \"@\" + formatTIPCInt(lower) + \"-\" + formatTIPCInt(upper)\n+ + \";flags=\" + flags + \";timeout=\" + timeout + \";usrHandle=\" + String.format(Locale.ENGLISH,\n+ \"%16s\", new BigInteger(1, usrHandle).toString(16)).replace(' ', '0') + \"]\";\n+ }\n+\n+ /**\n+ * Creates an {@link AFTIPCTopologySubscription} that cancels this subscription.\n+ * \n+ * Note that a cancellation cannot be cancelled again.\n+ * \n+ * @return The new {@link AFTIPCTopologySubscription}.\n+ */\n+ public AFTIPCTopologySubscription toCancellation() {\n+ return new AFTIPCTopologySubscription(type, lower, upper, Flags.TIPC_SUB_CANCEL, timeout,\n+ usrHandle);\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ final int prime = 31;\n+ int result = 1;\n+ result = prime * result + Arrays.hashCode(usrHandle);\n+ result = prime * result + Objects.hash(flags, lower, timeout, type, upper);\n+ return result;\n+ }\n+\n+ @Override\n+ public boolean equals(@Nullable Object obj) {\n+ if (this == obj) {\n+ return true;\n+ }\n+ if (!(obj instanceof AFTIPCTopologySubscription)) {\n+ return false;\n+ }\n+ AFTIPCTopologySubscription other = (AFTIPCTopologySubscription) obj;\n+ return Objects.equals(flags, other.flags) && lower == other.lower && timeout == other.timeout\n+ && type == other.type && upper == other.upper && Arrays.equals(usrHandle, other.usrHandle);\n+ }\n+\n+ /**\n+ * Returns the service type.\n+ * \n+ * @return The type.\n+ */\n+ public int getType() {\n+ return type;\n+ }\n+\n+ /**\n+ * Returns the lower instance value.\n+ * \n+ * @return The lower instance value.\n+ */\n+ public int getLower() {\n+ return lower;\n+ }\n+\n+ /**\n+ * Returns the upper instance value.\n+ * \n+ * @return The upper instance value.\n+ */\n+ public int getUpper() {\n+ return upper;\n+ }\n+\n+ /**\n+ * Returns the flags.\n+ * \n+ * @return The flags.\n+ */\n+ public Flags getFlags() {\n+ return flags;\n+ }\n+\n+ /**\n+ * Returns the timeout, in seconds (or {@link #TIPC_WAIT_FOREVER} for \"never timeout\").\n+ * \n+ * @return The timeout.\n+ */\n+ public int getTimeout() {\n+ return timeout;\n+ }\n+\n+ /**\n+ * Returns the 8-byte user handle.\n+ * \n+ * @return The user handle.\n+ */\n+ public byte[] getUsrHandle() {\n+ return usrHandle.clone();\n+ }\n+\n+ /**\n+ * Returns {@code true} iff the subscription has the\n+ * {@link AFTIPCTopologySubscription.Flags#TIPC_SUB_PORTS} flag set.\n+ * \n+ * @return {@code true} if this is a \"port\" subscription.\n+ */\n+ public boolean isPort() {\n+ return flags.hasFlag(Flags.TIPC_SUB_PORTS);\n+ }\n+\n+ /**\n+ * Returns {@code true} iff the subscription has the\n+ * {@link AFTIPCTopologySubscription.Flags#TIPC_SUB_SERVICE} flag set.\n+ * \n+ * @return {@code true} if this is a \"service\" subscription.\n+ */\n+ public boolean isService() {\n+ return flags.hasFlag(Flags.TIPC_SUB_SERVICE);\n+ }\n+\n+ /**\n+ * Returns {@code true} iff the subscription has the\n+ * {@link AFTIPCTopologySubscription.Flags#TIPC_SUB_CANCEL} flag set.\n+ * \n+ * @return {@code true} if this is a \"cancellation\" subscription request.\n+ */\n+ public boolean isCancellation() {\n+ return flags.hasFlag(Flags.TIPC_SUB_CANCEL);\n+ }\n+}\n\\ No newline at end of file\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCTopologyWatcher.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCTopologyWatcher.java\nnew file mode 100644\nindex 000000000..cb1ec3f54\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/AFTIPCTopologyWatcher.java\n@@ -0,0 +1,271 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2021 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix.tipc;\n+\n+import java.io.Closeable;\n+import java.io.IOException;\n+import java.nio.ByteBuffer;\n+import java.nio.channels.SelectionKey;\n+import java.nio.channels.Selector;\n+import java.util.concurrent.atomic.AtomicBoolean;\n+\n+import org.newsclub.net.unix.AFSocketType;\n+import org.newsclub.net.unix.AFTIPCSocketAddress;\n+\n+/**\n+ * Provides access to the TIPC topology service.\n+ * \n+ * @author Christian Kohlschütter\n+ */\n+public class AFTIPCTopologyWatcher implements Closeable {\n+ private final int defaultTimeout;\n+ private final AFTIPCDatagramChannel channel;\n+ private final Selector selector;\n+ private boolean doLoop;\n+ private final AtomicBoolean running = new AtomicBoolean(false);\n+\n+ /**\n+ * Creates an {@link AFTIPCTopologyWatcher} whose subscription requests do not time out by\n+ * default.\n+ * \n+ * @throws IOException on error.\n+ */\n+ public AFTIPCTopologyWatcher() throws IOException {\n+ this(AFTIPCTopologySubscription.TIPC_WAIT_FOREVER);\n+ }\n+\n+ /**\n+ * Creates an {@link AFTIPCTopologyWatcher} whose subscription requests use the given default\n+ * timeout.\n+ * \n+ * @param defaultTimeoutSeconds The timeout in seconds (or\n+ * {@link AFTIPCTopologySubscription#TIPC_WAIT_FOREVER};\n+ * @throws IOException on error.\n+ */\n+ public AFTIPCTopologyWatcher(int defaultTimeoutSeconds) throws IOException {\n+ this.defaultTimeout = defaultTimeoutSeconds;\n+ this.channel = AFTIPCDatagramSocket.newInstance(AFSocketType.SOCK_SEQPACKET).getChannel();\n+ this.selector = channel.provider().openSelector();\n+ channel.connect(AFTIPCSocketAddress.ofTopologyService());\n+ channel.configureBlocking(false);\n+ }\n+\n+ /**\n+ * Watches for all port changes.\n+ * \n+ * @return The subscription object.\n+ * @throws IOException on error.\n+ * @see #cancelSubscription(AFTIPCTopologySubscription)\n+ */\n+ public final AFTIPCTopologySubscription addPortSubscription() throws IOException {\n+ return addPortSubscription(0, ~0);\n+ }\n+\n+ /**\n+ * Watches for port changes of the given port (\"port\" meaning TIPC port, not TCP).\n+ * \n+ * @param port The port.\n+ * @return The subscription object.\n+ * @throws IOException on error.\n+ * @see #cancelSubscription(AFTIPCTopologySubscription)\n+ */\n+ public final AFTIPCTopologySubscription addPortSubscription(int port) throws IOException {\n+ return addPortSubscription(port, port);\n+ }\n+\n+ /**\n+ * Watches for port changes within the given range (\"port\" meaning TIPC port, not TCP).\n+ * \n+ * @param lower The lower value of the port range.\n+ * @param upper The upper value of the port range.\n+ * @return The subscription object.\n+ * @throws IOException on error.\n+ * @see #cancelSubscription(AFTIPCTopologySubscription)\n+ */\n+ public final AFTIPCTopologySubscription addPortSubscription(int lower, int upper)\n+ throws IOException {\n+ return sendMessage(new AFTIPCTopologySubscription(AFTIPCTopologySubscription.TIPC_NODE_STATE,\n+ lower, upper, AFTIPCTopologySubscription.Flags.TIPC_SUB_PORTS, defaultTimeout,\n+ AFTIPCTopologySubscription.USR_EMPTY));\n+ }\n+\n+ /**\n+ * Watches for all link state changes.\n+ * \n+ * @return The subscription object.\n+ * @throws IOException on error.\n+ * @see #cancelSubscription(AFTIPCTopologySubscription)\n+ */\n+ public final AFTIPCTopologySubscription addLinkStateSubscription() throws IOException {\n+ return sendMessage(new AFTIPCTopologySubscription(AFTIPCTopologySubscription.TIPC_LINK_STATE, 0,\n+ ~0, AFTIPCTopologySubscription.Flags.NONE, defaultTimeout,\n+ AFTIPCTopologySubscription.USR_EMPTY));\n+ }\n+\n+ /**\n+ * Watches for service changes of the given service type, matching any instance.\n+ * \n+ * @param type The service type.\n+ * @return The subscription object.\n+ * @throws IOException on error.\n+ * @see #cancelSubscription(AFTIPCTopologySubscription)\n+ */\n+ public final AFTIPCTopologySubscription addServiceSubscription(int type) throws IOException {\n+ return addServiceSubscription(type, 0, ~0);\n+ }\n+\n+ /**\n+ * Watches for service changes of the given service type, matching only the specified instance.\n+ * \n+ * @param type The service type.\n+ * @param instance The instance to match.\n+ * @return The subscription object.\n+ * @throws IOException on error.\n+ * @see #cancelSubscription(AFTIPCTopologySubscription)\n+ */\n+ public final AFTIPCTopologySubscription addServiceSubscription(int type, int instance)\n+ throws IOException {\n+ return addServiceSubscription(type, instance, instance);\n+ }\n+\n+ /**\n+ * Watches for service changes of the given service type and instance range.\n+ * \n+ * @param type The service type.\n+ * @param lower The lower value of the instance range.\n+ * @param upper The upper value of the instance range.\n+ * @return The subscription object.\n+ * @throws IOException on error.\n+ * @see #cancelSubscription(AFTIPCTopologySubscription)\n+ */\n+ public final AFTIPCTopologySubscription addServiceSubscription(int type, int lower, int upper)\n+ throws IOException {\n+ return sendMessage(new AFTIPCTopologySubscription(type, lower, upper,\n+ AFTIPCTopologySubscription.Flags.TIPC_SUB_SERVICE, defaultTimeout,\n+ AFTIPCTopologySubscription.USR_EMPTY));\n+ }\n+\n+ /**\n+ * Cancels a previously added service subscription.\n+ * \n+ * @param sub The subscription to cancel.\n+ * @throws IOException on error.\n+ */\n+ public final void cancelSubscription(AFTIPCTopologySubscription sub) throws IOException {\n+ sendMessage(sub.toCancellation());\n+ }\n+\n+ /**\n+ * Sends a manually crafted subscription message to the TIPC topology server. You usually don't\n+ * need to do this directly; use the\n+ * {@code #addPortSubscription(int, int)}/{@link #cancelSubscription(AFTIPCTopologySubscription)}\n+ * methods instead.\n+ * \n+ * @param sub The subscription message.\n+ * @return The very message.\n+ * @throws IOException on error.\n+ */\n+ public final AFTIPCTopologySubscription sendMessage(AFTIPCTopologySubscription sub)\n+ throws IOException {\n+ channel.write(sub.toBuffer());\n+ return sub;\n+ }\n+\n+ /**\n+ * Runs a receive loop until {@link #stopLoop()} or {@link #close()} is called.\n+ * \n+ * This method returns after the run loop terminates.\n+ * \n+ * @throws IOException on error.\n+ */\n+ @SuppressWarnings(\"null\")\n+ public final void runLoop() throws IOException {\n+ if (!running.compareAndSet(false, true)) {\n+ throw new IllegalStateException(\"Already running\");\n+ }\n+\n+ ByteBuffer buf = ByteBuffer.allocate(64);\n+ SelectionKey key = channel.register(selector, SelectionKey.OP_READ);\n+\n+ try {\n+ doLoop = true;\n+ while (!Thread.interrupted() && doLoop) {\n+ int n = selector.select();\n+ if (!key.isValid() || !doLoop) {\n+ break;\n+ }\n+ if (n > 0) {\n+ channel.receive(buf);\n+ @SuppressWarnings(\"cast\")\n+ AFTIPCTopologyEvent event = AFTIPCTopologyEvent.readFromBuffer((ByteBuffer) buf.flip());\n+ onEvent(event);\n+ buf.clear();\n+ }\n+ }\n+ } finally {\n+ key.cancel();\n+ running.set(false);\n+ }\n+ }\n+\n+ /**\n+ * Called for every event encountered by the run loop.\n+ * \n+ * @param event The event.\n+ * @throws IOException on error. Any exception will terminate the run loop.\n+ * @see #runLoop()\n+ */\n+ protected void onEvent(AFTIPCTopologyEvent event) throws IOException {\n+ }\n+\n+ /**\n+ * Called upon {@link #close()}.\n+ * \n+ * @throws IOException on error.\n+ */\n+ protected void onClose() throws IOException {\n+ }\n+\n+ /**\n+ * Checks if the watcher run loop is running.\n+ * \n+ * @return {@code true} if running.\n+ * @see #runLoop()\n+ */\n+ public boolean isRunning() {\n+ return running.get();\n+ }\n+\n+ /**\n+ * Stops the run loop.\n+ */\n+ public final void stopLoop() {\n+ doLoop = false;\n+ selector.wakeup();\n+ }\n+\n+ /**\n+ * Closes this instance.\n+ */\n+ @Override\n+ public final void close() throws IOException {\n+ channel.close();\n+ stopLoop();\n+ onClose();\n+ }\n+}\ndiff --git a/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/package-info.java b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/package-info.java\nnew file mode 100644\nindex 000000000..9c13e8f98\n--- /dev/null\n+++ b/junixsocket-tipc/src/main/java/org/newsclub/net/unix/tipc/package-info.java\n@@ -0,0 +1,4 @@\n+/**\n+ * The junixsocket implementation for AF_TIPC sockets.\n+ */\n+package org.newsclub.net.unix.tipc;\ndiff --git a/junixsocket-tipc/src/site/site.xml b/junixsocket-tipc/src/site/site.xml\nnew file mode 100644\nindex 000000000..873972284\n--- /dev/null\n+++ b/junixsocket-tipc/src/site/site.xml\n@@ -0,0 +1,33 @@\n+\n+\n+\n+ \n+ org.apache.maven.skins\n+ maven-fluido-skin\n+ \n+ \n+ \n+ \n+ kohlschutter/junixsocket\n+ right\n+ \n+ \n+ \n+\n+ \n+ ${project.name}\n+ \n+ \n+\n+ ${project.scm.url}\n+\n+ \n+

\n+ \n+ \n+ \n+\ndiff --git a/pom.xml b/pom.xml\nindex 9e7473433..d6055bee5 100644\n--- a/pom.xml\n+++ b/pom.xml\n@@ -5,12 +5,12 @@\n 4.0.0\n com.kohlschutter.junixsocket\n junixsocket-parent\n- 2.4.1-SNAPSHOT\n+ 2.5.0-SNAPSHOT\n pom\n \n com.kohlschutter\n kohlschutter-parent-multirelease\n- 1.4.3\n+ 1.4.4\n ../kohlschutter-parent/kohlschutter-parent-multirelease/pom.xml\n \n junixsocket-parent\n@@ -71,11 +71,12 @@ In contrast to other implementations, junixsocket extends the Java Sockets API (\n \n default\n \n- 7\n+ 8\n \n \n \n junixsocket-common\n+ junixsocket-tipc\n junixsocket-server\n junixsocket-rmi\n junixsocket-mysql\n@@ -263,6 +264,11 @@ In contrast to other implementations, junixsocket extends the Java Sockets API (\n kohlschutter-test-util\n test\n \n+ \n+ com.kohlschutter\n+ kohlschutter-util\n+ test\n+ \n \n com.kohlschutter\n compiler-annotations\ndiff --git a/src/site/markdown/changelog.md b/src/site/markdown/changelog.md\nindex 53b1842d6..d91f712bb 100644\n--- a/src/site/markdown/changelog.md\n+++ b/src/site/markdown/changelog.md\n@@ -5,10 +5,24 @@\n When upgrading from versions older than 2.4.0, please note that junixsocket-core is now a POM-only\n artifact (`pom`); see [Add junixsocket to your project](dependency.html) for details.\n \n-### _(2021-12-xx)_ **junixsocket 2.4.1**\n-\n+### _(2022-06-06)_ **junixsocket 2.5.0**\n+\n+ - New supported platforms: AIX 7 Power64, IBM i Power64, Windows ARM64, Windows Server 2019 & 2022 \n+ - Generic rework to support more than just Unix Domain sockets\n+ - Add support for AF_TIPC (on Linux)\n+ - Add support for using sockets passed as standard input\n+ - Add support for address-specific, non-standard URIs (for example\n+ unix:// and tipc://), as well as socat addresses\n+ - Add support for using FileDescriptor for ProcessBuilder Redirects (Java 9+)\n+ - Add support for peer credentials (PID) on Windows\n+ - Fix Selector logic\n - Fix cross-compilation on Apple Silicon\n+ - Fix a file descriptor leak (regression in 2.4.0)\n+ - Improve behavior on partially unsupported platforms and allow loading of Windows 10 native\n+ library on other Windows versions (e.g., Windows Server 2022, Windows 8.1).\n - Javadoc improvements, Code cleanup\n+ - Deprecate AFUNIXSocketCapability in favor of AFSocketCapability\n+ - Drop support for Java 7\n \n ### _(2021-07-30)_ **junixsocket 2.4.0**\n \ndiff --git a/src/site/markdown/compatibility.md b/src/site/markdown/compatibility.md\nindex 6cc968716..b60339145 100644\n--- a/src/site/markdown/compatibility.md\n+++ b/src/site/markdown/compatibility.md\n@@ -2,20 +2,20 @@\n \n ## Versioning\n \n-junixsocket versions consist of three parts: major, minor and patch (for example, 2.4.0).\n+junixsocket versions consist of three parts: major, minor and patch (for example, 2.5.0).\n \n-`-SNAPSHOT` builds are not considered releases, but merely previews of a future release.\n+\"Minor version\" updates (e.g., 2.4.0 -> 2.5.0) can still bring \"major\" new features but they\n+should be backwards compatible to releases of the same \"major version\" (e.g., 2.x).\n \n-### junixsocket 2.4.0\n+`-SNAPSHOT` builds are not considered releases, but merely previews of a future release.\n \n-junixsocket 2.4.0 is fully compatible with Java 8 and newer (tested up to Java 17).\n+### junixsocket 2.5.0\n \n-There is limited functionality for Java 7 systems: the core functionality (junixsocket-common and\n-junixsocket-server) is supported, but RMI, selftest and demos aren't.\n+junixsocket 2.5.0 is fully compatible with Java 8 and newer (tested up to Java 19).\n \n junixsocket has been tested to work with Oracle's Java 8 JDK, and OpenJDK for newer versions.\n \n-## Supported Architectures\n+## Supported Platforms\n \n The minimum set of supported (out of the box) platforms and processor architectures currently is:\n \n@@ -27,17 +27,84 @@ The minimum set of supported (out of the box) platforms and processor architectu\n * Linux RISC-V 64-bit (rv64ifd / lp64d)\n * Linux ppc64le (POWER 64-bit Little Endian)\n * Solaris x86 64-bit / OpenIndiana\n-* Windows 10 Intel 64-bit\n+* Windows 10 Intel 64-bit and ARM 64-bit\n+* Windows Server 2019\n+* Windows Server 2022\n * FreeBSD (amd64)\n * OpenBSD (amd64)\n * NetBSD (amd64)\n * DragonFlyBSD (amd64)\n+* IBM AIX 7 (POWER 64-bit)\n+* IBM i 7 (POWER 64-bit)\n \n Linux builds should be compatible with all major distributions, including the\n ones using musl (e.g., Alpine Linux).\n \n The native-common binaries for the above platforms are built on recent release versions of\n-either platform. \n+either platform.\n+\n+AIX support verified with IBM AIX 7.1 (7100-05-09), IBM AIX 7.2 (7200-05-03) and IBM AIX 7.3\n+(7300-00-01) on s922 and e980, using IBM J9 VMs (Java 8 and Java 11).\n+\n+IBM i support verified with 7.1 (IBM i 7R1 / 71-11-2984-4), 7.2 (IBM i 7R2 / 72-09-2984-5),\n+7.3 (IBM i 7R3 / 73-07-001), 7.4 (IBM i 7R4 / 74-05-2984-1) on s922 and e980, using IBM J9 64-bit\n+VMs (Java 8, and Java 11 where available).\n \n Support for [custom architectures](customarch.html) can be added by compiling a custom native binary\n on the target machine, or by [cross-compiling](crosscomp.html) using clang/LLVM on a suitable host.\n+\n+## Marginally supported platforms\n+\n+The following platforms can successfully load the JNI library, but since they do not provide\n+support for AF_UNIX, the functionality is currently too limited to call these platforms \"supported\":\n+\n+* Windows 8.1 64-bit\n+* Windows 10 before build 17061\n+* OSv Unikernel (tested with v0.56 on qemu and firecracker); socketpair works.\n+\n+This classification may change with the addition of new features beyond Unix domain sockets.\n+Please reach out if you have some feature in mind that may be supported on these platforms.\n+\n+## Additional Platforms and Architectures\n+\n+Upon request, support for additional systems, platforms and architectures may be added,\n+such as IBM z/OS, OpenVMS, FUJITSU BS2000/OSD, QNX, VxWorks, HP-UX, Haiku, etc.\n+\n+If you are interested in using junixsocket on another platform, or willing to sponsor development\n+(by providing access to such platforms, covering licensing costs, etc.), feel free to\n+[file a ticket](https://github.com/kohlschutter/junixsocket/issues/new/choose)\n+or [contact Christian Kohlschütter via email](mailto:christian@kohlschutter.com).\n+\n+## Selftest\n+\n+A reliable way to ensure that junixsocket works in your environment is to run the \"selftest\".\n+\n+ java -jar junixsocket-selftest-2.5.0-jar-with-dependencies.jar\n+\n+The last line should say \"Selftest PASSED\", and you're good to go.\n+\n+If not, please [file a bug report](https://github.com/kohlschutter/junixsocket/issues) with the\n+output of the selftest.\n+\n+Note: If your target platform supports both 32-bit and 64-bit Java VMs, make sure to use the\n+64-bit version first.\n+\n+## Workarounds/testing for broken setups\n+\n+There is a chance that something is subtly wrong with the combination of junixsocket and your system.\n+\n+To completely disable junixsocket (as if you were on a system for which no native library is available),\n+you can set the following System property: \n+\n+ -Dorg.newsclub.net.unix.library.disable=true\n+ \n+To selectively disable a junixsocket capability, you can specify a System property as follows:\n+\n+ -Dorg.newsclub.net.unix.library.disable.CAPABILITY_XYZ=true\n+ \n+For example, in order to disable the support for passing file descriptors via ancillary messages,\n+specify:\n+\n+ -Dorg.newsclub.net.unix.library.disable.CAPABILITY_FILE_DESCRIPTORS=true\n+\n+The set of available capabilities is enumerated in the `AFSocketCapability` enum.\ndiff --git a/src/site/markdown/customarch.md b/src/site/markdown/customarch.md\nindex 1a069b82d..5c790cc09 100644\n--- a/src/site/markdown/customarch.md\n+++ b/src/site/markdown/customarch.md\n@@ -84,7 +84,7 @@ for development and testing purposes:\n \n com.kohlschutter.junixsocket\n junixsocket-native-custom\n- 2.4.0\n+ 2.5.0\n amd64-Linux-gpp-jni\n \n \n@@ -97,17 +97,31 @@ have your custom artifact, there's a chance it wouldn't even build on other peop\n An alternative is to directly add the junixsocket-native-custom jar to the classpath whenever you\n invoke the Java VM (e.g., your web server, etc.), for example:\n \n- java -cp junixsocket-native-custom-2.4.0-amd64-Linux-gpp-jni.jar:*(...)* *YourMainClass*\n+ java -cp junixsocket-native-custom-2.5.0-amd64-Linux-gpp-jni.jar:*(...)* *YourMainClass*\n \n ## If that doesn't work...\n \n There may be reasons why all this doesn't work, and you simply want to specify the location of\n the native library yourself.\n \n-Simply set the system property `org.newsclub.net.unix.library.override` to the path of the native\n+Simply set the system property `org.newsclub.net.unix.library.override` to the absolute path of the native\n library. For example:\n \n- java -Dorg.newsclub.net.unix.library.override=/path/to/junixsocket-native-2.4.0.so (...)\n+ java -Dorg.newsclub.net.unix.library.override=/path/to/junixsocket-native-2.5.0.so (...)\n \n-> **NOTE** If this override fails to load, an attempt is made to load the standard junixsocket library,\n+If this override fails to load, an attempt is made to load the standard junixsocket library,\n unless the system property `org.newsclub.net.unix.library.override.force` is set to `true`.\n+\n+You can also specify the absolute path with the system property\n+`org.newsclub.net.unix.library.override.force`, which essentially combines these two declarations, i.e.\n+ \n+ java -Dorg.newsclub.net.unix.library.override.force=/path/to/junixsocket-native-2.5.0.so (...)\n+ \n+## If that doesn't work either...\n+\n+You may have a very special system setup. You can always try to manually load the native library\n+directly (using `System.load`, `System.loadLibrary`, etc.). Be sure to do this before any junixsocket\n+class is referenced. You also need to specify the system property\n+`org.newsclub.net.unix.library.override.force` with a value of `provided`, i.e.,\n+\n+ java -Dorg.newsclub.net.unix.library.override.force=provided\ndiff --git a/src/site/markdown/demo.md b/src/site/markdown/demo.md\nindex 67e0a68ea..bd49e6e99 100644\n--- a/src/site/markdown/demo.md\n+++ b/src/site/markdown/demo.md\n@@ -13,18 +13,13 @@ as expected.\n \n junixsocket-dist provides a self-contained jar that performs this selftest:\n \n- java -jar junixsocket-selftest-2.4.0-jar-with-dependencies.jar\n+ java -jar junixsocket-selftest-2.5.0-jar-with-dependencies.jar\n \n The last line should say \"Selftest PASSED\", and you're good to go.\n \n If not, please [file a bug report](https://github.com/kohlschutter/junixsocket/issues) with the\n output of the selftest.\n \n-> **NOTE:** On Java 7, you can use the following command for a very basic check:\n- \n- java -cp junixsocket-common.jar:junixsocket-native-common.jar \\\n- org.newsclub.net.unix.AFUNIXSocket\n-\n ## Running the demos\n \n Simply run\ndiff --git a/src/site/markdown/dependency.md b/src/site/markdown/dependency.md\nindex 8dad8d352..3ba48e840 100644\n--- a/src/site/markdown/dependency.md\n+++ b/src/site/markdown/dependency.md\n@@ -12,7 +12,7 @@ Add the following dependency to your Maven project\n \n com.kohlschutter.junixsocket\n junixsocket-core\n- 2.4.0\n+ 2.5.0\n pom\n \n \n@@ -25,7 +25,7 @@ If you're going to use AFUNIXSocketServer code, add the following dependency:\n \n com.kohlschutter.junixsocket\n junixsocket-server\n- 2.4.0\n+ 2.5.0\n \n \n If you're going to use RMI over Unix sockets, add the following dependency:\n@@ -33,7 +33,7 @@ If you're going to use RMI over Unix sockets, add the following dependency:\n \n com.kohlschutter.junixsocket\n junixsocket-rmi\n- 2.4.0\n+ 2.5.0\n \n \n If you're going to use the mySQL Connector for Unix sockets, add the following dependency:\n@@ -41,22 +41,22 @@ If you're going to use the mySQL Connector for Unix sockets, add the following d\n \n com.kohlschutter.junixsocket\n junixsocket-mysql\n- 2.4.0\n+ 2.5.0\n \n \n ## Gradle\n \n Minimum requirement:\n \n- compile 'com.kohlschutter.junixsocket:junixsocket-core:2.4.0'\n+ compile 'com.kohlschutter.junixsocket:junixsocket-core:2.5.0'\n \n For RMI support, add:\n \n- compile 'com.kohlschutter.junixsocket:junixsocket-rmi:2.4.0'\n+ compile 'com.kohlschutter.junixsocket:junixsocket-rmi:2.5.0'\n \n For MySQL support, add:\n \n- compile 'com.kohlschutter.junixsocket:junixsocket-mysql:2.4.0'\n+ compile 'com.kohlschutter.junixsocket:junixsocket-mysql:2.5.0'\n \n ## jars only\n \n@@ -77,12 +77,12 @@ databases such as PostgreSQL.\n \n Make sure that the following jars are on your classpath:\n \n- * junixsocket-core-2.4.0.jar\n- * junixsocket-common-2.4.0.jar\n- * junixsocket-mysql-2.4.0.jar\n- * mysql-connector-java-8.0.14.jar (earlier versions should work, too)\n- * (typically, omit if you use the custom library below) junixsocket-native-common-2.4.0.jar\n- * (optionally, if you have a custom architecture) junixsocket-native-custom-2.4.0.jar\n+ * junixsocket-core-2.5.0.jar\n+ * junixsocket-common-2.5.0.jar\n+ * junixsocket-mysql-2.5.0.jar\n+ * mysql-connector-java-8.0.14.jar (or newer; earlier versions should work, too)\n+ * (typically, omit if you use the custom library below) junixsocket-native-common-2.5.0.jar\n+ * (optionally, if you have a custom architecture) junixsocket-native-custom-2.5.0.jar\n \n Use the following connection properties (along with `user`, `password`, and other properties you may have).\n \n@@ -110,11 +110,11 @@ to disable SSL with older versions of Connector/J.\n \n Make sure that the following jars are on your classpath:\n \n- * junixsocket-core-2.4.0.jar\n- * junixsocket-common-2.4.0.jar\n- * postgresql-42.2.5.jar (earlier versions should work, too)\n- * (typically, omit if you use the custom library below) junixsocket-native-common-2.4.0.jar\n- * (optionally, if you have a custom architecture) junixsocket-native-custom-2.4.0.jar\n+ * junixsocket-core-2.5.0.jar\n+ * junixsocket-common-2.5.0.jar\n+ * postgresql-42.2.5.jar (or newer; earlier versions should work, too)\n+ * (typically, omit if you use the custom library below) junixsocket-native-common-2.5.0.jar\n+ * (optionally, if you have a custom architecture) junixsocket-native-custom-2.5.0.jar\n \n \n Use the following connection properties (along with `user`, `password`, and other properties you may have).\ndiff --git a/src/site/markdown/peercreds.md b/src/site/markdown/peercreds.md\nindex 6517fa9a7..23286b902 100644\n--- a/src/site/markdown/peercreds.md\n+++ b/src/site/markdown/peercreds.md\n@@ -41,5 +41,5 @@ to authenticate these connections with the help of peer credentials:\n \n ## Not supported by all platforms\n \n- Not all platforms support file descriptors over AF_UNIX. Make sure they're available using\n+Not all platforms support file descriptors over AF_UNIX. Make sure they're available using\n > `AFUNIXSocket.supports(AFUNIXSocketCapability.CAPABILITY_PEER_CREDENTIALS)`.\ndiff --git a/src/site/markdown/release.md b/src/site/markdown/release.md\nindex 549d853c4..68aab3bc7 100644\n--- a/src/site/markdown/release.md\n+++ b/src/site/markdown/release.md\n@@ -119,7 +119,7 @@ The files can be found in\n mvn clean install -Pstrict -Prelease\n \n # after gpgkeyname, specify the key you want to use for signing\n- mvn deploy -Pstrict -Prelease -Psigned -Dgpgkeyname=5034B... -Dgpg.executable=$(which gpg)\n+ mvn deploy -Pstrict -Prelease -Psigned -Dgpgkeyname=your@email.com -Dgpg.executable=$(which gpg)\n \n ##### Notes\n \n", "test_patch": "diff --git a/benchmark-tests/src/test/java/org/newsclub/net/unix/FileDescriptorCastRegressionTest.java b/benchmark-tests/src/test/java/org/newsclub/net/unix/FileDescriptorCastRegressionTest.java\nnew file mode 100644\nindex 000000000..a941a14b8\n--- /dev/null\n+++ b/benchmark-tests/src/test/java/org/newsclub/net/unix/FileDescriptorCastRegressionTest.java\n@@ -0,0 +1,99 @@\n+/*\n+ * Focused regression harness for junixsocket issue #97.\n+ *\n+ * The test body follows the official upstream test introduced by commit\n+ * 2f8f096b84fba1a, with only the forked-process helper adapted for the\n+ * pre-refactor parent tree.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.BufferedReader;\n+import java.io.FileDescriptor;\n+import java.io.InputStreamReader;\n+import java.lang.ProcessBuilder.Redirect;\n+import java.nio.charset.StandardCharsets;\n+import java.nio.file.Paths;\n+import java.util.concurrent.TimeUnit;\n+\n+public final class FileDescriptorCastRegressionTest {\n+ private static final String CLASS_NAME = FileDescriptorCastRegressionTest.class.getName();\n+\n+ private FileDescriptorCastRegressionTest() {\n+ throw new IllegalStateException(\"No instances\");\n+ }\n+\n+ private static void testForkedVMRedirectStdin() throws Exception {\n+ AFUNIXSocketAddress addr = AFUNIXSocketAddress.ofNewTempFile();\n+ try (AFUNIXServerSocket serverSocket = AFUNIXServerSocket.bindOn(addr);\n+ AFUNIXSocket clientConn = AFUNIXSocket.connectTo(addr);\n+ AFUNIXSocket serverConn = serverSocket.accept()) {\n+ if (!addr.getFile().delete()) {\n+ throw new AssertionError(\"Could not unlink temporary socket path\");\n+ }\n+\n+ String javaCommand = Paths.get(System.getProperty(\"java.home\"), \"bin\", \"java\").toString();\n+ ProcessBuilder processBuilder = new ProcessBuilder(javaCommand, \"-cp\",\n+ System.getProperty(\"java.class.path\"), StdinSocketApp.class.getName());\n+ processBuilder.redirectInput(FileDescriptorCast.using(clientConn.getFileDescriptor()).as(\n+ Redirect.class));\n+ processBuilder.redirectError(Redirect.INHERIT);\n+ Process process = processBuilder.start();\n+ try {\n+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(serverConn\n+ .getInputStream(), StandardCharsets.UTF_8))) {\n+ String firstLine = reader.readLine();\n+ if (!\"Hello world\".equals(firstLine)) {\n+ throw new AssertionError(\"Unexpected output: \" + firstLine);\n+ }\n+ String extraLine = reader.readLine();\n+ if (extraLine != null) {\n+ throw new AssertionError(\"Unexpected extra output: \" + extraLine);\n+ }\n+ }\n+ if (!process.waitFor(30, TimeUnit.SECONDS)) {\n+ throw new AssertionError(\"Forked VM did not terminate\");\n+ }\n+ if (process.exitValue() != 0) {\n+ throw new AssertionError(\"Forked VM exited with \" + process.exitValue());\n+ }\n+ } finally {\n+ process.destroyForcibly();\n+ }\n+ }\n+ }\n+\n+ private static void testStdoutFileDescriptorCast() throws Exception {\n+ FileDescriptor descriptor = FileDescriptorCast.using(FileDescriptor.out)\n+ .as(FileDescriptor.class);\n+ if (descriptor != FileDescriptor.out || !descriptor.valid()) {\n+ throw new AssertionError(\"stdout file descriptor cast was not preserved\");\n+ }\n+ }\n+\n+ private static boolean run(String methodName, CheckedRunnable test) {\n+ try {\n+ test.run();\n+ System.out.println(methodName + \" (\" + CLASS_NAME + \") ... ok\");\n+ return true;\n+ } catch (Throwable throwable) {\n+ throwable.printStackTrace(System.out);\n+ System.out.println(methodName + \" (\" + CLASS_NAME + \") ... ERROR\");\n+ return false;\n+ }\n+ }\n+\n+ public static void main(String[] args) {\n+ boolean targetPassed = run(\"testForkedVMRedirectStdin\",\n+ FileDescriptorCastRegressionTest::testForkedVMRedirectStdin);\n+ boolean controlPassed = run(\"testStdoutFileDescriptorCast\",\n+ FileDescriptorCastRegressionTest::testStdoutFileDescriptorCast);\n+ if (!targetPassed || !controlPassed) {\n+ System.exit(1);\n+ }\n+ }\n+\n+ @FunctionalInterface\n+ private interface CheckedRunnable {\n+ void run() throws Exception;\n+ }\n+}\ndiff --git a/benchmark-tests/src/test/java/org/newsclub/net/unix/StdinSocketApp.java b/benchmark-tests/src/test/java/org/newsclub/net/unix/StdinSocketApp.java\nnew file mode 100644\nindex 000000000..74b7cd189\n--- /dev/null\n+++ b/benchmark-tests/src/test/java/org/newsclub/net/unix/StdinSocketApp.java\n@@ -0,0 +1,36 @@\n+/*\n+ * junixsocket\n+ *\n+ * Copyright 2009-2022 Christian Kohlschütter\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.newsclub.net.unix;\n+\n+import java.io.FileDescriptor;\n+import java.io.PrintStream;\n+import java.nio.charset.StandardCharsets;\n+\n+/** A forked-VM helper used by the file-descriptor redirect regression test. */\n+public final class StdinSocketApp {\n+ private StdinSocketApp() {\n+ throw new IllegalStateException(\"No instances\");\n+ }\n+\n+ public static void main(String[] args) throws Exception {\n+ try (PrintStream out = new PrintStream(FileDescriptorCast.using(FileDescriptor.in)\n+ .as(AFUNIXSocket.class).getOutputStream(), true, StandardCharsets.UTF_8.name())) {\n+ out.println(\"Hello world\");\n+ }\n+ }\n+}\n", "FAIL_TO_PASS": ["org.newsclub.net.unix.FileDescriptorCastRegressionTest.testForkedVMRedirectStdin"], "PASS_TO_PASS": ["org.newsclub.net.unix.FileDescriptorCastRegressionTest.testStdoutFileDescriptorCast"]} +{"instance_id": "clb-javac-160", "repo": "kohlschutter/junixsocket", "base_commit": "ba3d20f60e7fbf1a49ae1f4bac09111299d104ee", "problem_statement": "setSoTimeout should force timed out calls to InputStream read to throw java.net.SocketTimeoutException\n**Describe the bug**\r\nSetting `AFUNIXSocket.setSoTimeout` should force timed out calls to `InputStream` read to throw `java.net.SocketTimeoutException`. [See here](https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#setSoTimeout(int)).\r\n\r\nThis does not happen --- instead `read` returns -1.\r\n\r\n**To Reproduce**\r\nHere's some sample code. Assumes that `nc` is available on host platform.\r\n\r\n```\r\nimport org.newsclub.net.unix.AFUNIXServerSocket;\r\nimport org.newsclub.net.unix.AFUNIXSocket;\r\nimport org.newsclub.net.unix.AFUNIXSocketAddress;\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.nio.file.Files;\r\nimport java.nio.file.Path;\r\n\r\npublic class Test {\r\n public static void main(String [] args) throws IOException, InterruptedException {\r\n\r\n AFUNIXServerSocket server = AFUNIXServerSocket.newInstance();\r\n Path temp = Files.createTempFile(\"brainopener\", \".sock\");\r\n final AFUNIXSocketAddress address = new AFUNIXSocketAddress(temp.toFile());\r\n\r\n System.out.println(\"Binding...\");\r\n server.bind(address);\r\n\r\n System.out.println(\"Starting nc...\");\r\n new ProcessBuilder(\"nc\", \"-U\", temp.toString()).start();\r\n\r\n final AFUNIXSocket socket = server.accept();\r\n System.out.println(\"Accepted...\");\r\n socket.setSoTimeout(5000);\r\n byte[] buf = new byte[socket.getReceiveBufferSize()];\r\n int read;\r\n InputStream in = socket.getInputStream();\r\n\r\n while ((read = in.read(buf)) != -1) {\r\n System.out.write(buf, 0, read);\r\n }\r\n\r\n System.out.println(\"Done.\");\r\n }\r\n}\r\n```\r\n\r\n\r\n**Expected behavior**\r\nThe call to `in.read(buf)` should throw `java.net.SocketTimeoutException` in the timeout condition.\r\n\r\n**Environment (please complete the following information):**\r\n - OS: macOS 11.4 (20F71), Darwin 20.5.0. Intel.\r\n - JVM: OpenJDK Runtime Environment AdoptOpenJDK-16.0.1+9 (build 16.0.1+9)\r\n\r\nSelf test output attached.\r\n[selftest.txt](https://github.com/kohlschutter/junixsocket/files/6690032/selftest.txt)\r\n\r\n\r\n**Notes**\r\nShould `OutputStream.write` also throw an exception on timeout condition?\n", "image": {"image_id": "sha256:15fcd1b85e32e2b60df81e65888a891648cf05421aece7b8fbaa0e829be75e24", "pull_reference": "yutu0814/javac-case-160-junixsocket@sha256:15fcd1b85e32e2b60df81e65888a891648cf05421aece7b8fbaa0e829be75e24"}, "cohort": "java_upstream11", "patch": "diff --git a/junixsocket-native/src/main/c/send.c b/junixsocket-native/src/main/c/send.c\nindex bc5a9211..0b664be6 100644\n--- a/junixsocket-native/src/main/c/send.c\n+++ b/junixsocket-native/src/main/c/send.c\n@@ -179,12 +179,12 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_write(\n free(buf);\n \n if(count == -1) {\n- if(errno == EAGAIN || errno == EWOULDBLOCK) {\n+ if(checkNonBlocking(handle, errno)) {\n return 0;\n+ } else {\n+ _throwErrnumException(env, errno, fd);\n+ return -1;\n }\n-\n- _throwErrnumException(env, errno, fd);\n- return -1;\n }\n \n return (jint)count;\n@@ -227,7 +227,6 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_send\n socklen_t sendToLen = addressBufferRef.size;\n \n int ret = sendmsg_wrapper(env, handle, dataBufferRef.buf, length, sendTo, sendToLen, opt, ancSupp);\n-\n if(ret < 0) {\n ret = 0;\n if(socket_errno != EAGAIN && errno != EWOULDBLOCK && (errno != ENOBUFS || (opt & org_newsclub_net_unix_NativeUnixSocket_OPT_NON_BLOCKING) == 0 )) {\n", "test_patch": "diff --git a/junixsocket-common/src/test/java/org/newsclub/net/unix/SoTimeoutTest.java b/junixsocket-common/src/test/java/org/newsclub/net/unix/SoTimeoutTest.java\nindex c1731641..b1ff3691 100644\n--- a/junixsocket-common/src/test/java/org/newsclub/net/unix/SoTimeoutTest.java\n+++ b/junixsocket-common/src/test/java/org/newsclub/net/unix/SoTimeoutTest.java\n@@ -24,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;\n import java.io.File;\n import java.io.IOException;\n import java.io.InputStream;\n+import java.io.OutputStream;\n import java.net.Socket;\n import java.net.SocketException;\n import java.net.SocketTimeoutException;\n@@ -105,7 +106,7 @@ public class SoTimeoutTest extends SocketTestBase {\n }\n \n @Test\n- public void testSocketTimeoutException() throws Exception {\n+ public void testSocketTimeoutExceptionRead() throws Exception {\n final File tempFile = newTempFile();\n final AFUNIXSocketAddress address = AFUNIXSocketAddress.of(tempFile);\n try (AFUNIXServerSocket server = AFUNIXServerSocket.bindOn(address);\n@@ -123,4 +124,25 @@ public class SoTimeoutTest extends SocketTestBase {\n tempFile.delete();\n }\n }\n+\n+ @Test\n+ public void testSocketTimeoutExceptionWrite() throws Exception {\n+ final File tempFile = newTempFile();\n+ final AFUNIXSocketAddress address = AFUNIXSocketAddress.of(tempFile);\n+ try (AFUNIXServerSocket server = AFUNIXServerSocket.bindOn(address);\n+ AFUNIXSocket client = AFUNIXSocket.connectTo(address)) {\n+\n+ final AFUNIXSocket socket = server.accept();\n+ socket.setSoTimeout(500);\n+ byte[] buf = new byte[socket.getSendBufferSize()];\n+ OutputStream out = socket.getOutputStream();\n+\n+ assertThrows(SocketTimeoutException.class, () -> {\n+ out.write(buf);\n+ out.write(buf);\n+ });\n+ } finally {\n+ tempFile.delete();\n+ }\n+ }\n }\n", "FAIL_TO_PASS": ["org.newsclub.net.unix.SoTimeoutTest.testSocketTimeoutExceptionWrite"], "PASS_TO_PASS": ["org.newsclub.net.unix.SoTimeoutTest.testSocketTimeoutExceptionRead"]} +{"instance_id": "clb-javac-161", "repo": "kohlschutter/junixsocket", "base_commit": "1df1513c64079a5100cdc2a372558e1f77849c0f", "problem_statement": "setSoTimeout should force timed out calls to InputStream read to throw java.net.SocketTimeoutException\n**Describe the bug**\r\nSetting `AFUNIXSocket.setSoTimeout` should force timed out calls to `InputStream` read to throw `java.net.SocketTimeoutException`. [See here](https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#setSoTimeout(int)).\r\n\r\nThis does not happen --- instead `read` returns -1.\r\n\r\n**To Reproduce**\r\nHere's some sample code. Assumes that `nc` is available on host platform.\r\n\r\n```\r\nimport org.newsclub.net.unix.AFUNIXServerSocket;\r\nimport org.newsclub.net.unix.AFUNIXSocket;\r\nimport org.newsclub.net.unix.AFUNIXSocketAddress;\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.nio.file.Files;\r\nimport java.nio.file.Path;\r\n\r\npublic class Test {\r\n public static void main(String [] args) throws IOException, InterruptedException {\r\n\r\n AFUNIXServerSocket server = AFUNIXServerSocket.newInstance();\r\n Path temp = Files.createTempFile(\"brainopener\", \".sock\");\r\n final AFUNIXSocketAddress address = new AFUNIXSocketAddress(temp.toFile());\r\n\r\n System.out.println(\"Binding...\");\r\n server.bind(address);\r\n\r\n System.out.println(\"Starting nc...\");\r\n new ProcessBuilder(\"nc\", \"-U\", temp.toString()).start();\r\n\r\n final AFUNIXSocket socket = server.accept();\r\n System.out.println(\"Accepted...\");\r\n socket.setSoTimeout(5000);\r\n byte[] buf = new byte[socket.getReceiveBufferSize()];\r\n int read;\r\n InputStream in = socket.getInputStream();\r\n\r\n while ((read = in.read(buf)) != -1) {\r\n System.out.write(buf, 0, read);\r\n }\r\n\r\n System.out.println(\"Done.\");\r\n }\r\n}\r\n```\r\n\r\n\r\n**Expected behavior**\r\nThe call to `in.read(buf)` should throw `java.net.SocketTimeoutException` in the timeout condition.\r\n\r\n**Environment (please complete the following information):**\r\n - OS: macOS 11.4 (20F71), Darwin 20.5.0. Intel.\r\n - JVM: OpenJDK Runtime Environment AdoptOpenJDK-16.0.1+9 (build 16.0.1+9)\r\n\r\nSelf test output attached.\r\n[selftest.txt](https://github.com/kohlschutter/junixsocket/files/6690032/selftest.txt)\r\n\r\n\r\n**Notes**\r\nShould `OutputStream.write` also throw an exception on timeout condition?\n", "image": {"image_id": "sha256:969c2650967701f77c0d620466db2df05b0f5f8b6706167dbf117545f54a2ad3", "pull_reference": "yutu0814/javac-case-161-junixsocket@sha256:969c2650967701f77c0d620466db2df05b0f5f8b6706167dbf117545f54a2ad3"}, "cohort": "java_upstream11", "patch": "diff --git a/junixsocket-native/src/main/c/receive.c b/junixsocket-native/src/main/c/receive.c\nindex 0077dc2..89378b0 100644\n--- a/junixsocket-native/src/main/c/receive.c\n+++ b/junixsocket-native/src/main/c/receive.c\n@@ -202,7 +202,19 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_read(\n #if defined(junixsocket_use_poll_for_read)\n int ret = pollWithTimeout(env, fd, handle, 0);\n if(ret < 1) {\n- return -1;\n+ if(ret == -1) {\n+ _throwErrnumException(env, errno, fd);\n+ return -1;\n+ }\n+ int flags = fcntl(handle, F_GETFL);\n+ if (flags != -1 && (flags & O_NONBLOCK)) {\n+ // non-blocking socket\n+ return 0;\n+ } else {\n+ // timeout on blocking socket\n+ _throwException(env, kExceptionSocketTimeoutException, \"timeout\");\n+ return -1;\n+ }\n }\n #endif\n \n@@ -259,6 +271,10 @@ JNIEXPORT jint JNICALL Java_org_newsclub_net_unix_NativeUnixSocket_receive\n \n int ret = pollWithTimeout(env, fd, handle, hardTimeoutMillis);\n if(ret < 1) {\n+ if(ret == -1) {\n+ _throwErrnumException(env, errno, fd);\n+ return -1;\n+ }\n int flags = fcntl(handle, F_GETFL);\n if (flags != -1 && (flags & O_NONBLOCK)) {\n // non-blocking socket\n", "test_patch": "diff --git a/junixsocket-common/src/test/java/org/newsclub/net/unix/SoTimeoutTest.java b/junixsocket-common/src/test/java/org/newsclub/net/unix/SoTimeoutTest.java\nindex 00be130..c173164 100644\n--- a/junixsocket-common/src/test/java/org/newsclub/net/unix/SoTimeoutTest.java\n+++ b/junixsocket-common/src/test/java/org/newsclub/net/unix/SoTimeoutTest.java\n@@ -18,12 +18,15 @@\n package org.newsclub.net.unix;\n \n import static org.junit.jupiter.api.Assertions.assertFalse;\n+import static org.junit.jupiter.api.Assertions.assertThrows;\n import static org.junit.jupiter.api.Assertions.assertTrue;\n \n+import java.io.File;\n import java.io.IOException;\n import java.io.InputStream;\n import java.net.Socket;\n import java.net.SocketException;\n+import java.net.SocketTimeoutException;\n import java.util.concurrent.Semaphore;\n import java.util.concurrent.TimeUnit;\n \n@@ -100,4 +103,24 @@ public class SoTimeoutTest extends SocketTestBase {\n }\n }\n }\n+\n+ @Test\n+ public void testSocketTimeoutException() throws Exception {\n+ final File tempFile = newTempFile();\n+ final AFUNIXSocketAddress address = AFUNIXSocketAddress.of(tempFile);\n+ try (AFUNIXServerSocket server = AFUNIXServerSocket.bindOn(address);\n+ AFUNIXSocket client = AFUNIXSocket.connectTo(address)) {\n+\n+ final AFUNIXSocket socket = server.accept();\n+ socket.setSoTimeout(500);\n+ byte[] buf = new byte[socket.getReceiveBufferSize()];\n+ InputStream in = socket.getInputStream();\n+\n+ assertThrows(SocketTimeoutException.class, () -> {\n+ in.read(buf);\n+ });\n+ } finally {\n+ tempFile.delete();\n+ }\n+ }\n }\n", "FAIL_TO_PASS": ["org.newsclub.net.unix.SoTimeoutTest.testSocketTimeoutException"], "PASS_TO_PASS": ["org.newsclub.net.unix.SoTimeoutTest.issue14Pass"]} +{"instance_id": "clb-javac-175", "repo": "kohlschutter/junixsocket", "base_commit": "2a159927761424440f7dbd7674992e4b5273a459", "problem_statement": "Sending large ByteBuffers is broken\n**Describe the bug**\r\n\r\nper @kevink-sq \r\n\r\nwe ran into response problems when using the jetty org.newsclub.net.unix.jetty.AFSocketServerConnector in version 2.6.2 in production. We were looking for alternatives to address the jnr-unixsocket load issue and tried junixsocket.\r\n\r\nsymptoms:\r\n\r\n* when the jetty service using the AFSocketServerConnector returned a response greater than 32KB, the same first 32KB (exactly every 0x8000 bytes) was repeated. For example, if the response was 100KB, then the same first 32KB was repeated until 100KB.\r\n* server did not log a warning or error and the request looked like a 200 response on the server side. Only when client attempted to parse the response was there an error (especially if it was supposed to be structured data).\r\n* OS socket SO_SNDBUF was verified to be 212MB.\r\n* Swapping out the connector to Jetty 10's UnixDomainServerConnector fixed the issue (note swapping the connector was the only diff in the server, no other changes/updates were present)\r\n\n", "image": {"image_id": "sha256:d5eaaed040c90536d22f0ef5548ad00d2ec61b59e698d725014695479df8a20d", "pull_reference": "yutu0814/javac-case-175-junixsocket@sha256:d5eaaed040c90536d22f0ef5548ad00d2ec61b59e698d725014695479df8a20d"}, "cohort": "java_upstream11", "patch": "diff --git a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFCore.java b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFCore.java\nindex 7df1083..dcbb00b 100644\n--- a/junixsocket-common/src/main/java/org/newsclub/net/unix/AFCore.java\n+++ b/junixsocket-common/src/main/java/org/newsclub/net/unix/AFCore.java\n@@ -138,7 +138,9 @@ class AFCore extends CleanableState {\n }\n if (buf != dst) { // NOPMD\n buf.limit(count);\n- dst.put(buf);\n+ while (buf.hasRemaining()) {\n+ dst.put(buf);\n+ }\n } else {\n if (count < 0) {\n throw new IllegalStateException();\n@@ -189,13 +191,7 @@ class AFCore extends CleanableState {\n \n bufPos = buf.position();\n \n- // Java 16: buf.put(bufPos, src, src.position(), Math.min(buf.limit(), src.limit()));\n- int limit = src.limit();\n- if (limit > buf.limit()) {\n- src.limit(buf.limit());\n- buf.put(src);\n- src.limit(limit);\n- } else {\n+ while (src.hasRemaining() && buf.hasRemaining()) {\n buf.put(src);\n }\n \ndiff --git a/junixsocket-jetty/pom.xml b/junixsocket-jetty/pom.xml\nindex 1223106..5a17878 100644\n--- a/junixsocket-jetty/pom.xml\n+++ b/junixsocket-jetty/pom.xml\n@@ -56,6 +56,14 @@\n ${jetty.version}\n test\n \n+ \n \n org.hamcrest\n hamcrest\n", "test_patch": "diff --git a/junixsocket-jetty/src/test/java/org/eclipse/jetty/unixdomain/server/UnixDomainTest.java b/junixsocket-jetty/src/test/java/org/eclipse/jetty/unixdomain/server/UnixDomainTest.java\nindex 76e3a6d..9bfa373 100644\n--- a/junixsocket-jetty/src/test/java/org/eclipse/jetty/unixdomain/server/UnixDomainTest.java\n+++ b/junixsocket-jetty/src/test/java/org/eclipse/jetty/unixdomain/server/UnixDomainTest.java\n@@ -31,6 +31,7 @@\n package org.eclipse.jetty.unixdomain.server;\n \n import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.junit.jupiter.api.Assertions.assertArrayEquals;\n import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;\n import static org.junit.jupiter.api.Assertions.assertEquals;\n import static org.junit.jupiter.api.Assertions.assertNotNull;\n@@ -45,6 +46,7 @@ import java.net.SocketException;\n import java.nio.file.Files;\n import java.nio.file.Path;\n import java.util.Objects;\n+import java.util.Random;\n import java.util.concurrent.TimeUnit;\n \n import org.eclipse.jetty.client.HttpClient;\n@@ -75,6 +77,7 @@ import org.newsclub.net.unix.AFUNIXSocketAddress;\n import org.newsclub.net.unix.jetty.AFSocketClientConnector;\n import org.newsclub.net.unix.jetty.AFSocketServerConnector;\n \n+import jakarta.servlet.ServletOutputStream;\n import jakarta.servlet.http.HttpServletRequest;\n import jakarta.servlet.http.HttpServletResponse;\n \n@@ -317,4 +320,43 @@ public class UnixDomainTest {\n }\n return ret.toString();\n }\n+\n+ @Test\n+ public void testLargeBody() throws Exception {\n+ String uri = \"http://localhost:1234/path\";\n+\n+ byte[] payload = new byte[512 * 1024]; // 512k\n+ Random random = new Random();\n+ for (int i = 0, n = payload.length; i < n; i++) {\n+ payload[i] = (byte) (random.nextInt() & 0xFF);\n+ }\n+\n+ start(new AbstractHandler() {\n+ @Override\n+ public void handle(String target, Request jettyRequest, HttpServletRequest request,\n+ HttpServletResponse response) throws IOException {\n+ jettyRequest.setHandled(true);\n+\n+ response.setContentType(\" application/octet-stream\");\n+ try (ServletOutputStream out = response.getOutputStream()) {\n+ out.write(payload);\n+ }\n+ }\n+ });\n+\n+ // ClientConnector clientConnector = ClientConnector.forUnixDomain(unixDomainPath);\n+ ClientConnector clientConnector = AFSocketClientConnector.withSocketAddress(AFUNIXSocketAddress\n+ .of(unixDomainPath));\n+ HttpClient httpClient = new HttpClient(new HttpClientTransportDynamic(clientConnector));\n+ httpClient.start();\n+ try {\n+ ContentResponse response = httpClient.newRequest(uri).timeout(5, TimeUnit.SECONDS).send();\n+\n+ assertEquals(HttpStatus.OK_200, response.getStatus());\n+ byte[] data = response.getContent();\n+ assertArrayEquals(payload, data);\n+ } finally {\n+ httpClient.stop();\n+ }\n+ }\n }\n\\ No newline at end of file\n", "FAIL_TO_PASS": ["org.eclipse.jetty.unixdomain.server.UnixDomainTest.testLargeBody"], "PASS_TO_PASS": ["org.eclipse.jetty.unixdomain.server.UnixDomainTest.testHTTPOverUnixDomain"]} +{"instance_id": "clb-javac-194", "repo": "MDSplus/mdsplus", "base_commit": "a73d6e87149698e49026e3bf8055efc6bbe71d90", "problem_statement": "Issuing (e.g. from tdic) TreeSetDefault('\\null') crashes tdishr\nApparently only names that start with \\null crash tdishr. Every other name (correct or incorrect) does not crash the system. \n", "image": {"image_id": "sha256:d12be7067ce51c31c085739c3a3fc4c69d273b8751059234700870a2ce9e5606", "pull_reference": "yutu0814/javac-case-194-mdsplus@sha256:d12be7067ce51c31c085739c3a3fc4c69d273b8751059234700870a2ce9e5606"}, "cohort": "java_upstream11", "patch": "diff --git a/treeshr/TreeFindNode.c b/treeshr/TreeFindNode.c\nindex a2ca7950b..547738eb0 100644\n--- a/treeshr/TreeFindNode.c\n+++ b/treeshr/TreeFindNode.c\n@@ -147,7 +147,12 @@ EXPORT int _TreeFindNode(void *dbid, char const *path, int *outnid)\n return TreeNOT_OPEN;\n if (dblist->remote)\n return FindNodeRemote(dblist, path, outnid);\n- \n+\n+ if (path && (path[0] == '\\n')) {\n+ status = TreeNNF;\n+ goto done;\n+ }\n+\n status = WildParse(path, &ctx, &wild);\n if STATUS_NOT_OK\n goto done;\n@@ -188,7 +193,7 @@ STATIC_ROUTINE void FreeSearchCtx(SEARCH_CTX *ctx)\n }\n STATIC_ROUTINE NODELIST *Search(PINO_DATABASE *dblist, SEARCH_CTX *ctx, SEARCH_TERM *term, NODE *start, NODELIST **tail)\n {\n- NODELIST *nodes = Find(dblist, term, start, tail);\n+ NODELIST *nodes = term ? Find(dblist, term, start, tail) : NULL;\n if (nodes) {\n NODELIST *more_nodes = NULL;\n NODELIST *more_tail = NULL; \ndiff --git a/treeshr/TreeFindNodeWild.l b/treeshr/TreeFindNodeWild.l\nindex e3b7d0867..ad1bd8b84 100644\n--- a/treeshr/TreeFindNodeWild.l\n+++ b/treeshr/TreeFindNodeWild.l\n@@ -153,11 +153,8 @@ EXPORT void FreeSearchTerms(SEARCH_TERM *terms)\n \n static char *strtrim(char *str)\n {\n- char *q = str;\n- while (* q) q++;\n- do { q--; } while (isspace(* q));\n- q++;\n- *q = '\\0';\n+ char *q;\n+ for (q=str+strlen(str)-1; (q > str) && isspace(*q); q--) *q='\\0';\n return str;\n }\n \ndiff --git a/treeshr/lex.yytreepath.c b/treeshr/lex.yytreepath.c\nindex d864239d5..fb3391b53 100644\n--- a/treeshr/lex.yytreepath.c\n+++ b/treeshr/lex.yytreepath.c\n@@ -8,7 +8,7 @@\n #define FLEX_SCANNER\n #define YY_FLEX_MAJOR_VERSION 2\n #define YY_FLEX_MINOR_VERSION 6\n-#define YY_FLEX_SUBMINOR_VERSION 0\n+#define YY_FLEX_SUBMINOR_VERSION 1\n #if YY_FLEX_SUBMINOR_VERSION > 0\n #define FLEX_BETA\n #endif\n@@ -87,25 +87,13 @@ typedef unsigned int flex_uint32_t;\n \n #endif /* ! FLEXINT_H */\n \n-#ifdef __cplusplus\n-\n-/* The \"const\" storage-class-modifier is valid. */\n-#define YY_USE_CONST\n-\n-#else\t/* ! __cplusplus */\n-\n-/* C99 requires __STDC__ to be defined as 1. */\n-#if defined (__STDC__)\n-\n-#define YY_USE_CONST\n-\n-#endif\t/* defined (__STDC__) */\n-#endif\t/* ! __cplusplus */\n-\n-#ifdef YY_USE_CONST\n+/* TODO: this is always defined, so inline it */\n #define yyconst const\n+\n+#if defined(__GNUC__) && __GNUC__ >= 3\n+#define yynoreturn __attribute__((__noreturn__))\n #else\n-#define yyconst\n+#define yynoreturn\n #endif\n \n /* Returned upon end-of-file. */\n@@ -218,12 +206,12 @@ struct yy_buffer_state\n \t/* Size of input buffer in bytes, not including room for EOB\n \t * characters.\n \t */\n-\tyy_size_t yy_buf_size;\n+\tint yy_buf_size;\n \n \t/* Number of characters read into yy_ch_buf, not including EOB\n \t * characters.\n \t */\n-\tyy_size_t yy_n_chars;\n+\tint yy_n_chars;\n \n \t/* Whether we \"own\" the buffer - i.e., we know we created it,\n \t * and can realloc() it to grow it, and should free() it to\n@@ -302,7 +290,7 @@ static void yytreepath_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yysca\n \n YY_BUFFER_STATE yytreepath_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );\n YY_BUFFER_STATE yytreepath_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );\n-YY_BUFFER_STATE yytreepath_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner );\n+YY_BUFFER_STATE yytreepath_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );\n \n void *yytreepathalloc (yy_size_t ,yyscan_t yyscanner );\n void *yytreepathrealloc (void *,yy_size_t ,yyscan_t yyscanner );\n@@ -346,17 +334,14 @@ typedef int yy_state_type;\n static yy_state_type yy_get_previous_state (yyscan_t yyscanner );\n static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner);\n static int yy_get_next_buffer (yyscan_t yyscanner );\n-#if defined(__GNUC__) && __GNUC__ >= 3\n-__attribute__((__noreturn__))\n-#endif\n-static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner );\n+static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );\n \n /* Done after the current pattern has been matched and before the\n * corresponding action - sets up yytext.\n */\n #define YY_DO_BEFORE_ACTION \\\n \tyyg->yytext_ptr = yy_bp; \\\n-\tyyleng = (size_t) (yy_cp - yy_bp); \\\n+\tyyleng = (int) (yy_cp - yy_bp); \\\n \tyyg->yy_hold_char = *yy_cp; \\\n \t*yy_cp = '\\0'; \\\n \tyyg->yy_c_buf_p = yy_cp;\n@@ -563,7 +548,7 @@ STATIC_ROUTINE int isPunctuation(char c)\n }\n \n #define YY_NO_INPUT 1\n-#line 567 \"lex.yytreepath.c\"\n+#line 552 \"lex.yytreepath.c\"\n \n #define INITIAL 0\n \n@@ -590,8 +575,8 @@ struct yyguts_t\n size_t yy_buffer_stack_max; /**< capacity of stack. */\n YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */\n char yy_hold_char;\n- yy_size_t yy_n_chars;\n- yy_size_t yyleng_r;\n+ int yy_n_chars;\n+ int yyleng_r;\n char *yy_c_buf_p;\n int yy_init;\n int yy_start;\n@@ -638,7 +623,7 @@ FILE *yytreepathget_out (yyscan_t yyscanner );\n \n void yytreepathset_out (FILE * _out_str ,yyscan_t yyscanner );\n \n-yy_size_t yytreepathget_leng (yyscan_t yyscanner );\n+\t\t\tint yytreepathget_leng (yyscan_t yyscanner );\n \n char *yytreepathget_text (yyscan_t yyscanner );\n \n@@ -699,7 +684,7 @@ static int input (yyscan_t yyscanner );\n /* This used to be an fputs(), but since the string might contain NUL's,\n * we now use fwrite().\n */\n-#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0)\n+#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0)\n #endif\n \n /* Gets input and stuffs it into \"buf\". number of characters read, or YY_NULL,\n@@ -710,7 +695,7 @@ static int input (yyscan_t yyscanner );\n \tif ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \\\n \t\t{ \\\n \t\tint c = '*'; \\\n-\t\tsize_t n; \\\n+\t\tint n; \\\n \t\tfor ( n = 0; n < max_size && \\\n \t\t\t (c = getc( yyin )) != EOF && c != '\\n'; ++n ) \\\n \t\t\tbuf[n] = (char) c; \\\n@@ -723,7 +708,7 @@ static int input (yyscan_t yyscanner );\n \telse \\\n \t\t{ \\\n \t\terrno=0; \\\n-\t\twhile ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \\\n+\t\twhile ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \\\n \t\t\t{ \\\n \t\t\tif( errno != EINTR) \\\n \t\t\t\t{ \\\n@@ -825,7 +810,7 @@ YY_DECL\n \t{\n #line 45 \"TreeFindNodeWild.l\"\n \n-#line 829 \"lex.yytreepath.c\"\n+#line 814 \"lex.yytreepath.c\"\n \n \twhile ( /*CONSTCOND*/1 )\t\t/* loops until end-of-file is reached */\n \t\t{\n@@ -856,7 +841,7 @@ yy_match:\n \t\t\t\tif ( yy_current_state >= 136 )\n \t\t\t\t\tyy_c = yy_meta[(unsigned int) yy_c];\n \t\t\t\t}\n-\t\t\tyy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];\n+\t\t\tyy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];\n \t\t\t++yy_cp;\n \t\t\t}\n \t\twhile ( yy_base[yy_current_state] != 163 );\n@@ -986,7 +971,7 @@ YY_RULE_SETUP\n #line 88 \"TreeFindNodeWild.l\"\n ECHO;\n \tYY_BREAK\n-#line 990 \"lex.yytreepath.c\"\n+#line 975 \"lex.yytreepath.c\"\n \n \tcase YY_END_OF_BUFFER:\n \t\t{\n@@ -1186,7 +1171,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)\n \n \t\t\tif ( b->yy_is_our_buffer )\n \t\t\t\t{\n-\t\t\t\tyy_size_t new_size = b->yy_buf_size * 2;\n+\t\t\t\tint new_size = b->yy_buf_size * 2;\n \n \t\t\t\tif ( new_size <= 0 )\n \t\t\t\t\tb->yy_buf_size += b->yy_buf_size / 8;\n@@ -1195,11 +1180,11 @@ static int yy_get_next_buffer (yyscan_t yyscanner)\n \n \t\t\t\tb->yy_ch_buf = (char *)\n \t\t\t\t\t/* Include room in for 2 EOB chars. */\n-\t\t\t\t\tyytreepathrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );\n+\t\t\t\t\tyytreepathrealloc((void *) b->yy_ch_buf,(yy_size_t) (b->yy_buf_size + 2) ,yyscanner );\n \t\t\t\t}\n \t\t\telse\n \t\t\t\t/* Can't grow it, we don't own it. */\n-\t\t\t\tb->yy_ch_buf = 0;\n+\t\t\t\tb->yy_ch_buf = NULL;\n \n \t\t\tif ( ! b->yy_ch_buf )\n \t\t\t\tYY_FATAL_ERROR(\n@@ -1241,10 +1226,10 @@ static int yy_get_next_buffer (yyscan_t yyscanner)\n \telse\n \t\tret_val = EOB_ACT_CONTINUE_SCAN;\n \n-\tif ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {\n+\tif ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {\n \t\t/* Extend the array by 50%, plus the number we really need. */\n-\t\tyy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);\n-\t\tYY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yytreepathrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );\n+\t\tint new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);\n+\t\tYY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yytreepathrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,(yy_size_t) new_size ,yyscanner );\n \t\tif ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )\n \t\t\tYY_FATAL_ERROR( \"out of dynamic memory in yy_get_next_buffer()\" );\n \t}\n@@ -1283,7 +1268,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)\n \t\t\tif ( yy_current_state >= 136 )\n \t\t\t\tyy_c = yy_meta[(unsigned int) yy_c];\n \t\t\t}\n-\t\tyy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];\n+\t\tyy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];\n \t\t}\n \n \treturn yy_current_state;\n@@ -1312,7 +1297,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)\n \t\tif ( yy_current_state >= 136 )\n \t\t\tyy_c = yy_meta[(unsigned int) yy_c];\n \t\t}\n-\tyy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];\n+\tyy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];\n \tyy_is_jam = (yy_current_state == 135);\n \n \t(void)yyg;\n@@ -1348,7 +1333,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)\n \n \t\telse\n \t\t\t{ /* need more input */\n-\t\t\tyy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr;\n+\t\t\tint offset = yyg->yy_c_buf_p - yyg->yytext_ptr;\n \t\t\t++yyg->yy_c_buf_p;\n \n \t\t\tswitch ( yy_get_next_buffer( yyscanner ) )\n@@ -1372,7 +1357,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)\n \t\t\t\tcase EOB_ACT_END_OF_FILE:\n \t\t\t\t\t{\n \t\t\t\t\tif ( yytreepathwrap(yyscanner ) )\n-\t\t\t\t\t\treturn EOF;\n+\t\t\t\t\t\treturn 0;\n \n \t\t\t\t\tif ( ! yyg->yy_did_buffer_switch_on_eof )\n \t\t\t\t\t\tYY_NEW_FILE;\n@@ -1478,12 +1463,12 @@ static void yytreepath_load_buffer_state (yyscan_t yyscanner)\n \tif ( ! b )\n \t\tYY_FATAL_ERROR( \"out of dynamic memory in yytreepath_create_buffer()\" );\n \n-\tb->yy_buf_size = (yy_size_t)size;\n+\tb->yy_buf_size = size;\n \n \t/* yy_ch_buf has to be 2 characters longer than the size given because\n \t * we need to put in 2 end-of-buffer characters.\n \t */\n-\tb->yy_ch_buf = (char *) yytreepathalloc(b->yy_buf_size + 2 ,yyscanner );\n+\tb->yy_ch_buf = (char *) yytreepathalloc((yy_size_t) (b->yy_buf_size + 2) ,yyscanner );\n \tif ( ! b->yy_ch_buf )\n \t\tYY_FATAL_ERROR( \"out of dynamic memory in yytreepath_create_buffer()\" );\n \n@@ -1630,7 +1615,7 @@ void yytreepathpop_buffer_state (yyscan_t yyscanner)\n */\n static void yytreepathensure_buffer_stack (yyscan_t yyscanner)\n {\n-\tyy_size_t num_to_alloc;\n+\tint num_to_alloc;\n struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;\n \n \tif (!yyg->yy_buffer_stack) {\n@@ -1686,16 +1671,16 @@ YY_BUFFER_STATE yytreepath_scan_buffer (char * base, yy_size_t size , yyscan_t\n \t base[size-2] != YY_END_OF_BUFFER_CHAR ||\n \t base[size-1] != YY_END_OF_BUFFER_CHAR )\n \t\t/* They forgot to leave room for the EOB's. */\n-\t\treturn 0;\n+\t\treturn NULL;\n \n \tb = (YY_BUFFER_STATE) yytreepathalloc(sizeof( struct yy_buffer_state ) ,yyscanner );\n \tif ( ! b )\n \t\tYY_FATAL_ERROR( \"out of dynamic memory in yytreepath_scan_buffer()\" );\n \n-\tb->yy_buf_size = size - 2;\t/* \"- 2\" to take care of EOB's */\n+\tb->yy_buf_size = (int) (size - 2);\t/* \"- 2\" to take care of EOB's */\n \tb->yy_buf_pos = b->yy_ch_buf = base;\n \tb->yy_is_our_buffer = 0;\n-\tb->yy_input_file = 0;\n+\tb->yy_input_file = NULL;\n \tb->yy_n_chars = b->yy_buf_size;\n \tb->yy_is_interactive = 0;\n \tb->yy_at_bol = 1;\n@@ -1718,7 +1703,7 @@ YY_BUFFER_STATE yytreepath_scan_buffer (char * base, yy_size_t size , yyscan_t\n YY_BUFFER_STATE yytreepath_scan_string (yyconst char * yystr , yyscan_t yyscanner)\n {\n \n-\treturn yytreepath_scan_bytes(yystr,strlen(yystr) ,yyscanner);\n+\treturn yytreepath_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner);\n }\n \n /** Setup the input buffer state to scan the given bytes. The next call to yytreepathlex() will\n@@ -1728,7 +1713,7 @@ YY_BUFFER_STATE yytreepath_scan_string (yyconst char * yystr , yyscan_t yyscanne\n * @param yyscanner The scanner object.\n * @return the newly allocated buffer state object.\n */\n-YY_BUFFER_STATE yytreepath_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner)\n+YY_BUFFER_STATE yytreepath_scan_bytes (yyconst char * yybytes, int _yybytes_len , yyscan_t yyscanner)\n {\n \tYY_BUFFER_STATE b;\n \tchar *buf;\n@@ -1736,7 +1721,7 @@ YY_BUFFER_STATE yytreepath_scan_bytes (yyconst char * yybytes, yy_size_t _yyby\n \tyy_size_t i;\n \n \t/* Get memory for full buffer, including space for trailing EOB's. */\n-\tn = _yybytes_len + 2;\n+\tn = (yy_size_t) _yybytes_len + 2;\n \tbuf = (char *) yytreepathalloc(n ,yyscanner );\n \tif ( ! buf )\n \t\tYY_FATAL_ERROR( \"out of dynamic memory in yytreepath_scan_bytes()\" );\n@@ -1762,7 +1747,7 @@ YY_BUFFER_STATE yytreepath_scan_bytes (yyconst char * yybytes, yy_size_t _yyby\n #define YY_EXIT_FAILURE 2\n #endif\n \n-static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)\n+static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)\n {\n \tstruct yyguts_t * yyg = (struct yyguts_t*)yyscanner;\n \t(void)yyg;\n@@ -1845,7 +1830,7 @@ FILE *yytreepathget_out (yyscan_t yyscanner)\n /** Get the length of the current token.\n * @param yyscanner The scanner object.\n */\n-yy_size_t yytreepathget_leng (yyscan_t yyscanner)\n+int yytreepathget_leng (yyscan_t yyscanner)\n {\n struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;\n return yyleng;\n@@ -2004,10 +1989,10 @@ static int yy_init_globals (yyscan_t yyscanner)\n * This function is called from yytreepathlex_destroy(), so don't allocate here.\n */\n \n- yyg->yy_buffer_stack = 0;\n+ yyg->yy_buffer_stack = NULL;\n yyg->yy_buffer_stack_top = 0;\n yyg->yy_buffer_stack_max = 0;\n- yyg->yy_c_buf_p = (char *) 0;\n+ yyg->yy_c_buf_p = NULL;\n yyg->yy_init = 0;\n yyg->yy_start = 0;\n \n@@ -2020,8 +2005,8 @@ static int yy_init_globals (yyscan_t yyscanner)\n yyin = stdin;\n yyout = stdout;\n #else\n- yyin = (FILE *) 0;\n- yyout = (FILE *) 0;\n+ yyin = NULL;\n+ yyout = NULL;\n #endif\n \n /* For future reference: Set errno on error, since we are called by\n@@ -2091,7 +2076,7 @@ void *yytreepathalloc (yy_size_t size , yyscan_t yyscanner)\n {\n \tstruct yyguts_t * yyg = (struct yyguts_t*)yyscanner;\n \t(void)yyg;\n-\treturn (void *) malloc( size );\n+\treturn malloc(size);\n }\n \n void *yytreepathrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)\n@@ -2106,7 +2091,7 @@ void *yytreepathrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)\n \t * any pointer type to void*, and deal with argument conversions\n \t * as though doing an assignment.\n \t */\n-\treturn (void *) realloc( (char *) ptr, size );\n+\treturn realloc(ptr, size);\n }\n \n void yytreepathfree (void * ptr , yyscan_t yyscanner)\n@@ -2188,11 +2173,8 @@ EXPORT void FreeSearchTerms(SEARCH_TERM *terms)\n \n static char *strtrim(char *str)\n {\n- char *q = str;\n- while (* q) q++;\n- do { q--; } while (isspace(* q));\n- q++;\n- *q = '\\0';\n+ char *q;\n+ for (q=str+strlen(str)-1; (q > str) && isspace(*q); q--) *q='\\0';\n return str;\n }\n \n", "test_patch": "diff --git a/tditest/testing/test-treeshr.ans b/tditest/testing/test-treeshr.ans\nindex dd8bccbc1..60452431a 100644\n--- a/tditest/testing/test-treeshr.ans\n+++ b/tditest/testing/test-treeshr.ans\n@@ -18,6 +18,12 @@ getnci('?ember','fullpath')\n \"\\\\MAIN::TOP:MEMBER\"\n getnci('%ember','fullpath')\n [\"\\\\MAIN::TOP:MEMBER\"]\n+getnci('\\n','fullpath')\n+%TREE-W-NNF, Node Not Found\n+%TDI Error in GETNCI(\"\\n\", \"fullpath\")\n+%TDI Error in EVALUATE(GETNCI(\"\\n\", \"fullpath\"))\n+%TDI Error in EXECUTE(\"getnci('\\\\n','fullpath')\")\n+\n _tim=getnci(member,'time_inserted')\n 49776423271761650QU\n date_time(_tim)\ndiff --git a/tditest/testing/test-treeshr.tdi b/tditest/testing/test-treeshr.tdi\nindex 4712199cf..9d6510c2d 100644\n--- a/tditest/testing/test-treeshr.tdi\n+++ b/tditest/testing/test-treeshr.tdi\n@@ -9,6 +9,7 @@ getnci(member,'length')\n getnci(member,'on')\n getnci('?ember','fullpath')\n getnci('%ember','fullpath')\n+getnci('\\n','fullpath')\n _tim=getnci(member,'time_inserted')\n date_time(_tim)\n .subtree:a12:name\n", "FAIL_TO_PASS": ["MDSplus.tditest.test-treeshr"], "PASS_TO_PASS": ["MDSplus.tditest.test-tdishr"]} +{"instance_id": "clb-javac-200", "repo": "MDSplus/mdsplus", "base_commit": "f6c82e695f5b6964daeec2c4e0bc449a89be892a", "problem_statement": "UIDs are now 32 bits so can no longer fit uid and gid\nOn linux UIDs are now 32 bit integers. The 32bits in the NCI are no longer wide enough to hold both a UID and a GID.\r\n\r\nI propose dropping the GID and just storing the UID. This will involve changing dir/full to display the UID and username and not try to do the group.\r\n\r\nThe current code which sets the owner_id to:\r\n```\r\n((gid_t)getgid() << 16) | (uid_t)getuid()\r\n```\r\nworks fine if neither has any of their high 16 bits set. Otherwise it breaks.\r\n\r\nI will make this change unless someone objects. \r\n\r\nWe could say if the uid does not have any high bit sets then put the low 16 bits of the gid in the 16 bits of the owner id, but then I do not thing we will be able to distinguish the two cases when we read them back.\r\n\n", "image": {"image_id": "sha256:77c71ce09d01e830e0b98f3607636f0ffb03abc24ad51498190f6e7e0fb961dd", "pull_reference": "yutu0814/javac-case-200-mdsplus@sha256:77c71ce09d01e830e0b98f3607636f0ffb03abc24ad51498190f6e7e0fb961dd"}, "cohort": "java_upstream11", "patch": "diff --git a/tcl/tcl_directory.c b/tcl/tcl_directory.c\nindex deb9e7a0d13a2b20e6aba3acd93fb1374a3d251b..edf245b6824dc3db76985fcff3529ecfc37928a9 100644\n--- a/tcl/tcl_directory.c\n+++ b/tcl/tcl_directory.c\n@@ -62,23 +62,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n ************************************************************************/\n \n static int doFull(char **output, int nid, unsigned char nodeUsage, int version);\n-static char *mds_owner( /* Return: ptr to \"user\" string */\n- unsigned int owner /* owner id */\n-)\n+/// @param uid - user id\n+/// @return ptr to \"user\" string\n+static char *mds_owner(unsigned int uid)\n {\n static char ownerString[512];\n- int gid = owner >> 16;\n- int uid = owner & 0xFFFF;\n- char *groupname = 0;\n char *username = 0;\n-#ifdef HAVE_GETGRGID\n- struct group *g = getgrgid(gid);\n- if (g)\n- {\n- groupname = alloca(strlen(g->gr_name) + 3);\n- sprintf(groupname, \"(%s)\", g->gr_name);\n- }\n-#endif\n #ifdef HAVE_GETPWUID\n struct passwd *p = getpwuid(uid);\n if (p)\n@@ -87,11 +76,9 @@ static char *mds_owner( /* Return: ptr to \"user\" string\n sprintf(username, \"(%s)\", p->pw_name);\n }\n #endif\n- if (groupname == 0)\n- groupname = \"\";\n if (username == 0)\n username = \"\";\n- sprintf(ownerString, \"gid=%d%s,uid=%d%s\", gid, groupname, uid, username);\n+ sprintf(ownerString, \"uid=%d%s\", uid, username);\n return (ownerString);\n }\n \ndiff --git a/treeshr/TreeGetNci.c b/treeshr/TreeGetNci.c\nindex 02782e37b83d45f168ec07c9dfc30bfd518fddcb..bb83f3cd1467c08300eab36cf2c1da91d64da06f 100644\n--- a/treeshr/TreeGetNci.c\n+++ b/treeshr/TreeGetNci.c\n@@ -276,7 +276,12 @@ int TreeGetNci(int nid_in, struct nci_itm *nci_itm)\n break_on_no_node;\n read_nci;\n set_retlen(sizeof(nci.owner_identifier));\n- *(unsigned int *)itm->pointer = nci.owner_identifier;\n+ unsigned int owner = nci.owner_identifier;\n+ if (!(nci.flags2 & NciM_32BIT_UID_NCI))\n+ {\n+ owner &= 0xFFFF;\n+ }\n+ *(unsigned int *)itm->pointer = owner;\n break;\n case NciCLASS:\n break_on_no_node;\ndiff --git a/treeshr/TreePutRecord.c b/treeshr/TreePutRecord.c\nindex 44cb67fb26c1ef1ea0ab500cfee4ee5bcdf30d9b..20082fa11598fb31581c58b4033b1fddc417d433 100644\n--- a/treeshr/TreePutRecord.c\n+++ b/treeshr/TreePutRecord.c\n@@ -120,6 +120,7 @@ int _TreePutRecord(void *dbid, int nid, struct descriptor *descriptor_ptr,\n int nidx;\n unsigned int old_record_length = 0;\n static int saved_uic = 0;\n+ static int saved_uic32 = 0;\n int shot_open;\n EXTENDED_ATTRIBUTES attributes;\n int extended = 0;\n@@ -127,8 +128,15 @@ int _TreePutRecord(void *dbid, int nid, struct descriptor *descriptor_ptr,\n int compress_utility = utility_update == 2;\n #ifndef _WIN32\n if (!saved_uic)\n- saved_uic = (getgid() << 16) | getuid();\n-#endif\n+ {\n+ saved_uic = getuid();\n+ saved_uic32 = (saved_uic & 0xFFFF0000) != 0;\n+ if (!saved_uic32)\n+ {\n+ saved_uic = (getgid() << 16) | (saved_uic);\n+ }\n+ }\n+ #endif\n if (!(IS_OPEN(dblist)))\n return TreeNOT_OPEN;\n if (dblist->open_readonly)\n@@ -181,13 +189,14 @@ int _TreePutRecord(void *dbid, int nid, struct descriptor *descriptor_ptr,\n TREETHREADSTATIC_INIT;\n local_nci.flags = TREE_TEMPNCI.flags;\n bitassign(0, local_nci.flags, NciM_VERSIONS);\n+ bitassign((TREE_TEMPNCI.flags2 & NciM_32BIT_UID_NCI), local_nci.flags2, NciM_32BIT_UID_NCI);\n local_nci.owner_identifier = TREE_TEMPNCI.owner_identifier;\n local_nci.time_inserted = TREE_TEMPNCI.time_inserted;\n }\n else\n {\n- bitassign(dblist->setup_info, local_nci.flags,\n- NciM_SETUP_INFORMATION);\n+ bitassign(dblist->setup_info, local_nci.flags, NciM_SETUP_INFORMATION);\n+ bitassign(saved_uic32, local_nci.flags2, NciM_32BIT_UID_NCI);\n local_nci.owner_identifier = saved_uic;\n /* VMS time = unixtime * 10,000,000 + 0x7c95674beb4000q */\n local_nci.time_inserted = TreeTimeInserted();\ndiff --git a/treeshr/TreeSegments.c b/treeshr/TreeSegments.c\nindex 712a704a1394b992ed530d36a8202125e3a09145..022fc58be1996c20091385d56abe5eb2014ac979 100644\n--- a/treeshr/TreeSegments.c\n+++ b/treeshr/TreeSegments.c\n@@ -985,12 +985,24 @@ inline static int begin_finish(vars_t *vars)\n \n #ifndef _WIN32\n static int saved_uic = 0;\n-static void init_saved_uic() { saved_uic = (getgid() << 16) | getuid(); }\n+static int saved_uic32 = 0;\n+static void init_saved_uic() {\n+ if (!saved_uic)\n+ {\n+ saved_uic = getuid();\n+ saved_uic32 = (saved_uic & 0xFFFF0000) != 0;\n+ if (!saved_uic32)\n+ {\n+ saved_uic = (getgid() << 16) | (saved_uic);\n+ }\n+ }\n+}\n #endif\n inline static void begin_local_nci(vars_t *vars,\n const mdsdsc_a_t *initialValue)\n {\n- vars->local_nci.flags2 &= ~NciM_DATA_IN_ATT_BLOCK;\n+ // reset flag2 bits\n+ vars->local_nci.flags2 &= ~(NciM_DATA_IN_ATT_BLOCK | NciM_32BIT_UID_NCI);\n vars->local_nci.dtype = initialValue->dtype;\n vars->local_nci.class = CLASS_R;\n vars->local_nci.time_inserted = TreeTimeInserted();\n@@ -998,7 +1010,12 @@ inline static void begin_local_nci(vars_t *vars,\n RUN_FUNCTION_ONCE(init_saved_uic);\n #else\n const int saved_uic = 0;\n+ const int saved_uic32 = 0;\n #endif\n+ if (saved_uic32)\n+ {\n+ vars->local_nci.flags2 |= NciM_32BIT_UID_NCI;\n+ }\n vars->local_nci.owner_identifier = saved_uic;\n }\n \ndiff --git a/treeshr/treeshrp.h b/treeshr/treeshrp.h\nindex 49f80de128cf813c99307fbc7e639b420cf360ff..a6ac0682bacaeb030334873793df2d4831555a63 100644\n--- a/treeshr/treeshrp.h\n+++ b/treeshr/treeshrp.h\n@@ -40,6 +40,8 @@\n #define NciV_NON_VMS 3\n #define NciM_EXTENDED_NCI 0x10\n #define NciV_EXTENDED_NCI 4\n+#define NciM_32BIT_UID_NCI 0x20\n+#define NciV_32BIT_UID_NCI 5\n \n typedef struct nci\n {\n", "test_patch": "diff --git a/tditest/testing/test-treeshr.ans b/tditest/testing/test-treeshr.ans\nindex df6b7e82c0ebe73d5e2a608d23e0fdea9e3d4bfa..f443686d66c54261f4dde23488ceda667330c55c 100644\n--- a/tditest/testing/test-treeshr.ans\n+++ b/tditest/testing/test-treeshr.ans\n@@ -140,7 +140,7 @@ getnci(.subtree:a12,\"parent_relationship\")\n getnci(.subtree:a12,\"get_flags\")\n 128LU\n getnci(.subtree:a12,\"owner_id\")\n-4194368LU\n+64LU\n getnci(.subtree:a12,\"status\")\n 0LU\n getnci(.subtree:a12,\"brother\")\n", "FAIL_TO_PASS": ["MDSplus.tditest.test-treeshr-owner-id"], "PASS_TO_PASS": ["MDSplus.tditest.test-tdishr"]}