code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
<html>
<head>
<link rel="stylesheet" type="text/css" href="/css/c3.css">
</head>
<body>
<div id="chart"></div>
<script src="http://d3js.org/d3.v4.min.js" charset="utf-8"></script>
<script src="/js/c3.js"></script>
<script>
var columns = [];
for (var i = 0; i < 5; i++ ) {
columns[i] = ['datahogehogeohgeohoge' + i, 10 * i, 20 * i, 30 * i];
}
var chart = c3.generate({
data: {
columns: columns,
},
axis: {
x: {
type: 'category'
}
}
});
setTimeout(function () {
chart.legend.hide();
}, 1000);
setTimeout(function () {
chart = c3.generate({
data: {
columns: columns,
},
axis: {
x: {
type: 'category'
}
},
legend: {
position: 'right'
}
});
}, 2000);
setTimeout(function () {
chart.legend.hide();
}, 3000);
setTimeout(function () {
chart = c3.generate({
data: {
columns: columns,
},
axis: {
rotated: true
}
});
}, 4000);
setTimeout(function () {
chart.legend.hide();
}, 5000);
setTimeout(function () {
chart = c3.generate({
data: {
columns: columns,
},
legend: {
position: 'right'
},
axis: {
rotated: true
}
});
}, 6000);
setTimeout(function () {
chart.legend.hide();
}, 7000);
setTimeout(function () {
chart = c3.generate({
data: {
columns: columns,
},
legend: {
show: false
}
});
}, 8000);
setTimeout(function () {
chart.legend.show();
}, 9000);
setTimeout(function () {
chart = c3.generate({
data: {
columns: columns,
},
legend: {
show: false
},
axis: {
rotated: true
}
});
}, 10000);
setTimeout(function () {
chart.legend.show();
}, 11000);
setTimeout(function () {
chart = c3.generate({
data: {
columns: columns,
},
legend: {
position: 'right',
show: false
}
});
}, 12000);
setTimeout(function () {
chart.legend.show();
}, 13000);
</script>
</body>
</html>
|
tuandinhvu/v2CRM
|
public/plugins/c3-0.5.4/htdocs/samples/api_legend.html
|
HTML
|
mit
| 2,644
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import itertools
import json
import os
import unittest
import numpy as np
from monty.json import MontyDecoder
from pymatgen.core.periodic_table import Element
from pymatgen.core.lattice import Lattice
from pymatgen.core.structure import Structure
from pymatgen.analysis.defects.core import Interstitial, Substitution, Vacancy
from pymatgen.analysis.structure_matcher import (
ElementComparator,
FrameworkComparator,
OccupancyComparator,
OrderDisorderElementComparator,
PointDefectComparator,
StructureMatcher,
)
from pymatgen.core import PeriodicSite
from pymatgen.core.operations import SymmOp
from pymatgen.util.coord import find_in_coord_list_pbc
from pymatgen.util.testing import PymatgenTest
class StructureMatcherTest(PymatgenTest):
_multiprocess_shared_ = True
def setUp(self):
with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "TiO2_entries.json"), "r") as fp:
entries = json.load(fp, cls=MontyDecoder)
self.struct_list = [e.structure for e in entries]
self.oxi_structs = [
self.get_structure("Li2O"),
Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "POSCAR.Li2O")),
]
def test_ignore_species(self):
s1 = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "LiFePO4.cif"))
s2 = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "POSCAR"))
m = StructureMatcher(ignored_species=["Li"], primitive_cell=False, attempt_supercell=True)
self.assertTrue(m.fit(s1, s2))
self.assertTrue(m.fit_anonymous(s1, s2))
groups = m.group_structures([s1, s2])
self.assertEqual(len(groups), 1)
s2.make_supercell((2, 1, 1))
ss1 = m.get_s2_like_s1(s2, s1, include_ignored_species=True)
self.assertAlmostEqual(ss1.lattice.a, 20.820740000000001)
self.assertEqual(ss1.composition.reduced_formula, "LiFePO4")
self.assertEqual(
{k.symbol: v.symbol for k, v in m.get_best_electronegativity_anonymous_mapping(s1, s2).items()},
{"Fe": "Fe", "P": "P", "O": "O"},
)
def test_get_supercell_size(self):
l = Lattice.cubic(1)
l2 = Lattice.cubic(0.9)
s1 = Structure(l, ["Mg", "Cu", "Ag", "Cu", "Ag"], [[0] * 3] * 5)
s2 = Structure(l2, ["Cu", "Cu", "Ag"], [[0] * 3] * 3)
sm = StructureMatcher(supercell_size="volume")
self.assertEqual(sm._get_supercell_size(s1, s2), (1, True))
self.assertEqual(sm._get_supercell_size(s2, s1), (1, True))
sm = StructureMatcher(supercell_size="num_sites")
self.assertEqual(sm._get_supercell_size(s1, s2), (2, False))
self.assertEqual(sm._get_supercell_size(s2, s1), (2, True))
sm = StructureMatcher(supercell_size="Ag")
self.assertEqual(sm._get_supercell_size(s1, s2), (2, False))
self.assertEqual(sm._get_supercell_size(s2, s1), (2, True))
sm = StructureMatcher(supercell_size=["Ag", "Cu"])
self.assertEqual(sm._get_supercell_size(s1, s2), (1, True))
self.assertEqual(sm._get_supercell_size(s2, s1), (1, True))
sm = StructureMatcher(supercell_size="wfieoh")
self.assertRaises(ValueError, sm._get_supercell_size, s1, s2)
def test_cmp_fstruct(self):
sm = StructureMatcher()
s1 = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]])
s2 = np.array([[0.11, 0.22, 0.33]])
frac_tol = np.array([0.02, 0.03, 0.04])
mask = np.array([[False, False]])
mask2 = np.array([[True, False]])
self.assertRaises(ValueError, sm._cmp_fstruct, s2, s1, frac_tol, mask.T)
self.assertRaises(ValueError, sm._cmp_fstruct, s1, s2, frac_tol, mask.T)
self.assertTrue(sm._cmp_fstruct(s1, s2, frac_tol, mask))
self.assertFalse(sm._cmp_fstruct(s1, s2, frac_tol / 2, mask))
self.assertFalse(sm._cmp_fstruct(s1, s2, frac_tol, mask2))
def test_cart_dists(self):
sm = StructureMatcher()
l = Lattice.orthorhombic(1, 2, 3)
s1 = np.array([[0.13, 0.25, 0.37], [0.1, 0.2, 0.3]])
s2 = np.array([[0.11, 0.22, 0.33]])
s3 = np.array([[0.1, 0.2, 0.3], [0.11, 0.2, 0.3]])
s4 = np.array([[0.1, 0.2, 0.3], [0.1, 0.6, 0.7]])
mask = np.array([[False, False]])
mask2 = np.array([[False, True]])
mask3 = np.array([[False, False], [False, False]])
mask4 = np.array([[False, True], [False, True]])
n1 = (len(s1) / l.volume) ** (1 / 3)
n2 = (len(s2) / l.volume) ** (1 / 3)
self.assertRaises(ValueError, sm._cart_dists, s2, s1, l, mask.T, n2)
self.assertRaises(ValueError, sm._cart_dists, s1, s2, l, mask.T, n1)
d, ft, s = sm._cart_dists(s1, s2, l, mask, n1)
self.assertTrue(np.allclose(d, [0]))
self.assertTrue(np.allclose(ft, [-0.01, -0.02, -0.03]))
self.assertTrue(np.allclose(s, [1]))
# check that masking best value works
d, ft, s = sm._cart_dists(s1, s2, l, mask2, n1)
self.assertTrue(np.allclose(d, [0]))
self.assertTrue(np.allclose(ft, [0.02, 0.03, 0.04]))
self.assertTrue(np.allclose(s, [0]))
# check that averaging of translation is done properly
d, ft, s = sm._cart_dists(s1, s3, l, mask3, n1)
self.assertTrue(np.allclose(d, [0.08093341] * 2))
self.assertTrue(np.allclose(ft, [0.01, 0.025, 0.035]))
self.assertTrue(np.allclose(s, [1, 0]))
# check distances are large when mask allows no 'real' mapping
d, ft, s = sm._cart_dists(s1, s4, l, mask4, n1)
self.assertTrue(np.min(d) > 1e8)
self.assertTrue(np.min(ft) > 1e8)
def test_get_mask(self):
sm = StructureMatcher(comparator=ElementComparator())
l = Lattice.cubic(1)
s1 = Structure(l, ["Mg", "Cu", "Ag", "Cu"], [[0] * 3] * 4)
s2 = Structure(l, ["Cu", "Cu", "Ag"], [[0] * 3] * 3)
result = [
[True, False, True, False],
[True, False, True, False],
[True, True, False, True],
]
m, inds, i = sm._get_mask(s1, s2, 1, True)
self.assertTrue(np.all(m == result))
self.assertTrue(i == 2)
self.assertEqual(inds, [2])
# test supercell with match
result = [
[1, 1, 0, 0, 1, 1, 0, 0],
[1, 1, 0, 0, 1, 1, 0, 0],
[1, 1, 1, 1, 0, 0, 1, 1],
]
m, inds, i = sm._get_mask(s1, s2, 2, True)
self.assertTrue(np.all(m == result))
self.assertTrue(i == 2)
self.assertTrue(np.allclose(inds, np.array([4])))
# test supercell without match
result = [
[1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 1, 1],
[1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 1],
]
m, inds, i = sm._get_mask(s2, s1, 2, True)
self.assertTrue(np.all(m == result))
self.assertTrue(i == 0)
self.assertTrue(np.allclose(inds, np.array([])))
# test s2_supercell
result = [
[1, 1, 1],
[1, 1, 1],
[0, 0, 1],
[0, 0, 1],
[1, 1, 0],
[1, 1, 0],
[0, 0, 1],
[0, 0, 1],
]
m, inds, i = sm._get_mask(s2, s1, 2, False)
self.assertTrue(np.all(m == result))
self.assertTrue(i == 0)
self.assertTrue(np.allclose(inds, np.array([])))
# test for multiple translation indices
s1 = Structure(l, ["Cu", "Ag", "Cu", "Ag", "Ag"], [[0] * 3] * 5)
s2 = Structure(l, ["Ag", "Cu", "Ag"], [[0] * 3] * 3)
result = [[1, 0, 1, 0, 0], [0, 1, 0, 1, 1], [1, 0, 1, 0, 0]]
m, inds, i = sm._get_mask(s1, s2, 1, True)
self.assertTrue(np.all(m == result))
self.assertTrue(i == 1)
self.assertTrue(np.allclose(inds, [0, 2]))
def test_get_supercells(self):
sm = StructureMatcher(comparator=ElementComparator())
l = Lattice.cubic(1)
l2 = Lattice.cubic(0.5)
s1 = Structure(l, ["Mg", "Cu", "Ag", "Cu"], [[0] * 3] * 4)
s2 = Structure(l2, ["Cu", "Cu", "Ag"], [[0] * 3] * 3)
scs = list(sm._get_supercells(s1, s2, 8, False))
for x in scs:
self.assertAlmostEqual(abs(np.linalg.det(x[3])), 8)
self.assertEqual(len(x[0]), 4)
self.assertEqual(len(x[1]), 24)
self.assertEqual(len(scs), 48)
scs = list(sm._get_supercells(s2, s1, 8, True))
for x in scs:
self.assertAlmostEqual(abs(np.linalg.det(x[3])), 8)
self.assertEqual(len(x[0]), 24)
self.assertEqual(len(x[1]), 4)
self.assertEqual(len(scs), 48)
def test_fit(self):
"""
Take two known matched structures
1) Ensure match
2) Ensure match after translation and rotations
3) Ensure no-match after large site translation
4) Ensure match after site shuffling
"""
sm = StructureMatcher()
self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1]))
# Test rotational/translational invariance
op = SymmOp.from_axis_angle_and_translation([0, 0, 1], 30, False, np.array([0.4, 0.7, 0.9]))
self.struct_list[1].apply_operation(op)
self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1]))
# Test failure under large atomic translation
self.struct_list[1].translate_sites([0], [0.4, 0.4, 0.2], frac_coords=True)
self.assertFalse(sm.fit(self.struct_list[0], self.struct_list[1]))
self.struct_list[1].translate_sites([0], [-0.4, -0.4, -0.2], frac_coords=True)
# random.shuffle(editor._sites)
self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1]))
# Test FrameworkComporator
sm2 = StructureMatcher(comparator=FrameworkComparator())
lfp = self.get_structure("LiFePO4")
nfp = self.get_structure("NaFePO4")
self.assertTrue(sm2.fit(lfp, nfp))
self.assertFalse(sm.fit(lfp, nfp))
# Test anonymous fit.
self.assertEqual(sm.fit_anonymous(lfp, nfp), True)
self.assertAlmostEqual(sm.get_rms_anonymous(lfp, nfp)[0], 0.060895871160262717)
# Test partial occupancies.
s1 = Structure(
Lattice.cubic(3),
[{"Fe": 0.5}, {"Fe": 0.5}, {"Fe": 0.5}, {"Fe": 0.5}],
[[0, 0, 0], [0.25, 0.25, 0.25], [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]],
)
s2 = Structure(
Lattice.cubic(3),
[{"Fe": 0.25}, {"Fe": 0.5}, {"Fe": 0.5}, {"Fe": 0.75}],
[[0, 0, 0], [0.25, 0.25, 0.25], [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]],
)
self.assertFalse(sm.fit(s1, s2))
self.assertFalse(sm.fit(s2, s1))
s2 = Structure(
Lattice.cubic(3),
[{"Mn": 0.5}, {"Mn": 0.5}, {"Mn": 0.5}, {"Mn": 0.5}],
[[0, 0, 0], [0.25, 0.25, 0.25], [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]],
)
self.assertEqual(sm.fit_anonymous(s1, s2), True)
self.assertAlmostEqual(sm.get_rms_anonymous(s1, s2)[0], 0)
# test symmetric
sm_coarse = sm = StructureMatcher(
comparator=ElementComparator(),
ltol=0.6,
stol=0.6,
angle_tol=6,
)
s1 = Structure.from_file(PymatgenTest.TEST_FILES_DIR / "fit_symm_s1.vasp")
s2 = Structure.from_file(PymatgenTest.TEST_FILES_DIR / "fit_symm_s2.vasp")
self.assertEqual(sm_coarse.fit(s1, s2), True)
self.assertEqual(sm_coarse.fit(s2, s1), False)
self.assertEqual(sm_coarse.fit(s1, s2, symmetric=True), False)
self.assertEqual(sm_coarse.fit(s2, s1, symmetric=True), False)
def test_oxi(self):
"""Test oxidation state removal matching"""
sm = StructureMatcher()
self.assertFalse(sm.fit(self.oxi_structs[0], self.oxi_structs[1]))
sm = StructureMatcher(comparator=ElementComparator())
self.assertTrue(sm.fit(self.oxi_structs[0], self.oxi_structs[1]))
def test_primitive(self):
"""Test primitive cell reduction"""
sm = StructureMatcher(primitive_cell=True)
self.struct_list[1].make_supercell([[2, 0, 0], [0, 3, 0], [0, 0, 1]])
self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1]))
def test_class(self):
# Tests entire class as single working unit
sm = StructureMatcher()
# Test group_structures and find_indices
out = sm.group_structures(self.struct_list)
self.assertEqual(list(map(len, out)), [4, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1])
self.assertEqual(sum(map(len, out)), len(self.struct_list))
for s in self.struct_list[::2]:
s.replace_species({"Ti": "Zr", "O": "Ti"})
out = sm.group_structures(self.struct_list, anonymous=True)
self.assertEqual(list(map(len, out)), [4, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1])
def test_mix(self):
structures = [
self.get_structure("Li2O"),
self.get_structure("Li2O2"),
self.get_structure("LiFePO4"),
]
for fname in ["POSCAR.Li2O", "POSCAR.LiFePO4"]:
structures.append(Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, fname)))
sm = StructureMatcher(comparator=ElementComparator())
groups = sm.group_structures(structures)
for g in groups:
formula = g[0].composition.reduced_formula
if formula in ["Li2O", "LiFePO4"]:
self.assertEqual(len(g), 2)
else:
self.assertEqual(len(g), 1)
def test_left_handed_lattice(self):
"""Ensure Left handed lattices are accepted"""
sm = StructureMatcher()
s = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "Li3GaPCO7.json"))
self.assertTrue(sm.fit(s, s))
def test_as_dict_and_from_dict(self):
sm = StructureMatcher(
ltol=0.1,
stol=0.2,
angle_tol=2,
primitive_cell=False,
scale=False,
comparator=FrameworkComparator(),
)
d = sm.as_dict()
sm2 = StructureMatcher.from_dict(d)
self.assertEqual(sm2.as_dict(), d)
def test_no_scaling(self):
sm = StructureMatcher(ltol=0.1, stol=0.1, angle_tol=2, scale=False, comparator=ElementComparator())
self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1]))
self.assertTrue(sm.get_rms_dist(self.struct_list[0], self.struct_list[1])[0] < 0.0008)
def test_supercell_fit(self):
sm = StructureMatcher(attempt_supercell=False)
s1 = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "Al3F9.json"))
s2 = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "Al3F9_distorted.json"))
self.assertFalse(sm.fit(s1, s2))
sm = StructureMatcher(attempt_supercell=True)
self.assertTrue(sm.fit(s1, s2))
self.assertTrue(sm.fit(s2, s1))
def test_get_lattices(self):
sm = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=True,
scale=True,
attempt_supercell=False,
)
l1 = Lattice.from_parameters(1, 2.1, 1.9, 90, 89, 91)
l2 = Lattice.from_parameters(1.1, 2, 2, 89, 91, 90)
s1 = Structure(l1, [], [])
s2 = Structure(l2, [], [])
lattices = list(sm._get_lattices(s=s1, target_lattice=s2.lattice))
self.assertEqual(len(lattices), 16)
l3 = Lattice.from_parameters(1.1, 2, 20, 89, 91, 90)
s3 = Structure(l3, [], [])
lattices = list(sm._get_lattices(s=s1, target_lattice=s3.lattice))
self.assertEqual(len(lattices), 0)
def test_find_match1(self):
sm = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=True,
scale=True,
attempt_supercell=False,
)
l = Lattice.orthorhombic(1, 2, 3)
s1 = Structure(l, ["Si", "Si", "Ag"], [[0, 0, 0.1], [0, 0, 0.2], [0.7, 0.4, 0.5]])
s2 = Structure(l, ["Si", "Si", "Ag"], [[0, 0.1, 0], [0, 0.1, -0.95], [0.7, 0.5, 0.375]])
s1, s2, fu, s1_supercell = sm._preprocess(s1, s2, False)
match = sm._strict_match(s1, s2, fu, s1_supercell=True, use_rms=True, break_on_match=False)
scale_matrix = match[2]
s2.make_supercell(scale_matrix)
fc = s2.frac_coords + match[3]
fc -= np.round(fc)
self.assertAlmostEqual(np.sum(fc), 0.9)
self.assertAlmostEqual(np.sum(fc[:, :2]), 0.1)
cart_dist = np.sum(match[1] * (l.volume / 3) ** (1 / 3))
self.assertAlmostEqual(cart_dist, 0.15)
def test_find_match2(self):
sm = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=True,
scale=True,
attempt_supercell=False,
)
l = Lattice.orthorhombic(1, 2, 3)
s1 = Structure(l, ["Si", "Si"], [[0, 0, 0.1], [0, 0, 0.2]])
s2 = Structure(l, ["Si", "Si"], [[0, 0.1, 0], [0, 0.1, -0.95]])
s1, s2, fu, s1_supercell = sm._preprocess(s1, s2, False)
match = sm._strict_match(s1, s2, fu, s1_supercell=False, use_rms=True, break_on_match=False)
scale_matrix = match[2]
s2.make_supercell(scale_matrix)
s2.translate_sites(range(len(s2)), match[3])
self.assertAlmostEqual(np.sum(s2.frac_coords) % 1, 0.3)
self.assertAlmostEqual(np.sum(s2.frac_coords[:, :2]) % 1, 0)
def test_supercell_subsets(self):
sm = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=False,
scale=True,
attempt_supercell=True,
allow_subset=True,
supercell_size="volume",
)
sm_no_s = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=False,
scale=True,
attempt_supercell=True,
allow_subset=False,
supercell_size="volume",
)
l = Lattice.orthorhombic(1, 2, 3)
s1 = Structure(l, ["Ag", "Si", "Si"], [[0.7, 0.4, 0.5], [0, 0, 0.1], [0, 0, 0.2]])
s1.make_supercell([2, 1, 1])
s2 = Structure(l, ["Si", "Si", "Ag"], [[0, 0.1, -0.95], [0, 0.1, 0], [-0.7, 0.5, 0.375]])
shuffle = [0, 2, 1, 3, 4, 5]
s1 = Structure.from_sites([s1[i] for i in shuffle])
# test when s1 is exact supercell of s2
result = sm.get_s2_like_s1(s1, s2)
for a, b in zip(s1, result):
self.assertTrue(a.distance(b) < 0.08)
self.assertEqual(a.species, b.species)
self.assertTrue(sm.fit(s1, s2))
self.assertTrue(sm.fit(s2, s1))
self.assertTrue(sm_no_s.fit(s1, s2))
self.assertTrue(sm_no_s.fit(s2, s1))
rms = (0.048604032430991401, 0.059527539448807391)
self.assertTrue(np.allclose(sm.get_rms_dist(s1, s2), rms))
self.assertTrue(np.allclose(sm.get_rms_dist(s2, s1), rms))
# test when the supercell is a subset of s2
subset_supercell = s1.copy()
del subset_supercell[0]
result = sm.get_s2_like_s1(subset_supercell, s2)
self.assertEqual(len(result), 6)
for a, b in zip(subset_supercell, result):
self.assertTrue(a.distance(b) < 0.08)
self.assertEqual(a.species, b.species)
self.assertTrue(sm.fit(subset_supercell, s2))
self.assertTrue(sm.fit(s2, subset_supercell))
self.assertFalse(sm_no_s.fit(subset_supercell, s2))
self.assertFalse(sm_no_s.fit(s2, subset_supercell))
rms = (0.053243049896333279, 0.059527539448807336)
self.assertTrue(np.allclose(sm.get_rms_dist(subset_supercell, s2), rms))
self.assertTrue(np.allclose(sm.get_rms_dist(s2, subset_supercell), rms))
# test when s2 (once made a supercell) is a subset of s1
s2_missing_site = s2.copy()
del s2_missing_site[1]
result = sm.get_s2_like_s1(s1, s2_missing_site)
for a, b in zip((s1[i] for i in (0, 2, 4, 5)), result):
self.assertTrue(a.distance(b) < 0.08)
self.assertEqual(a.species, b.species)
self.assertTrue(sm.fit(s1, s2_missing_site))
self.assertTrue(sm.fit(s2_missing_site, s1))
self.assertFalse(sm_no_s.fit(s1, s2_missing_site))
self.assertFalse(sm_no_s.fit(s2_missing_site, s1))
rms = (0.029763769724403633, 0.029763769724403987)
self.assertTrue(np.allclose(sm.get_rms_dist(s1, s2_missing_site), rms))
self.assertTrue(np.allclose(sm.get_rms_dist(s2_missing_site, s1), rms))
def test_get_s2_large_s2(self):
sm = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=False,
scale=False,
attempt_supercell=True,
allow_subset=False,
supercell_size="volume",
)
l = Lattice.orthorhombic(1, 2, 3)
s1 = Structure(l, ["Ag", "Si", "Si"], [[0.7, 0.4, 0.5], [0, 0, 0.1], [0, 0, 0.2]])
l2 = Lattice.orthorhombic(1.01, 2.01, 3.01)
s2 = Structure(l2, ["Si", "Si", "Ag"], [[0, 0.1, -0.95], [0, 0.1, 0], [-0.7, 0.5, 0.375]])
s2.make_supercell([[0, -1, 0], [1, 0, 0], [0, 0, 1]])
result = sm.get_s2_like_s1(s1, s2)
for x, y in zip(s1, result):
self.assertLess(x.distance(y), 0.08)
def test_get_mapping(self):
sm = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=False,
scale=True,
attempt_supercell=False,
allow_subset=True,
)
l = Lattice.orthorhombic(1, 2, 3)
s1 = Structure(l, ["Ag", "Si", "Si"], [[0.7, 0.4, 0.5], [0, 0, 0.1], [0, 0, 0.2]])
s1.make_supercell([2, 1, 1])
s2 = Structure(l, ["Si", "Si", "Ag"], [[0, 0.1, -0.95], [0, 0.1, 0], [-0.7, 0.5, 0.375]])
shuffle = [2, 0, 1, 3, 5, 4]
s1 = Structure.from_sites([s1[i] for i in shuffle])
# test the mapping
s2.make_supercell([2, 1, 1])
# equal sizes
for i, x in enumerate(sm.get_mapping(s1, s2)):
self.assertEqual(s1[x].species, s2[i].species)
del s1[0]
# s1 is subset of s2
for i, x in enumerate(sm.get_mapping(s2, s1)):
self.assertEqual(s1[i].species, s2[x].species)
# s2 is smaller than s1
del s2[0]
del s2[1]
self.assertRaises(ValueError, sm.get_mapping, s2, s1)
def test_get_supercell_matrix(self):
sm = StructureMatcher(
ltol=0.1,
stol=0.3,
angle_tol=2,
primitive_cell=False,
scale=True,
attempt_supercell=True,
)
l = Lattice.orthorhombic(1, 2, 3)
s1 = Structure(l, ["Si", "Si", "Ag"], [[0, 0, 0.1], [0, 0, 0.2], [0.7, 0.4, 0.5]])
s1.make_supercell([2, 1, 1])
s2 = Structure(l, ["Si", "Si", "Ag"], [[0, 0.1, 0], [0, 0.1, -0.95], [-0.7, 0.5, 0.375]])
result = sm.get_supercell_matrix(s1, s2)
self.assertTrue((result == [[-2, 0, 0], [0, 1, 0], [0, 0, 1]]).all())
s1 = Structure(l, ["Si", "Si", "Ag"], [[0, 0, 0.1], [0, 0, 0.2], [0.7, 0.4, 0.5]])
s1.make_supercell([[1, -1, 0], [0, 0, -1], [0, 1, 0]])
s2 = Structure(l, ["Si", "Si", "Ag"], [[0, 0.1, 0], [0, 0.1, -0.95], [-0.7, 0.5, 0.375]])
result = sm.get_supercell_matrix(s1, s2)
self.assertTrue((result == [[-1, -1, 0], [0, 0, -1], [0, 1, 0]]).all())
# test when the supercell is a subset
sm = StructureMatcher(
ltol=0.1,
stol=0.3,
angle_tol=2,
primitive_cell=False,
scale=True,
attempt_supercell=True,
allow_subset=True,
)
del s1[0]
result = sm.get_supercell_matrix(s1, s2)
self.assertTrue((result == [[-1, -1, 0], [0, 0, -1], [0, 1, 0]]).all())
def test_subset(self):
sm = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=False,
scale=True,
attempt_supercell=False,
allow_subset=True,
)
l = Lattice.orthorhombic(10, 20, 30)
s1 = Structure(l, ["Si", "Si", "Ag"], [[0, 0, 0.1], [0, 0, 0.2], [0.7, 0.4, 0.5]])
s2 = Structure(l, ["Si", "Ag"], [[0, 0.1, 0], [-0.7, 0.5, 0.4]])
result = sm.get_s2_like_s1(s1, s2)
self.assertEqual(len(find_in_coord_list_pbc(result.frac_coords, [0, 0, 0.1])), 1)
self.assertEqual(len(find_in_coord_list_pbc(result.frac_coords, [0.7, 0.4, 0.5])), 1)
# test with fewer species in s2
s1 = Structure(l, ["Si", "Ag", "Si"], [[0, 0, 0.1], [0, 0, 0.2], [0.7, 0.4, 0.5]])
s2 = Structure(l, ["Si", "Si"], [[0, 0.1, 0], [-0.7, 0.5, 0.4]])
result = sm.get_s2_like_s1(s1, s2)
mindists = np.min(s1.lattice.get_all_distances(s1.frac_coords, result.frac_coords), axis=0)
self.assertLess(np.max(mindists), 1e-6)
self.assertEqual(len(find_in_coord_list_pbc(result.frac_coords, [0, 0, 0.1])), 1)
self.assertEqual(len(find_in_coord_list_pbc(result.frac_coords, [0.7, 0.4, 0.5])), 1)
# test with not enough sites in s1
# test with fewer species in s2
s1 = Structure(l, ["Si", "Ag", "Cl"], [[0, 0, 0.1], [0, 0, 0.2], [0.7, 0.4, 0.5]])
s2 = Structure(l, ["Si", "Si"], [[0, 0.1, 0], [-0.7, 0.5, 0.4]])
self.assertEqual(sm.get_s2_like_s1(s1, s2), None)
def test_out_of_cell_s2_like_s1(self):
l = Lattice.cubic(5)
s1 = Structure(l, ["Si", "Ag", "Si"], [[0, 0, -0.02], [0, 0, 0.001], [0.7, 0.4, 0.5]])
s2 = Structure(l, ["Si", "Ag", "Si"], [[0, 0, 0.98], [0, 0, 0.99], [0.7, 0.4, 0.5]])
new_s2 = StructureMatcher(primitive_cell=False).get_s2_like_s1(s1, s2)
dists = np.sum((s1.cart_coords - new_s2.cart_coords) ** 2, axis=-1) ** 0.5
self.assertLess(np.max(dists), 0.1)
def test_disordered_primitive_to_ordered_supercell(self):
sm_atoms = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=False,
scale=True,
attempt_supercell=True,
allow_subset=True,
supercell_size="num_atoms",
comparator=OrderDisorderElementComparator(),
)
sm_sites = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=False,
scale=True,
attempt_supercell=True,
allow_subset=True,
supercell_size="num_sites",
comparator=OrderDisorderElementComparator(),
)
lp = Lattice.orthorhombic(10, 20, 30)
pcoords = [[0, 0, 0], [0.5, 0.5, 0.5]]
ls = Lattice.orthorhombic(20, 20, 30)
scoords = [[0, 0, 0], [0.75, 0.5, 0.5]]
prim = Structure(lp, [{"Na": 0.5}, {"Cl": 0.5}], pcoords)
supercell = Structure(ls, ["Na", "Cl"], scoords)
supercell.make_supercell([[-1, 1, 0], [0, 1, 1], [1, 0, 0]])
self.assertFalse(sm_sites.fit(prim, supercell))
self.assertTrue(sm_atoms.fit(prim, supercell))
self.assertRaises(ValueError, sm_atoms.get_s2_like_s1, prim, supercell)
self.assertEqual(len(sm_atoms.get_s2_like_s1(supercell, prim)), 4)
def test_ordered_primitive_to_disordered_supercell(self):
sm_atoms = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=False,
scale=True,
attempt_supercell=True,
allow_subset=True,
supercell_size="num_atoms",
comparator=OrderDisorderElementComparator(),
)
sm_sites = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=False,
scale=True,
attempt_supercell=True,
allow_subset=True,
supercell_size="num_sites",
comparator=OrderDisorderElementComparator(),
)
lp = Lattice.orthorhombic(10, 20, 30)
pcoords = [[0, 0, 0], [0.5, 0.5, 0.5]]
ls = Lattice.orthorhombic(20, 20, 30)
scoords = [[0, 0, 0], [0.5, 0, 0], [0.25, 0.5, 0.5], [0.75, 0.5, 0.5]]
s1 = Structure(lp, ["Na", "Cl"], pcoords)
s2 = Structure(ls, [{"Na": 0.5}, {"Na": 0.5}, {"Cl": 0.5}, {"Cl": 0.5}], scoords)
self.assertTrue(sm_sites.fit(s1, s2))
self.assertFalse(sm_atoms.fit(s1, s2))
def test_disordered_to_disordered(self):
sm_atoms = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=False,
scale=True,
attempt_supercell=True,
allow_subset=False,
comparator=OrderDisorderElementComparator(),
)
lp = Lattice.orthorhombic(10, 20, 30)
coords = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]]
s1 = Structure(lp, [{"Na": 0.5, "Cl": 0.5}, {"Na": 0.5, "Cl": 0.5}], coords)
s2 = Structure(lp, [{"Na": 0.5, "Cl": 0.5}, {"Na": 0.5, "Br": 0.5}], coords)
self.assertFalse(sm_atoms.fit(s1, s2))
def test_occupancy_comparator(self):
lp = Lattice.orthorhombic(10, 20, 30)
pcoords = [[0, 0, 0], [0.5, 0.5, 0.5]]
s1 = Structure(lp, [{"Na": 0.6, "K": 0.4}, "Cl"], pcoords)
s2 = Structure(lp, [{"Xa": 0.4, "Xb": 0.6}, "Cl"], pcoords)
s3 = Structure(lp, [{"Xa": 0.5, "Xb": 0.5}, "Cl"], pcoords)
sm_sites = StructureMatcher(
ltol=0.2,
stol=0.3,
angle_tol=5,
primitive_cell=False,
scale=True,
attempt_supercell=True,
allow_subset=True,
supercell_size="num_sites",
comparator=OccupancyComparator(),
)
self.assertTrue(sm_sites.fit(s1, s2))
self.assertFalse(sm_sites.fit(s1, s3))
def test_electronegativity(self):
sm = StructureMatcher(ltol=0.2, stol=0.3, angle_tol=5)
s1 = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "Na2Fe2PAsO4S4.json"))
s2 = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "Na2Fe2PNO4Se4.json"))
self.assertEqual(
sm.get_best_electronegativity_anonymous_mapping(s1, s2),
{
Element("S"): Element("Se"),
Element("As"): Element("N"),
Element("Fe"): Element("Fe"),
Element("Na"): Element("Na"),
Element("P"): Element("P"),
Element("O"): Element("O"),
},
)
self.assertEqual(len(sm.get_all_anonymous_mappings(s1, s2)), 2)
# test include_dist
dists = {Element("N"): 0, Element("P"): 0.0010725064}
for mapping, d in sm.get_all_anonymous_mappings(s1, s2, include_dist=True):
self.assertAlmostEqual(dists[mapping[Element("As")]], d)
def test_rms_vs_minimax(self):
# This tests that structures with adjusted RMS less than stol, but minimax
# greater than stol are treated properly
# stol=0.3 gives exactly an ftol of 0.1 on the c axis
sm = StructureMatcher(ltol=0.2, stol=0.301, angle_tol=1, primitive_cell=False)
l = Lattice.orthorhombic(1, 2, 12)
sp = ["Si", "Si", "Al"]
s1 = Structure(l, sp, [[0.5, 0, 0], [0, 0, 0], [0, 0, 0.5]])
s2 = Structure(l, sp, [[0.5, 0, 0], [0, 0, 0], [0, 0, 0.6]])
self.assertArrayAlmostEqual(sm.get_rms_dist(s1, s2), (0.32 ** 0.5 / 2, 0.4))
self.assertEqual(sm.fit(s1, s2), False)
self.assertEqual(sm.fit_anonymous(s1, s2), False)
self.assertEqual(sm.get_mapping(s1, s2), None)
class PointDefectComparatorTest(PymatgenTest):
def test_defect_matching(self):
# SETUP DEFECTS FOR TESTING
# symmorphic defect test set
s_struc = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "CsSnI3.cif")) # tetragonal CsSnI3
identical_Cs_vacs = [Vacancy(s_struc, s_struc[0]), Vacancy(s_struc, s_struc[1])]
identical_I_vacs_sublattice1 = [
Vacancy(s_struc, s_struc[4]),
Vacancy(s_struc, s_struc[5]),
Vacancy(s_struc, s_struc[8]),
Vacancy(s_struc, s_struc[9]),
] # in plane halides
identical_I_vacs_sublattice2 = [
Vacancy(s_struc, s_struc[6]),
Vacancy(s_struc, s_struc[7]),
] # out of plane halides
pdc = PointDefectComparator()
# NOW TEST DEFECTS
# test vacancy matching
self.assertTrue(pdc.are_equal(identical_Cs_vacs[0], identical_Cs_vacs[0])) # trivial vacancy test
self.assertTrue(pdc.are_equal(identical_Cs_vacs[0], identical_Cs_vacs[1])) # vacancies on same sublattice
for i, j in itertools.combinations(range(4), 2):
self.assertTrue(pdc.are_equal(identical_I_vacs_sublattice1[i], identical_I_vacs_sublattice1[j]))
self.assertTrue(pdc.are_equal(identical_I_vacs_sublattice2[0], identical_I_vacs_sublattice2[1]))
self.assertFalse(
pdc.are_equal(
identical_Cs_vacs[0],
# both vacancies, but different specie types
identical_I_vacs_sublattice1[0],
)
)
self.assertFalse(
pdc.are_equal(
identical_I_vacs_sublattice1[0],
# same specie type, different sublattice
identical_I_vacs_sublattice2[0],
)
)
# test substitutional matching
sub_Cs_on_I_sublattice1_set1 = PeriodicSite(
"Cs", identical_I_vacs_sublattice1[0].site.frac_coords, s_struc.lattice
)
sub_Cs_on_I_sublattice1_set2 = PeriodicSite(
"Cs", identical_I_vacs_sublattice1[1].site.frac_coords, s_struc.lattice
)
sub_Cs_on_I_sublattice2 = PeriodicSite("Cs", identical_I_vacs_sublattice2[0].site.frac_coords, s_struc.lattice)
sub_Rb_on_I_sublattice2 = PeriodicSite("Rb", identical_I_vacs_sublattice2[0].site.frac_coords, s_struc.lattice)
self.assertTrue(
pdc.are_equal( # trivial substitution test
Substitution(s_struc, sub_Cs_on_I_sublattice1_set1),
Substitution(s_struc, sub_Cs_on_I_sublattice1_set1),
)
)
self.assertTrue(
pdc.are_equal( # same sublattice, different coords
Substitution(s_struc, sub_Cs_on_I_sublattice1_set1),
Substitution(s_struc, sub_Cs_on_I_sublattice1_set2),
)
)
self.assertFalse(
pdc.are_equal( # different subs (wrong specie)
Substitution(s_struc, sub_Cs_on_I_sublattice2),
Substitution(s_struc, sub_Rb_on_I_sublattice2),
)
)
self.assertFalse(
pdc.are_equal( # different subs (wrong sublattice)
Substitution(s_struc, sub_Cs_on_I_sublattice1_set1),
Substitution(s_struc, sub_Cs_on_I_sublattice2),
)
)
# test symmorphic interstitial matching
# (using set generated from Voronoi generator, with same sublattice given by saturatated_
# interstitial_structure function)
inter_H_sublattice1_set1 = PeriodicSite("H", [0.0, 0.75, 0.25], s_struc.lattice)
inter_H_sublattice1_set2 = PeriodicSite("H", [0.0, 0.75, 0.75], s_struc.lattice)
inter_H_sublattice2 = PeriodicSite("H", [0.57796112, 0.06923687, 0.56923687], s_struc.lattice)
inter_H_sublattice3 = PeriodicSite("H", [0.25, 0.25, 0.54018268], s_struc.lattice)
inter_He_sublattice3 = PeriodicSite("He", [0.25, 0.25, 0.54018268], s_struc.lattice)
self.assertTrue(
pdc.are_equal( # trivial interstitial test
Interstitial(s_struc, inter_H_sublattice1_set1),
Interstitial(s_struc, inter_H_sublattice1_set1),
)
)
self.assertTrue(
pdc.are_equal( # same sublattice, different coords
Interstitial(s_struc, inter_H_sublattice1_set1),
Interstitial(s_struc, inter_H_sublattice1_set2),
)
)
self.assertFalse(
pdc.are_equal( # different interstitials (wrong sublattice)
Interstitial(s_struc, inter_H_sublattice1_set1),
Interstitial(s_struc, inter_H_sublattice2),
)
)
self.assertFalse(
pdc.are_equal( # different interstitials (wrong sublattice)
Interstitial(s_struc, inter_H_sublattice1_set1),
Interstitial(s_struc, inter_H_sublattice3),
)
)
self.assertFalse(
pdc.are_equal( # different interstitials (wrong specie)
Interstitial(s_struc, inter_H_sublattice3),
Interstitial(s_struc, inter_He_sublattice3),
)
)
# test non-symmorphic interstitial matching
# (using set generated from Voronoi generator, with same sublattice given by
# saturatated_interstitial_structure function)
ns_struc = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "CuCl.cif"))
ns_inter_H_sublattice1_set1 = PeriodicSite("H", [0.06924513, 0.06308959, 0.86766528], ns_struc.lattice)
ns_inter_H_sublattice1_set2 = PeriodicSite("H", [0.43691041, 0.36766528, 0.06924513], ns_struc.lattice)
ns_inter_H_sublattice2 = PeriodicSite("H", [0.06022109, 0.60196031, 0.1621814], ns_struc.lattice)
ns_inter_He_sublattice2 = PeriodicSite("He", [0.06022109, 0.60196031, 0.1621814], ns_struc.lattice)
self.assertTrue(
pdc.are_equal( # trivial interstitial test
Interstitial(ns_struc, ns_inter_H_sublattice1_set1),
Interstitial(ns_struc, ns_inter_H_sublattice1_set1),
)
)
self.assertTrue(
pdc.are_equal( # same sublattice, different coords
Interstitial(ns_struc, ns_inter_H_sublattice1_set1),
Interstitial(ns_struc, ns_inter_H_sublattice1_set2),
)
)
self.assertFalse(
pdc.are_equal(
Interstitial(ns_struc, ns_inter_H_sublattice1_set1),
# different interstitials (wrong sublattice)
Interstitial(ns_struc, ns_inter_H_sublattice2),
)
)
self.assertFalse(
pdc.are_equal( # different interstitials (wrong specie)
Interstitial(ns_struc, ns_inter_H_sublattice2),
Interstitial(ns_struc, ns_inter_He_sublattice2),
)
)
# test influence of charge on defect matching (default is to be charge agnostic)
vac_diff_chg = identical_Cs_vacs[0].copy()
vac_diff_chg.set_charge(3.0)
self.assertTrue(pdc.are_equal(identical_Cs_vacs[0], vac_diff_chg))
chargecheck_pdc = PointDefectComparator(check_charge=True) # switch to PDC which cares about charge state
self.assertFalse(chargecheck_pdc.are_equal(identical_Cs_vacs[0], vac_diff_chg))
# test different supercell size
# (comparing same defect but different supercells - default is to not check for this)
sc_agnostic_pdc = PointDefectComparator(check_primitive_cell=True)
sc_scaled_s_struc = s_struc.copy()
sc_scaled_s_struc.make_supercell([2, 2, 3])
sc_scaled_I_vac_sublatt1_ps1 = PeriodicSite(
"I",
identical_I_vacs_sublattice1[0].site.coords,
sc_scaled_s_struc.lattice,
coords_are_cartesian=True,
)
sc_scaled_I_vac_sublatt1_ps2 = PeriodicSite(
"I",
identical_I_vacs_sublattice1[1].site.coords,
sc_scaled_s_struc.lattice,
coords_are_cartesian=True,
)
sc_scaled_I_vac_sublatt2_ps = PeriodicSite(
"I",
identical_I_vacs_sublattice2[1].site.coords,
sc_scaled_s_struc.lattice,
coords_are_cartesian=True,
)
sc_scaled_I_vac_sublatt1_defect1 = Vacancy(sc_scaled_s_struc, sc_scaled_I_vac_sublatt1_ps1)
sc_scaled_I_vac_sublatt1_defect2 = Vacancy(sc_scaled_s_struc, sc_scaled_I_vac_sublatt1_ps2)
sc_scaled_I_vac_sublatt2_defect = Vacancy(sc_scaled_s_struc, sc_scaled_I_vac_sublatt2_ps)
self.assertFalse(
pdc.are_equal(
identical_I_vacs_sublattice1[0],
# trivially same defect site but between different supercells
sc_scaled_I_vac_sublatt1_defect1,
)
)
self.assertTrue(sc_agnostic_pdc.are_equal(identical_I_vacs_sublattice1[0], sc_scaled_I_vac_sublatt1_defect1))
self.assertFalse(
pdc.are_equal(
identical_I_vacs_sublattice1[1],
# same coords, different lattice structure
sc_scaled_I_vac_sublatt1_defect1,
)
)
self.assertTrue(sc_agnostic_pdc.are_equal(identical_I_vacs_sublattice1[1], sc_scaled_I_vac_sublatt1_defect1))
self.assertFalse(
pdc.are_equal(
identical_I_vacs_sublattice1[0],
# same sublattice, different coords
sc_scaled_I_vac_sublatt1_defect2,
)
)
self.assertTrue(sc_agnostic_pdc.are_equal(identical_I_vacs_sublattice1[0], sc_scaled_I_vac_sublatt1_defect2))
self.assertFalse(
sc_agnostic_pdc.are_equal(
identical_I_vacs_sublattice1[0],
# different defects (wrong sublattice)
sc_scaled_I_vac_sublatt2_defect,
)
)
# test same structure size, but scaled lattice volume
# (default is to not allow these to be equal, but check_lattice_scale=True allows for this)
vol_agnostic_pdc = PointDefectComparator(check_lattice_scale=True)
vol_scaled_s_struc = s_struc.copy()
vol_scaled_s_struc.scale_lattice(s_struc.volume * 0.95)
vol_scaled_I_vac_sublatt1_defect1 = Vacancy(vol_scaled_s_struc, vol_scaled_s_struc[4])
vol_scaled_I_vac_sublatt1_defect2 = Vacancy(vol_scaled_s_struc, vol_scaled_s_struc[5])
vol_scaled_I_vac_sublatt2_defect = Vacancy(vol_scaled_s_struc, vol_scaled_s_struc[6])
self.assertFalse(
pdc.are_equal(
identical_I_vacs_sublattice1[0],
# trivially same defect (but vol change)
vol_scaled_I_vac_sublatt1_defect1,
)
)
self.assertTrue(vol_agnostic_pdc.are_equal(identical_I_vacs_sublattice1[0], vol_scaled_I_vac_sublatt1_defect1))
self.assertFalse(
pdc.are_equal(
identical_I_vacs_sublattice1[0],
# same defect, different sublattice point (and vol change)
vol_scaled_I_vac_sublatt1_defect2,
)
)
self.assertTrue(vol_agnostic_pdc.are_equal(identical_I_vacs_sublattice1[0], vol_scaled_I_vac_sublatt1_defect2))
self.assertFalse(
vol_agnostic_pdc.are_equal(
identical_I_vacs_sublattice1[0],
# different defect (wrong sublattice)
vol_scaled_I_vac_sublatt2_defect,
)
)
# test identical defect which has had entire lattice shifted
shift_s_struc = s_struc.copy()
shift_s_struc.translate_sites(range(len(s_struc)), [0.2, 0.3, 0.4], frac_coords=True, to_unit_cell=True)
shifted_identical_Cs_vacs = [
Vacancy(shift_s_struc, shift_s_struc[0]),
Vacancy(shift_s_struc, shift_s_struc[1]),
]
self.assertTrue(
pdc.are_equal(
identical_Cs_vacs[0],
# trivially same defect (but shifted)
shifted_identical_Cs_vacs[0],
)
)
self.assertTrue(
pdc.are_equal(
identical_Cs_vacs[0],
# same defect on different sublattice point (and shifted)
shifted_identical_Cs_vacs[1],
)
)
# test uniform lattice shift within non-symmorphic structure
shift_ns_struc = ns_struc.copy()
shift_ns_struc.translate_sites(range(len(ns_struc)), [0.0, 0.6, 0.3], frac_coords=True, to_unit_cell=True)
shift_ns_inter_H_sublattice1_set1 = PeriodicSite(
"H",
ns_inter_H_sublattice1_set1.frac_coords + [0.0, 0.6, 0.3],
shift_ns_struc.lattice,
)
shift_ns_inter_H_sublattice1_set2 = PeriodicSite(
"H",
ns_inter_H_sublattice1_set2.frac_coords + [0.0, 0.6, 0.3],
shift_ns_struc.lattice,
)
self.assertTrue(
pdc.are_equal(
Interstitial(ns_struc, ns_inter_H_sublattice1_set1),
# trivially same defect (but shifted)
Interstitial(shift_ns_struc, shift_ns_inter_H_sublattice1_set1),
)
)
self.assertTrue(
pdc.are_equal(
Interstitial(ns_struc, ns_inter_H_sublattice1_set1),
# same defect on different sublattice point (and shifted)
Interstitial(shift_ns_struc, shift_ns_inter_H_sublattice1_set2),
)
)
# test a rotational + supercell type structure transformation (requires check_primitive_cell=True)
rotated_s_struc = s_struc.copy()
rotated_s_struc.make_supercell([[2, 1, 0], [-1, 3, 0], [0, 0, 2]])
rotated_identical_Cs_vacs = [
Vacancy(rotated_s_struc, rotated_s_struc[0]),
Vacancy(rotated_s_struc, rotated_s_struc[1]),
]
self.assertFalse(
pdc.are_equal(
identical_Cs_vacs[0],
# trivially same defect (but rotated)
rotated_identical_Cs_vacs[0],
)
)
self.assertTrue(sc_agnostic_pdc.are_equal(identical_Cs_vacs[0], rotated_identical_Cs_vacs[0]))
self.assertFalse(
pdc.are_equal(
identical_Cs_vacs[0],
# same defect on different sublattice (and rotated)
rotated_identical_Cs_vacs[1],
)
)
self.assertTrue(
sc_agnostic_pdc.are_equal(
identical_Cs_vacs[0],
# same defect on different sublattice point (and rotated)
rotated_identical_Cs_vacs[1],
)
)
# test a rotational + supercell + shift type structure transformation for non-symmorphic structure
rotANDshift_ns_struc = ns_struc.copy()
rotANDshift_ns_struc.translate_sites(range(len(ns_struc)), [0.0, 0.6, 0.3], frac_coords=True, to_unit_cell=True)
rotANDshift_ns_struc.make_supercell([[2, 1, 0], [-1, 3, 0], [0, 0, 2]])
ns_vac_Cs_set1 = Vacancy(ns_struc, ns_struc[0])
rotANDshift_ns_vac_Cs_set1 = Vacancy(rotANDshift_ns_struc, rotANDshift_ns_struc[0])
rotANDshift_ns_vac_Cs_set2 = Vacancy(rotANDshift_ns_struc, rotANDshift_ns_struc[1])
self.assertTrue(
sc_agnostic_pdc.are_equal(
ns_vac_Cs_set1,
# trivially same defect (but rotated and sublattice shifted)
rotANDshift_ns_vac_Cs_set1,
)
)
self.assertTrue(
sc_agnostic_pdc.are_equal(
ns_vac_Cs_set1,
# same defect on different sublattice point (shifted and rotated)
rotANDshift_ns_vac_Cs_set2,
)
)
if __name__ == "__main__":
unittest.main()
|
richardtran415/pymatgen
|
pymatgen/analysis/tests/test_structure_matcher.py
|
Python
|
mit
| 47,994
|
#ifndef SRC_NODE_LTTNG_PROVIDER_H_
#define SRC_NODE_LTTNG_PROVIDER_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#define TRACEPOINT_CREATE_PROBES
#define TRACEPOINT_DEFINE
#include "node_lttng_tp.h"
namespace node {
#define FOR_ALL_GC_TYPES(APPLY) \
APPLY(kGCTypeScavenge) \
APPLY(kGCTypeMarkSweepCompact) \
APPLY(kGCTypeAll)
#define FOR_ALL_GC_CALLBACK_FLAGS(APPLY) \
APPLY(kNoGCCallbackFlags) \
APPLY(kGCCallbackFlagConstructRetainedObjectInfos) \
APPLY(kGCCallbackFlagForced) \
APPLY(kGCCallbackFlagSynchronousPhantomCallbackProcessing)
void NODE_HTTP_SERVER_REQUEST(node_lttng_http_server_request_t* req,
node_lttng_connection_t* conn,
const char *remote, int port,
const char *method, const char *url,
int fd) {
tracepoint(node, http_server_request, req->url, req->method, \
req->forwarded_for);
}
void NODE_HTTP_SERVER_RESPONSE(node_lttng_connection_t* conn,
const char *remote, int port, int fd) {
tracepoint(node, http_server_response, port, conn->remote, fd);
}
void NODE_HTTP_CLIENT_REQUEST(node_lttng_http_client_request_t* req,
node_lttng_connection_t* conn,
const char *remote, int port,
const char *method, const char *url,
int fd) {
tracepoint(node, http_client_request, req->url, req->method);
}
void NODE_HTTP_CLIENT_RESPONSE(node_lttng_connection_t* conn,
const char *remote, int port, int fd) {
tracepoint(node, http_client_response, port, conn->remote, fd);
}
void NODE_NET_SERVER_CONNECTION(node_lttng_connection_t* conn,
const char *remote, int port, int fd) {
tracepoint(node, net_server_connection, conn->remote, port, fd, \
conn->buffered);
}
void NODE_NET_STREAM_END(node_lttng_connection_t* conn,
const char *remote, int port, int fd) {
tracepoint(node, net_stream_end, conn->remote, port, fd);
}
void NODE_GC_START(v8::GCType type,
v8::GCCallbackFlags flags,
v8::Isolate* isolate) {
const char* typeStr = "Unknown GC Type";
const char* flagsStr = "Unknown GC Flag";
#define BUILD_IF(f) if (type == v8::GCType::f) { typeStr = #f; }
FOR_ALL_GC_TYPES(BUILD_IF);
#undef BUILD_IF
#define BUILD_IF(f) if (flags == v8::GCCallbackFlags::f) { flagsStr = #f; }
FOR_ALL_GC_CALLBACK_FLAGS(BUILD_IF);
#undef BUILD_IF
tracepoint(node, gc_start, typeStr, flagsStr);
}
void NODE_GC_DONE(v8::GCType type,
v8::GCCallbackFlags flags,
v8::Isolate* isolate) {
const char* typeStr = "Unknown GC Type";
const char* flagsStr = "Unknown GC Flag";
#define BUILD_IF(f) if (type == v8::GCType::f) { typeStr = #f; }
FOR_ALL_GC_TYPES(BUILD_IF);
#undef BUILD_IF
#define BUILD_IF(f) if (flags == v8::GCCallbackFlags::f) { flagsStr = #f; }
FOR_ALL_GC_CALLBACK_FLAGS(BUILD_IF);
#undef BUILD_IF
tracepoint(node, gc_done, typeStr, flagsStr);
}
bool NODE_HTTP_SERVER_REQUEST_ENABLED() { return true; }
bool NODE_HTTP_SERVER_RESPONSE_ENABLED() { return true; }
bool NODE_HTTP_CLIENT_REQUEST_ENABLED() { return true; }
bool NODE_HTTP_CLIENT_RESPONSE_ENABLED() { return true; }
bool NODE_NET_SERVER_CONNECTION_ENABLED() { return true; }
bool NODE_NET_STREAM_END_ENABLED() { return true; }
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_NODE_LTTNG_PROVIDER_H_
|
hoho/dosido
|
nodejs/src/node_lttng_provider.h
|
C
|
mit
| 3,638
|
var global = require('../internals/global');
var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var redefine = require('../internals/redefine');
var setGlobal = require('../internals/set-global');
var copyConstructorProperties = require('../internals/copy-constructor-properties');
var isForced = require('../internals/is-forced');
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.noTargetGet - prevent calling a getter on target
options.name - the .name of the function if it does not match the key
*/
module.exports = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var FORCED, target, key, targetProperty, sourceProperty, descriptor;
if (GLOBAL) {
target = global;
} else if (STATIC) {
target = global[TARGET] || setGlobal(TARGET, {});
} else {
target = (global[TARGET] || {}).prototype;
}
if (target) for (key in source) {
sourceProperty = source[key];
if (options.noTargetGet) {
descriptor = getOwnPropertyDescriptor(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contained in target
if (!FORCED && targetProperty !== undefined) {
if (typeof sourceProperty == typeof targetProperty) continue;
copyConstructorProperties(sourceProperty, targetProperty);
}
// add a flag to not completely full polyfills
if (options.sham || (targetProperty && targetProperty.sham)) {
createNonEnumerableProperty(sourceProperty, 'sham', true);
}
// extend global
redefine(target, key, sourceProperty, options);
}
};
|
zloirock/core-js
|
packages/core-js/internals/export.js
|
JavaScript
|
mit
| 2,597
|
#!/bin/bash
set -e
/work/prepare_repo.sh
#source emsdk/emsdk_env.sh
cd duktape
/bin/bash --login
|
svaarala/duktape
|
docker/duktape-shell-ubuntu-20.04-arm64/run.sh
|
Shell
|
mit
| 101
|
// word frequencies of first two chapters of Oliver Twist
var words = [
{text: 'have', size: 102},
{text: 'Oliver', size: 47},
{text: 'say', size: 46},
{text: 'said', size: 36},
{text: 'bumble', size: 29, href: 'https://en.wikipedia.org/wiki/Beadle'},
{text: 'will', size: 29},
{text: 'Mrs', size: 56, href: 'https://en.wikipedia.org/wiki/Mrs.'},
{text: 'Mann', size: 27, href: 'http://educationcing.blogspot.nl/2012/06/oliver-twist-mrs-manns-character.html'},
{text: 'Mr', size: 27},
{text: 'very', size: 26},
{text: 'child', size: 20},
{text: 'all', size: 19},
{text: 'boy', size: 19},
{text: 'gentleman', size: 19, href: 'http://www.thefreelibrary.com/The+gentleman+in+the+white+waistcoat%3a+Dickens+and+metonymy.-a0154239625'},
{text: 'great', size: 19},
{text: 'take', size: 19},
{text: 'but', size: 18},
{text: 'beadle', size: 16},
{text: 'twist', size: 16},
{text: 'board', size: 15},
{text: 'more', size: 15},
{text: 'one', size: 15},
{text: 'workhouse', size: 15},
{text: 'parish', size: 14},
{text: 'there', size: 14},
{text: 'come', size: 13},
{text: 'hand', size: 13},
{text: 'know', size: 13},
{text: 'sir', size: 13},
{text: 'being', size: 12},
{text: 'head', size: 12},
{text: 'make', size: 12},
{text: 'out', size: 12},
{text: 'can', size: 11},
{text: 'little', size: 11},
{text: 'reply', size: 11},
{text: 'any', size: 10},
{text: 'cry', size: 10},
{text: 'good', size: 10},
{text: 'name', size: 10},
{text: 'poor', size: 10},
{text: 'time', size: 10},
{text: 'two', size: 10},
{text: 'after', size: 9},
{text: 'dear', size: 9},
{text: 'get', size: 9},
{text: 'gruel', size: 9},
{text: 'long', size: 9},
{text: 'may', size: 9},
{text: 'never', size: 9},
{text: 'some', size: 9},
{text: 'well', size: 9},
{text: 'white', size: 9},
{text: 'woman', size: 9},
{text: 'chair', size: 8},
{text: 'day', size: 8},
{text: 'give', size: 8},
{text: 'inquire', size: 8},
{text: 'made', size: 8},
{text: 'next', size: 8},
{text: 'now', size: 8},
{text: 'other', size: 8},
{text: 'over', size: 8},
{text: 'small', size: 8},
{text: 'surgeon', size: 8},
{text: 'think', size: 8},
{text: 'too', size: 8},
{text: 'walk', size: 8},
{text: 'want', size: 8},
{text: 'bless', size: 7},
{text: 'eye', size: 7},
{text: 'man', size: 7},
{text: 'master', size: 7},
{text: 'most', size: 7},
{text: 'old', size: 7},
{text: 'people', size: 7},
{text: 'see', size: 7},
{text: 'another', size: 6},
{text: 'at all', size: 6},
{text: 'authorities', size: 6},
{text: 'authority', size: 6},
{text: 'away', size: 6},
{text: 'face', size: 6},
{text: 'gate', size: 6},
{text: 'half', size: 6},
{text: 'hands', size: 6},
{text: 'heart', size: 6},
{text: 'last', size: 6},
{text: 'might', size: 6},
{text: 'nurse', size: 6},
{text: 'once', size: 6},
{text: 'place', size: 6},
{text: 'room', size: 6},
{text: 'table', size: 6},
{text: 'three', size: 6},
{text: 'voice', size: 6},
{text: 'waistcoat', size: 6},
{text: 'wash', size: 6},
{text: 'water', size: 6},
{text: 'a little', size: 5},
{text: 'bow', size: 5},
{text: 'business', size: 5},
{text: 'drop', size: 5},
{text: 'eyes', size: 5},
{text: 'fall', size: 5},
{text: 'find', size: 5},
{text: 'gin', size: 5},
{text: 'high', size: 5},
{text: 'house', size: 5},
{text: 'infant', size: 5},
{text: 'night', size: 5},
{text: 'nobody', size: 5},
{text: 'orphan', size: 5},
{text: 'pauper', size: 5},
{text: 'perhaps', size: 5},
{text: 'rather', size: 5},
{text: 'round', size: 5},
{text: 'sit', size: 5},
{text: 'world', size: 5},
{text: 'young', size: 5},
{text: 'add', size: 4},
{text: 'ask', size: 4},
{text: 'at once', size: 4},
{text: 'behind', size: 4},
{text: 'bottle', size: 4},
{text: 'bread', size: 4},
{text: 'care', size: 4},
{text: 'copper', size: 4},
{text: 'die', size: 4},
{text: 'farm', size: 4},
{text: 'fat', size: 4},
{text: 'father', size: 4},
{text: 'fell', size: 4},
{text: 'female', size: 4},
{text: 'going', size: 4},
{text: 'happen', size: 4},
{text: 'hat', size: 4},
{text: 'here', size: 4},
{text: 'however', size: 4},
{text: 'hungry', size: 4},
{text: 'in this', size: 4},
{text: 'keep', size: 4},
{text: 'large', size: 4},
{text: 'low', size: 4},
{text: 'matter', size: 4},
{text: 'out of', size: 4},
{text: 'pound', size: 4},
{text: 'public', size: 4},
{text: 'quarter', size: 4},
{text: 'quite', size: 4},
{text: 'raise', size: 4},
{text: 'sleep', size: 4},
{text: 'spirit', size: 4},
{text: 'ten', size: 4},
{text: 'turn', size: 4},
{text: 'wanted', size: 4},
{text: 'washing', size: 4},
{text: 'week', size: 4},
{text: 'word', size: 4},
{text: 'age', size: 3},
{text: 'arm', size: 3},
{text: 'ask for', size: 3},
{text: 'assistant', size: 3},
{text: 'be born', size: 3},
{text: 'bed', size: 3},
{text: 'bill', size: 3},
{text: 'body', size: 3},
{text: 'born', size: 3},
{text: 'brick', size: 3},
{text: 'bring', size: 3},
{text: 'cane', size: 3},
{text: 'case', size: 3},
{text: 'Christian', size: 3},
{text: 'circumstance', size: 3},
{text: 'cock', size: 3},
{text: 'cocked hat', size: 3},
{text: 'cold', size: 3},
{text: 'come to', size: 3},
{text: 'companion', size: 3},
{text: 'consequence', size: 3},
{text: 'corner', size: 3},
{text: 'deposit', size: 3},
{text: 'dress', size: 3},
{text: 'eat', size: 3},
{text: 'eight', size: 3},
{text: 'expect', size: 3},
{text: 'expected', size: 3},
{text: 'experimental', size: 3},
{text: 'feed', size: 3},
{text: 'fire', size: 3},
{text: 'glass', size: 3},
{text: 'go to', size: 3},
{text: 'green', size: 3},
{text: 'halfpenny', size: 3},
{text: 'hang', size: 3},
{text: 'have got', size: 3},
{text: 'hint', size: 3},
{text: 'hunger', size: 3},
{text: 'interest', size: 3},
{text: 'known', size: 3},
{text: 'latter', size: 3},
{text: 'lay', size: 3},
{text: 'lead', size: 3},
{text: 'let', size: 3},
{text: 'live', size: 3},
{text: 'mention', size: 3},
{text: 'month', size: 3},
{text: 'morning', size: 3},
{text: 'ninth', size: 3},
{text: 'offer', size: 3},
{text: 'old woman', size: 3},
{text: 'open', size: 3},
{text: 'operation', size: 3},
{text: 'order', size: 3},
{text: 'pale', size: 3},
{text: 'pick', size: 3},
{text: 'possess', size: 3},
{text: 'possible', size: 3},
{text: 'pray', size: 3},
{text: 'process', size: 3},
{text: 'proper', size: 3},
{text: 'purpose', size: 3},
{text: 'raised', size: 3},
{text: 'remove', size: 3},
{text: 'removed', size: 3},
{text: 'render', size: 3},
{text: 'set', size: 3},
{text: 'shake', size: 3},
{text: 'sitting', size: 3},
{text: 'smile', size: 3},
{text: 'somewhat', size: 3},
{text: 'speak', size: 3},
{text: 'spoon', size: 3},
{text: 'supper', size: 3},
{text: 'sure', size: 3},
{text: 'system', size: 3},
{text: 'tender', size: 3},
{text: 'thin', size: 3},
{text: 'troublesome', size: 3},
{text: 'twenty', size: 3},
{text: 'usually', size: 3},
{text: 'words', size: 3},
{text: 'yes', size: 3},
{text: 'a great deal', size: 2},
{text: 'accident', size: 2},
{text: 'accompanied', size: 2},
{text: 'accompany', size: 2},
{text: 'advance', size: 2},
{text: 'advancing', size: 2},
{text: 'allowance', size: 2},
{text: 'answer', size: 2},
{text: 'appear', size: 2},
{text: 'apron', size: 2},
{text: 'arrive', size: 2},
{text: 'assign', size: 2},
{text: 'astonishment', size: 2},
{text: 'at last', size: 2},
{text: 'attend', size: 2},
{text: 'basin', size: 2},
{text: 'bedstead', size: 2},
{text: 'besides', size: 2},
{text: 'birth', size: 2},
{text: 'birthday', size: 2},
{text: 'bowed', size: 2},
{text: 'bowl', size: 2},
{text: 'bowls', size: 2},
{text: 'breast', size: 2},
{text: 'brief', size: 2},
{text: 'bring up', size: 2},
{text: 'cast', size: 2},
{text: 'catch', size: 2},
{text: 'class', size: 2},
{text: 'clothe', size: 2},
{text: 'common', size: 2},
{text: 'compel', size: 2},
{text: 'compose', size: 2},
{text: 'conduct', size: 2},
{text: 'considerable', size: 2},
{text: 'consolation', size: 2},
{text: 'contract', size: 2},
{text: 'convince', size: 2},
{text: 'convinced', size: 2},
{text: 'cook', size: 2},
{text: 'countenance', size: 2},
{text: 'couple', size: 2},
{text: 'cry for', size: 2},
{text: 'crying', size: 2},
{text: 'cuff', size: 2},
{text: 'deal', size: 2},
{text: 'decidedly', size: 2},
{text: 'deeply', size: 2},
{text: 'diet', size: 2},
{text: 'difficulty', size: 2},
{text: 'dinner', size: 2},
{text: 'directly', size: 2},
{text: 'discover', size: 2},
{text: 'draw', size: 2},
{text: 'ecstasy', size: 2},
{text: 'elderly', size: 2},
{text: 'evening', size: 2},
{text: 'excellent', size: 2},
{text: 'except', size: 2},
{text: 'experience', size: 2},
{text: 'extraordinary', size: 2},
{text: 'faint', size: 2},
{text: 'fall into', size: 2},
{text: 'fist', size: 2},
{text: 'floor', size: 2},
{text: 'follow', size: 2},
{text: 'food', size: 2},
{text: 'fool', size: 2},
{text: 'forehead', size: 2},
{text: 'frighten', size: 2},
{text: 'frightened', size: 2},
{text: 'garden', size: 2},
{text: 'gaze', size: 2},
{text: 'glance', size: 2},
{text: 'go along', size: 2},
{text: 'grasp', size: 2},
{text: 'grasping', size: 2},
{text: 'great deal', size: 2},
{text: 'hope', size: 2},
{text: 'horse', size: 2},
{text: 'humane', size: 2},
{text: 'humility', size: 2},
{text: 'impress', size: 2},
{text: 'impressed', size: 2},
{text: 'in no time', size: 2},
{text: 'in other words', size: 2},
{text: 'increase', size: 2},
{text: 'inmate', size: 2},
{text: 'inside', size: 2},
{text: 'instead', size: 2},
{text: 'interesting', size: 2},
{text: 'interpose', size: 2},
{text: 'ladle', size: 2},
{text: 'lady', size: 2},
{text: 'leaving', size: 2},
{text: 'loud', size: 2},
{text: 'mile', size: 2},
{text: 'misery', size: 2},
{text: 'nearly', size: 2},
{text: 'necessary', size: 2},
{text: 'notwithstanding', size: 2},
{text: 'oakum', size: 2},
{text: 'on the table', size: 2},
{text: 'opened', size: 2},
{text: 'overseer', size: 2},
{text: 'philosopher', size: 2},
{text: 'picking', size: 2},
{text: 'piece', size: 2},
{text: 'pillow', size: 2},
{text: 'please', size: 2},
{text: 'pocket', size: 2},
{text: 'poor people', size: 2},
{text: 'possessed', size: 2},
{text: 'probable', size: 2},
{text: 'proceed', size: 2},
{text: 'produce', size: 2},
{text: 'provide', size: 2},
{text: 'putt', size: 2},
{text: 'putting', size: 2},
{text: 'red', size: 2},
{text: 'relief', size: 2},
{text: 'remain', size: 2},
{text: 'repeat', size: 2},
{text: 'result', size: 2},
{text: 'reward', size: 2},
{text: 'roll', size: 2},
{text: 'rose', size: 2},
{text: 'seat', size: 2},
{text: 'sense', size: 2},
{text: 'shaking', size: 2},
{text: 'sight', size: 2},
{text: 'situation', size: 2},
{text: 'six', size: 2, href: 'https://en.wikipedia.org/wiki/Six'},
{text: 'slice', size: 2},
{text: 'society', size: 2},
{text: 'spoke', size: 2},
{text: 'start', size: 2},
{text: 'starve', size: 2},
{text: 'starved', size: 2},
{text: 'station', size: 2},
{text: 'stop', size: 2},
{text: 'stranger', size: 2},
{text: 'suffer', size: 2},
{text: 'supply', size: 2},
{text: 'support', size: 2},
{text: 'suppose', size: 2},
{text: 'take care', size: 2},
{text: 'taking', size: 2},
{text: 'talk', size: 2},
{text: 'tap', size: 2},
{text: 'teach', size: 2},
{text: 'tear', size: 2},
{text: 'tears', size: 2},
{text: 'telling', size: 2},
{text: 'to that', size: 2},
{text: 'tone', size: 2},
{text: 'too much', size: 2},
{text: 'town', size: 2},
{text: 'trade', size: 2},
{text: 'treat', size: 2},
{text: 'trouble', size: 2},
{text: 'useful', size: 2},
{text: 'usher', size: 2},
{text: 'view', size: 2},
{text: 'walk in', size: 2},
{text: 'warden', size: 2},
{text: 'wicket', size: 2},
{text: 'wild', size: 2},
{text: 'wisdom', size: 2},
{text: 'wretched', size: 2},
{text: 'young woman', size: 2},
{text: 'a couple of', size: 1},
{text: 'accurate', size: 1},
{text: 'address', size: 1},
{text: 'advertise', size: 1},
{text: 'affect', size: 1},
{text: 'affected', size: 1},
{text: 'affix', size: 1},
{text: 'agony', size: 1},
{text: 'aim', size: 1},
{text: 'alarm', size: 1},
{text: 'alarmed', size: 1},
{text: 'alive', size: 1},
{text: 'all over', size: 1},
{text: 'all the way', size: 1},
{text: 'allot', size: 1},
{text: 'allotted', size: 1},
{text: 'aloud', size: 1},
{text: 'alphabet', size: 1},
{text: 'alphabetical', size: 1},
{text: 'alternately', size: 1},
{text: 'alternative', size: 1},
{text: 'anciently', size: 1},
{text: 'animate', size: 1},
{text: 'animated', size: 1},
{text: 'anxious', size: 1},
{text: 'apparently', size: 1},
{text: 'apparition', size: 1},
{text: 'appendage', size: 1},
{text: 'appetite', size: 1},
{text: 'applicant', size: 1},
{text: 'applied', size: 1},
{text: 'apply', size: 1},
{text: 'apprentice', size: 1},
{text: 'approach', size: 1},
{text: 'approaching', size: 1},
{text: 'appropriate', size: 1},
{text: 'approvingly', size: 1},
{text: 'arrive at', size: 1},
{text: 'articulate', size: 1},
{text: 'articulated', size: 1},
{text: 'as it is', size: 1},
{text: 'assiduously', size: 1},
{text: 'assigned', size: 1},
{text: 'assist', size: 1},
{text: 'assisted', size: 1},
{text: 'astound', size: 1},
{text: 'astounded', size: 1},
{text: 'at length', size: 1},
{text: 'atrociously', size: 1},
{text: 'attended', size: 1},
{text: 'attending', size: 1},
{text: 'attribute', size: 1},
{text: 'awaken', size: 1},
{text: 'bachelor', size: 1},
{text: 'badge', size: 1},
{text: 'bait', size: 1},
{text: 'balance', size: 1},
{text: 'baptize', size: 1},
{text: 'baptized', size: 1},
{text: 'Beadle', size: 1},
{text: 'beer', size: 1},
{text: 'befall', size: 1},
{text: 'beg', size: 1},
{text: 'beggar', size: 1},
{text: 'behold', size: 1},
{text: 'benevolent', size: 1},
{text: 'bestow', size: 1},
{text: 'bid', size: 1},
{text: 'bidding', size: 1},
{text: 'biography', size: 1},
{text: 'bitterly', size: 1},
{text: 'blandness', size: 1},
{text: 'blanket', size: 1},
{text: 'blessed', size: 1},
{text: 'blessing', size: 1},
{text: 'blow', size: 1},
{text: 'bolt', size: 1},
{text: 'bosom', size: 1},
{text: 'branch', size: 1},
{text: 'brat', size: 1},
{text: 'bread and butter', size: 1},
{text: 'breakfast', size: 1},
{text: 'breathe', size: 1},
{text: 'breathed', size: 1},
{text: 'brown', size: 1},
{text: 'brush', size: 1},
{text: 'brushed', size: 1},
{text: 'buffet', size: 1},
{text: 'buffeted', size: 1},
{text: 'build', size: 1},
{text: 'burden', size: 1},
{text: 'burst', size: 1},
{text: 'butter', size: 1},
{text: 'by hand', size: 1},
{text: 'by no means', size: 1},
{text: 'calico', size: 1},
{text: 'calling', size: 1},
{text: 'calm', size: 1},
{text: 'cap', size: 1},
{text: 'capital', size: 1},
{text: 'captivate', size: 1},
{text: 'captivating', size: 1},
{text: 'careful', size: 1},
{text: 'carelessly', size: 1},
{text: 'catch sight', size: 1},
{text: 'catch up', size: 1},
{text: 'catching', size: 1},
{text: 'cellar', size: 1},
{text: 'chafe', size: 1},
{text: 'chafed', size: 1},
{text: 'check', size: 1},
{text: 'checked', size: 1},
{text: 'cheerfulness', size: 1},
{text: 'childish', size: 1},
{text: 'choleric', size: 1},
{text: 'circumference', size: 1},
{text: 'clean', size: 1},
{text: 'clearly', size: 1},
{text: 'cling', size: 1},
{text: 'cloth', size: 1},
{text: 'clothes', size: 1},
{text: 'clothing', size: 1},
{text: 'coal', size: 1},
{text: 'coat', size: 1},
{text: 'cold water', size: 1},
{text: 'combination', size: 1},
{text: 'come on', size: 1},
{text: 'come out', size: 1},
{text: 'comfort', size: 1},
{text: 'comfortable', size: 1},
{text: 'Commons', size: 1},
{text: 'commons', size: 1},
{text: 'compelling', size: 1},
{text: 'complacently', size: 1},
{text: 'completed', size: 1},
{text: 'compliment', size: 1},
{text: 'composed', size: 1},
{text: 'composition', size: 1},
{text: 'comprise', size: 1},
{text: 'concise', size: 1},
{text: 'conclave', size: 1},
{text: 'confinement', size: 1},
{text: 'consideration', size: 1},
{text: 'consign', size: 1},
{text: 'consolatory', size: 1},
{text: 'contents', size: 1},
{text: 'contracted', size: 1},
{text: 'contrive', size: 1},
{text: 'contrived', size: 1},
{text: 'controvert', size: 1},
{text: 'cork', size: 1},
{text: 'corn', size: 1},
{text: 'cottage', size: 1},
{text: 'cough', size: 1},
{text: 'coupled', size: 1},
{text: 'cover', size: 1},
{text: 'covering', size: 1},
{text: 'coverlet', size: 1},
{text: 'crop', size: 1},
{text: 'culprit', size: 1},
{text: 'cupboard', size: 1},
{text: 'curtsey', size: 1},
{text: 'custom', size: 1},
{text: 'darkly', size: 1},
{text: 'date', size: 1},
{text: 'deceive', size: 1},
{text: 'deception', size: 1},
{text: 'decision', size: 1},
{text: 'define', size: 1},
{text: 'defined', size: 1},
{text: 'delegate', size: 1},
{text: 'deliberation', size: 1},
{text: 'deliver', size: 1},
{text: 'demolition', size: 1},
{text: 'demonstrate', size: 1},
{text: 'demonstrated', size: 1},
{text: 'depict', size: 1},
{text: 'depicted', size: 1},
{text: 'depth', size: 1},
{text: 'desperate', size: 1},
{text: 'despise', size: 1},
{text: 'despised', size: 1},
{text: 'destitute', size: 1},
{text: 'determine', size: 1},
{text: 'devotional', size: 1},
{text: 'devour', size: 1},
{text: 'dietary', size: 1},
{text: 'dignified', size: 1},
{text: 'dignify', size: 1},
{text: 'dignity', size: 1},
{text: 'diminutive', size: 1},
{text: 'dirt', size: 1},
{text: 'disappear', size: 1},
{text: 'discussion', size: 1},
{text: 'dispatch', size: 1},
{text: 'display', size: 1},
{text: 'dispose', size: 1},
{text: 'disposed', size: 1},
{text: 'distinctly', size: 1},
{text: 'divide', size: 1},
{text: 'divided', size: 1},
{text: 'divorce', size: 1},
{text: 'doctor', size: 1},
{text: 'Doctor', size: 1},
{text: 'domicile', size: 1},
{text: 'dressed', size: 1},
{text: 'drudge', size: 1},
{text: 'duly', size: 1},
{text: 'dying', size: 1},
{text: 'eager', size: 1},
{text: 'ease', size: 1},
{text: 'eating', size: 1},
{text: 'educate', size: 1},
{text: 'educated', size: 1},
{text: 'education', size: 1},
{text: 'emanate', size: 1},
{text: 'embrace', size: 1},
{text: 'employ', size: 1},
{text: 'encrust', size: 1},
{text: 'encrusted', size: 1},
{text: 'engender', size: 1},
{text: 'entertainment', size: 1},
{text: 'envelop', size: 1},
{text: 'enviable', size: 1},
{text: 'establish', size: 1},
{text: 'established', size: 1},
{text: 'establishment', size: 1},
{text: 'evaporate', size: 1},
{text: 'evaporated', size: 1},
{text: 'event', size: 1},
{text: 'every night', size: 1},
{text: 'every quarter', size: 1},
{text: 'evident', size: 1},
{text: 'evidently', size: 1},
{text: 'excitement', size: 1},
{text: 'exercise', size: 1},
{text: 'exertion', size: 1},
{text: 'exist', size: 1},
{text: 'expand', size: 1},
{text: 'expense', size: 1},
{text: 'expensive', size: 1},
{text: 'experienced', size: 1},
{text: 'extant', size: 1},
{text: 'faced', size: 1},
{text: 'factor', size: 1},
{text: 'fail', size: 1},
{text: 'faithful', size: 1},
{text: 'fall back', size: 1},
{text: 'fall out', size: 1},
{text: 'farming', size: 1},
{text: 'favour', size: 1},
{text: 'feebly', size: 1},
{text: 'feint', size: 1},
{text: 'festive', size: 1},
{text: 'fetch', size: 1},
{text: 'fictitious', size: 1},
{text: 'fictitious name', size: 1},
{text: 'find out', size: 1},
{text: 'finding', size: 1},
{text: 'finger', size: 1},
{text: 'finish', size: 1},
{text: 'firmly', size: 1},
{text: 'fling', size: 1},
{text: 'flock', size: 1},
{text: 'flutter', size: 1},
{text: 'folk', size: 1},
{text: 'folks', size: 1},
{text: 'fond', size: 1},
{text: 'fondling', size: 1},
{text: 'for the first time', size: 1},
{text: 'forever', size: 1},
{text: 'forgotten', size: 1},
{text: 'forthwith', size: 1},
{text: 'fortunate', size: 1},
{text: 'fortunately', size: 1},
{text: 'furious', size: 1},
{text: 'gasp', size: 1},
{text: 'gather', size: 1},
{text: 'gathered', size: 1},
{text: 'generation', size: 1},
{text: 'gesture', size: 1},
{text: 'get behind', size: 1},
{text: 'get to', size: 1},
{text: 'gloom', size: 1},
{text: 'glove', size: 1},
{text: 'go away', size: 1},
{text: 'go to sleep', size: 1},
{text: 'go with', size: 1},
{text: 'going away', size: 1},
{text: 'good-looking', size: 1},
{text: 'goodness', size: 1},
{text: 'grace', size: 1},
{text: 'gracious', size: 1},
{text: 'gradual', size: 1},
{text: 'grandmother', size: 1},
{text: 'gratified', size: 1},
{text: 'gratify', size: 1},
{text: 'grief', size: 1},
{text: 'grown', size: 1},
{text: 'gruff', size: 1},
{text: 'hall', size: 1},
{text: 'hand over', size: 1},
{text: 'handed', size: 1},
{text: 'hastily', size: 1},
{text: 'haughty', size: 1},
{text: 'headed', size: 1},
{text: 'healthy', size: 1},
{text: 'hesitate', size: 1},
{text: 'hesitating', size: 1},
{text: 'hitherto', size: 1},
{text: 'horror', size: 1},
{text: 'human being', size: 1},
{text: 'humanely', size: 1},
{text: 'humble', size: 1},
{text: 'hurried', size: 1},
{text: 'hurry', size: 1},
{text: 'hush', size: 1},
{text: 'ill-usage', size: 1},
{text: 'illustration', size: 1},
{text: 'impart', size: 1},
{text: 'imperfectly', size: 1},
{text: 'impertinence', size: 1},
{text: 'implant', size: 1},
{text: 'implanted', size: 1},
{text: 'implicitly', size: 1},
{text: 'importance', size: 1},
{text: 'impose', size: 1},
{text: 'imposed', size: 1},
{text: 'imprint', size: 1},
{text: 'in full', size: 1},
{text: 'in hand', size: 1},
{text: 'inadvertently', size: 1},
{text: 'inconvenience', size: 1},
{text: 'increased', size: 1},
{text: 'indubitably', size: 1},
{text: 'induce', size: 1},
{text: 'inducing', size: 1},
{text: 'inestimable', size: 1},
{text: 'inevitably', size: 1},
{text: 'inflame', size: 1},
{text: 'inflaming', size: 1},
{text: 'inform', size: 1},
{text: 'informed', size: 1},
{text: 'inheritance', size: 1},
{text: 'inquest', size: 1},
{text: 'inquiring', size: 1},
{text: 'inseparable', size: 1},
{text: 'instant', size: 1},
{text: 'intelligence', size: 1},
{text: 'interrogation', size: 1},
{text: 'invariably', size: 1},
{text: 'invitation', size: 1},
{text: 'issue', size: 1},
{text: 'item', size: 1},
{text: 'jury', size: 1},
{text: 'juvenile', size: 1},
{text: 'keeping', size: 1},
{text: 'kick', size: 1},
{text: 'kill', size: 1},
{text: 'kindly', size: 1},
{text: 'kindness', size: 1},
{text: 'kindred', size: 1},
{text: 'knock', size: 1},
{text: 'knowing', size: 1},
{text: 'lace', size: 1},
{text: 'laced', size: 1},
{text: 'lady of the house', size: 1},
{text: 'lamb', size: 1},
{text: 'large white', size: 1},
{text: 'lean', size: 1},
{text: 'leave behind', size: 1},
{text: 'left hand', size: 1},
{text: 'leg', size: 1},
{text: 'lie', size: 1},
{text: 'lie in', size: 1},
{text: 'lighted', size: 1},
{text: 'liked', size: 1},
{text: 'linger', size: 1},
{text: 'lingering', size: 1},
{text: 'lip', size: 1},
{text: 'listen', size: 1},
{text: 'literary', size: 1},
{text: 'literature', size: 1},
{text: 'lively', size: 1},
{text: 'lock', size: 1},
{text: 'lock up', size: 1},
{text: 'loneliness', size: 1},
{text: 'long time', size: 1},
{text: 'long-headed', size: 1},
{text: 'loosely', size: 1},
{text: 'lots', size: 1},
{text: 'lowest', size: 1},
{text: 'lump', size: 1},
{text: 'lung', size: 1},
{text: 'lustily', size: 1},
{text: 'luxuriant', size: 1},
{text: 'magnanimously', size: 1},
{text: 'maintain', size: 1},
{text: 'majestic', size: 1},
{text: 'make it', size: 1},
{text: 'male', size: 1},
{text: 'mar', size: 1},
{text: 'marry', size: 1},
{text: 'marvellously', size: 1},
{text: 'material', size: 1},
{text: 'mattress', size: 1},
{text: 'meal', size: 1},
{text: 'mealtime', size: 1},
{text: 'meanwhile', size: 1},
{text: 'medical', size: 1},
{text: 'member', size: 1},
{text: 'memoir', size: 1},
{text: 'mercy', size: 1},
{text: 'merit', size: 1},
{text: 'miserable', size: 1},
{text: 'misty', size: 1},
{text: 'mix', size: 1},
{text: 'mixing', size: 1},
{text: 'mollify', size: 1},
{text: 'morrow', size: 1},
{text: 'mortality', size: 1},
{text: 'mortar', size: 1},
{text: 'narrative', size: 1},
{text: 'naturally', size: 1},
{text: 'neat', size: 1},
{text: 'necessity', size: 1},
{text: 'neglect', size: 1},
{text: 'neighbor', size: 1},
{text: 'nobleman', size: 1},
{text: 'noticed', size: 1},
{text: 'notion', size: 1},
{text: 'nourishment', size: 1},
{text: 'novel', size: 1},
{text: 'nudge', size: 1},
{text: "o'clock", size: 1},
{text: 'oatmeal', size: 1},
{text: 'oblige', size: 1},
{text: 'obliged', size: 1},
{text: 'observe', size: 1},
{text: 'occasionally', size: 1},
{text: 'occasions', size: 1},
{text: 'occur', size: 1},
{text: 'occurrence', size: 1},
{text: 'offend', size: 1},
{text: 'offended', size: 1},
{text: 'offender', size: 1},
{text: 'offering', size: 1},
{text: 'officiously', size: 1},
{text: 'once again', size: 1},
{text: 'onion', size: 1},
{text: 'oratorical', size: 1},
{text: 'originally', size: 1},
{text: 'ounce', size: 1},
{text: 'outer', size: 1},
{text: 'overload', size: 1},
{text: 'overlook', size: 1},
{text: 'overlooked', size: 1},
{text: 'page', size: 1},
{text: 'palm', size: 1},
{text: 'paralyse', size: 1},
{text: 'pardon', size: 1},
{text: 'parental', size: 1},
{text: 'parishioner', size: 1},
{text: 'parlour', size: 1},
{text: 'parochial', size: 1},
{text: 'participate', size: 1},
{text: 'participating', size: 1},
{text: 'passionately', size: 1},
{text: 'paste', size: 1},
{text: 'pasted', size: 1},
{text: 'patchwork', size: 1},
{text: 'patient', size: 1},
{text: 'pause', size: 1},
{text: 'per diem', size: 1},
{text: 'perception', size: 1},
{text: 'perform', size: 1},
{text: 'periodical', size: 1},
{text: 'periodically', size: 1},
{text: 'perspective', size: 1},
{text: 'perspiration', size: 1},
{text: 'persuasively', size: 1},
{text: 'perversely', size: 1},
{text: 'philosophical', size: 1},
{text: 'philosophy', size: 1},
{text: 'pick up', size: 1},
{text: 'pilgrimage', size: 1},
{text: 'pinion', size: 1},
{text: 'pinioned', size: 1},
{text: 'pity', size: 1},
{text: 'placid', size: 1},
{text: 'plenty', size: 1},
{text: 'poise', size: 1},
{text: 'poised', size: 1},
{text: 'polish', size: 1},
{text: 'polished', size: 1},
{text: 'porringer', size: 1},
{text: 'portion', size: 1},
{text: 'possibility', size: 1},
{text: 'possibly', size: 1},
{text: 'prayer', size: 1},
{text: 'prefix', size: 1},
{text: 'presume', size: 1},
{text: 'pride', size: 1},
{text: 'profound', size: 1},
{text: 'proof', size: 1},
{text: 'prophetic', size: 1},
{text: 'prospect', size: 1},
{text: 'protect', size: 1},
{text: 'protecting', size: 1},
{text: 'prudent', size: 1},
{text: 'put on', size: 1},
{text: 'quantity', size: 1},
{text: 'quite a', size: 1},
{text: 'raising', size: 1},
{text: 'range', size: 1},
{text: 'rare', size: 1},
{text: 'reader', size: 1},
{text: 'readiness', size: 1},
{text: 'reasonably', size: 1},
{text: 'rebel', size: 1},
{text: 'rebelliously', size: 1},
{text: 'recent', size: 1},
{text: 'reckless', size: 1},
{text: 'recollection', size: 1},
{text: 'red-faced', size: 1},
{text: 'reference', size: 1},
{text: 'reflection', size: 1},
{text: 'refrain', size: 1},
{text: 'refusal', size: 1},
{text: 'regret', size: 1},
{text: 'regular', size: 1},
{text: 'regulation', size: 1},
{text: 'rejoice', size: 1},
{text: 'rejoicing', size: 1},
{text: 'relax', size: 1},
{text: 'relaxed', size: 1},
{text: 'remonstrance', size: 1},
{text: 'reported', size: 1},
{text: 'resolve', size: 1},
{text: 'resolved', size: 1},
{text: 'respectful', size: 1},
{text: 'respiration', size: 1},
{text: 'respond', size: 1},
{text: 'right hand', size: 1},
{text: 'ring', size: 1},
{text: 'robe', size: 1},
{text: 'rolled', size: 1},
{text: 'rough', size: 1},
{text: 'rub', size: 1},
{text: 'run out', size: 1},
{text: 'rush', size: 1},
{text: 'rushed', size: 1},
{text: 'rustle', size: 1},
{text: 'sage', size: 1},
{text: 'salutation', size: 1},
{text: 'satisfaction', size: 1},
{text: 'scald', size: 1},
{text: 'scarce', size: 1},
{text: 'scrub', size: 1},
{text: 'scrubbed', size: 1},
{text: 'seated', size: 1},
{text: 'select', size: 1},
{text: 'self', size: 1},
{text: 'sending', size: 1},
{text: 'sequel', size: 1},
{text: 'set down', size: 1},
{text: 'set up', size: 1},
{text: 'setting', size: 1},
{text: 'settlement', size: 1},
{text: 'shine', size: 1},
{text: 'shoe', size: 1},
{text: 'shoes', size: 1},
{text: 'shook', size: 1},
{text: 'shop', size: 1},
{text: 'shriek', size: 1},
{text: 'shrieked', size: 1},
{text: 'shrunken', size: 1},
{text: 'shudder', size: 1},
{text: 'sicken', size: 1},
{text: 'signature', size: 1},
{text: 'sink', size: 1},
{text: 'sit down', size: 1},
{text: 'sit in', size: 1},
{text: 'sleep in', size: 1},
{text: 'sleeping', size: 1},
{text: 'slow', size: 1},
{text: 'smother', size: 1},
{text: 'smothered', size: 1},
{text: 'snappish', size: 1},
{text: 'sneeze', size: 1},
{text: 'sob', size: 1},
{text: 'soften', size: 1},
{text: 'softened', size: 1},
{text: 'solemn', size: 1},
{text: 'sorrow', size: 1},
{text: 'spare', size: 1},
{text: 'specimen', size: 1},
{text: 'speedily', size: 1},
{text: 'spirited', size: 1},
{text: 'spirits', size: 1},
{text: 'splash', size: 1},
{text: 'spoken', size: 1},
{text: 'stammer', size: 1},
{text: 'stand in', size: 1},
{text: 'stare', size: 1},
{text: 'staring', size: 1},
{text: 'start up', size: 1},
{text: 'startle', size: 1},
{text: 'startled', size: 1},
{text: 'starvation', size: 1},
{text: 'stature', size: 1},
{text: 'stipend', size: 1},
{text: 'stipendiary', size: 1},
{text: 'stir', size: 1},
{text: 'stirred', size: 1},
{text: 'stomach', size: 1},
{text: 'stone', size: 1},
{text: 'stoop', size: 1},
{text: 'stoop to', size: 1},
{text: 'stooped', size: 1},
{text: 'straw', size: 1},
{text: 'stray', size: 1},
{text: 'stretch', size: 1},
{text: 'stretch out', size: 1},
{text: 'stretched', size: 1},
{text: 'stride', size: 1},
{text: 'strive', size: 1},
{text: 'striving', size: 1},
{text: 'struggle', size: 1},
{text: 'stupefied', size: 1},
{text: 'stupefy', size: 1},
{text: 'sturdy', size: 1},
{text: 'suck', size: 1},
{text: 'sucking', size: 1},
{text: 'sugar', size: 1},
{text: 'suit', size: 1},
{text: 'summon', size: 1},
{text: 'superintendence', size: 1},
{text: 'superlative', size: 1},
{text: 'surly', size: 1},
{text: 'surround', size: 1},
{text: 'surrounded', size: 1},
{text: 'survive', size: 1},
{text: 'swallow', size: 1},
{text: 'swear', size: 1},
{text: 'sweetness', size: 1},
{text: 'systematic', size: 1},
{text: 'take down', size: 1},
{text: 'take in', size: 1},
{text: 'take on', size: 1},
{text: 'take out', size: 1},
{text: 'take place', size: 1},
{text: 'take up', size: 1},
{text: 'talk about', size: 1},
{text: 'talk of', size: 1},
{text: 'tall', size: 1},
{text: 'taste', size: 1},
{text: 'tasting', size: 1},
{text: 'tavern', size: 1},
{text: 'tea', size: 1},
{text: 'tear into', size: 1},
{text: 'temerity', size: 1},
{text: 'temple', size: 1},
{text: 'temporary', size: 1},
{text: 'termination', size: 1},
{text: 'testimony', size: 1},
{text: 'thanks', size: 1},
{text: 'the Street', size: 1},
{text: 'theory', size: 1},
{text: 'thereby', size: 1},
{text: 'thereon', size: 1},
{text: 'theretofore', size: 1},
{text: 'thingummy', size: 1},
{text: 'think about', size: 1},
{text: 'thirteen', size: 1},
{text: 'thirty', size: 1},
{text: 'thrash', size: 1},
{text: 'thrashing', size: 1},
{text: 'thrust', size: 1},
{text: 'thrusting', size: 1},
{text: 'ticket', size: 1},
{text: 'to be sure', size: 1},
{text: 'to wit', size: 1},
{text: 'torture', size: 1},
{text: 'treachery', size: 1},
{text: 'tremble', size: 1},
{text: 'tremendous', size: 1},
{text: 'trot', size: 1},
{text: 'turn up', size: 1},
{text: 'twice', size: 1},
{text: 'uncomfortable', size: 1},
{text: 'unconsciously', size: 1},
{text: 'unconsciousness', size: 1},
{text: 'undertake', size: 1},
{text: 'undertaker', size: 1},
{text: 'undo', size: 1},
{text: 'unequally', size: 1},
{text: 'unexpectedly', size: 1},
{text: 'unfortunately', size: 1},
{text: 'uniform', size: 1},
{text: 'unlimited', size: 1},
{text: 'unquestionably', size: 1},
{text: 'unwonted', size: 1},
{text: 'upstairs', size: 1},
{text: 'upward', size: 1},
{text: 'usage', size: 1},
{text: 'venture', size: 1},
{text: 'victim', size: 1},
{text: 'vindicate', size: 1},
{text: 'vindicated', size: 1},
{text: 'violent', size: 1},
{text: 'voracious', size: 1},
{text: 'wake', size: 1},
{text: 'walk away', size: 1},
{text: 'ward', size: 1},
{text: 'washed', size: 1},
{text: 'waste', size: 1},
{text: 'wasted', size: 1},
{text: 'wave', size: 1},
{text: 'waving', size: 1},
{text: 'weak', size: 1},
{text: 'weakly', size: 1},
{text: 'wed', size: 1},
{text: 'wedding', size: 1},
{text: 'weekly', size: 1},
{text: 'weep', size: 1},
{text: 'weeping', size: 1},
{text: 'whisper', size: 1},
{text: 'whispered', size: 1},
{text: 'wildly', size: 1},
{text: 'wink', size: 1},
{text: 'wink at', size: 1},
{text: 'wipe', size: 1},
{text: 'wise', size: 1},
{text: 'wit', size: 1},
{text: 'worn', size: 1},
{text: 'wrap', size: 1},
{text: 'wrapped', size: 1},
{text: 'yellow', size: 1},
{text: 'Young', size: 1}
];
|
wvengen/d3-wordcloud
|
example/example.words.js
|
JavaScript
|
mit
| 34,916
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="./../../helpwin.css">
<title>MATLAB File Help: prtPreProcPca/isCrossValidateValid</title>
</head>
<body>
<!--Single-page help-->
<table border="0" cellspacing="0" width="100%">
<tr class="subheader">
<td class="headertitle">MATLAB File Help: prtPreProcPca/isCrossValidateValid</td>
</tr>
</table>
<div class="title">prtPreProcPca/isCrossValidateValid</div>
<div class="helptext"><pre><!--helptext --> <span class="helptopic">isCrossValidateValid</span> - True
Help for <span class="helptopic">prtPreProcPca/isCrossValidateValid</span> is inherited from superclass <a href="./../prtPreProc.html">prtPreProc</a></pre></div><!--after help -->
<!--Property-->
<div class="sectiontitle">Property Details</div>
<table class="class-details">
<tr>
<td class="class-detail-label">Constant</td>
<td>false</td>
</tr>
<tr>
<td class="class-detail-label">Dependent</td>
<td>false</td>
</tr>
<tr>
<td class="class-detail-label">Sealed</td>
<td>false</td>
</tr>
<tr>
<td class="class-detail-label">Transient</td>
<td>false</td>
</tr>
<tr>
<td class="class-detail-label">GetAccess</td>
<td>public</td>
</tr>
<tr>
<td class="class-detail-label">SetAccess</td>
<td>protected</td>
</tr>
<tr>
<td class="class-detail-label">GetObservable</td>
<td>false</td>
</tr>
<tr>
<td class="class-detail-label">SetObservable</td>
<td>false</td>
</tr>
</table>
</body>
</html>
|
jpalves/PRT
|
doc/functionReference/prtPreProcPca/isCrossValidateValid.html
|
HTML
|
mit
| 1,937
|
<!DOCTYPE html>
<html>
<head>
<title>label examples</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="description" content="An example of drawing shapes with labels">
<meta name="author" content="Ryan Westphal">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/blitzer/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<style type="text/css">
#map
{
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
</style>
</head>
<body>
<div>
<div id="map">
</div>
<div class="info">
<div class="links">
<a href="../" class="docLink">< docs</a>
<a href="http://jsfiddle.net/ryanttb/2TAzc/embedded/" class="fiddleLink not-mobile"><img src="img/jsfiddle.png" alt="" /> jsFiddle ></a>
</div>
<h1>label</h1>
<p class="not-mobile">This example builds on the drawing example by appending a label with shapes. Enter label text (HTML is ok), choose a tool below, and start labelling!</p>
<input type="text" name="label" value="a label" autofocus />
<div id="modes">
<input type="radio" id="drawPoint" name="mode" value="drawPoint" checked="checked" /><label for="drawPoint">point</label>
<input type="radio" id="drawLineString" name="mode" value="drawLineString" /><label for="drawLineString">line</label>
<input type="radio" id="drawPolygon" name="mode" value="drawPolygon" /><label for="drawPolygon">polygon</label>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
<script src="../jquery.geo-test.min.js"></script>
<script>
$(function () {
// create a map, setting mode to drawPoint initially
var map = $("#map").geomap({
center: [-71.0595678, 42.3604823],
zoom: 8,
mode: "drawPoint",
shape: function (e, geo) {
// the shape event triggers when a user draws a shape
// the geo object is a simple GeoJSON object: Point, LineString or Polygon
// we can append it directly to the map
// grab the text of the label input and send it as a label for this shape
map.geomap("append", geo, $("input[name='label']").val());
}
});
// jQuery UI for pretty buttons
$("#modes").buttonset();
$("#modes input").click(function () {
// set the map's mode option based on value of the input clicked
// this will change the map's mode to drawPoint, drawLineString or drawPolygon
map.geomap("option", "mode", $(this).val());
});
});
</script>
<script>
var _gaq = [['_setAccount', 'UA-26084853-1'], ['_trackPageview']];
(function (d, t) {
var g = d.createElement(t), s = d.getElementsByTagName(t)[0]; g.async = 1;
g.src = ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js';
s.parentNode.insertBefore(g, s);
} (document, 'script'));
</script>
</body>
</html>
|
bertomartin/geo
|
docs/examples/label.html
|
HTML
|
mit
| 3,269
|
<html lang="en">
<head>
<title>Copying - Using the GNU Compiler Collection (GCC)</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using the GNU Compiler Collection (GCC)">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="prev" href="GNU-Project.html#GNU-Project" title="GNU Project">
<link rel="next" href="GNU-Free-Documentation-License.html#GNU-Free-Documentation-License" title="GNU Free Documentation License">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997,
1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
2010 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being ``Funding Free Software'', the Front-Cover
Texts being (a) (see below), and with the Back-Cover Texts being (b)
(see below). A copy of the license is included in the section entitled
``GNU Free Documentation License''.
(a) The FSF's Front-Cover Text is:
A GNU Manual
(b) The FSF's Back-Cover Text is:
You have freedom to copy and modify this GNU Manual, like GNU
software. Copies published by the Free Software Foundation raise
funds for GNU development.-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="Copying"></a>
Next: <a rel="next" accesskey="n" href="GNU-Free-Documentation-License.html#GNU-Free-Documentation-License">GNU Free Documentation License</a>,
Previous: <a rel="previous" accesskey="p" href="GNU-Project.html#GNU-Project">GNU Project</a>,
Up: <a rel="up" accesskey="u" href="index.html#Top">Top</a>
<hr>
</div>
<!-- man begin DESCRIPTION -->
<h2 class="unnumbered">GNU General Public License</h2>
<div align="center">Version 3, 29 June 2007</div>
<!-- This file is intended to be included in another file. -->
<pre class="display"> Copyright © 2007 Free Software Foundation, Inc. <a href="http://fsf.org/">http://fsf.org/</a>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
</pre>
<h3 class="heading">Preamble</h3>
<p>The GNU General Public License is a free, copyleft license for
software and other kinds of works.
<p>The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom
to share and change all versions of a program–to make sure it remains
free software for all its users. We, the Free Software Foundation,
use the GNU General Public License for most of our software; it
applies also to any other work released this way by its authors. You
can apply it to your programs, too.
<p>When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
<p>To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you
have certain responsibilities if you distribute copies of the
software, or if you modify it: responsibilities to respect the freedom
of others.
<p>For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too,
receive or can get the source code. And you must show them these
terms so they know their rights.
<p>Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
<p>For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
<p>Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the
manufacturer can do so. This is fundamentally incompatible with the
aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for
individuals to use, which is precisely where it is most unacceptable.
Therefore, we have designed this version of the GPL to prohibit the
practice for those products. If such problems arise substantially in
other domains, we stand ready to extend this provision to those
domains in future versions of the GPL, as needed to protect the
freedom of users.
<p>Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish
to avoid the special danger that patents applied to a free program
could make it effectively proprietary. To prevent this, the GPL
assures that patents cannot be used to render the program non-free.
<p>The precise terms and conditions for copying, distribution and
modification follow.
<h3 class="heading">TERMS AND CONDITIONS</h3>
<ol type=1 start=0>
<li>Definitions.
<p>“This License” refers to version 3 of the GNU General Public License.
<p>“Copyright” also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.
<p>“The Program” refers to any copyrightable work licensed under this
License. Each licensee is addressed as “you”. “Licensees” and
“recipients” may be individuals or organizations.
<p>To “modify” a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a “modified version” of
the earlier work or a work “based on” the earlier work.
<p>A “covered work” means either the unmodified Program or a work based
on the Program.
<p>To “propagate” a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
<p>To “convey” a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.
<p>An interactive user interface displays “Appropriate Legal Notices” to
the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
<li>Source Code.
<p>The “source code” for a work means the preferred form of the work for
making modifications to it. “Object code” means any non-source form
of a work.
<p>A “Standard Interface” means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
<p>The “System Libraries” of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
“Major Component”, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
<p>The “Corresponding Source” for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
<p>The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.
<p>The Corresponding Source for a work in source code form is that same
work.
<li>Basic Permissions.
<p>All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
<p>You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.
<p>Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
<li>Protecting Users' Legal Rights From Anti-Circumvention Law.
<p>No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
<p>When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.
<li>Conveying Verbatim Copies.
<p>You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
<p>You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
<li>Conveying Modified Source Versions.
<p>You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
<ol type=a start=1>
<li>The work must carry prominent notices stating that you modified it,
and giving a relevant date.
<li>The work must carry prominent notices stating that it is released
under this License and any conditions added under section 7. This
requirement modifies the requirement in section 4 to “keep intact all
notices”.
<li>You must license the entire work, as a whole, under this License to
anyone who comes into possession of a copy. This License will
therefore apply, along with any applicable section 7 additional terms,
to the whole of the work, and all its parts, regardless of how they
are packaged. This License gives no permission to license the work in
any other way, but it does not invalidate such permission if you have
separately received it.
<li>If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your work
need not make them do so.
</ol>
<p>A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
“aggregate” if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
<li>Conveying Non-Source Forms.
<p>You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:
<ol type=a start=1>
<li>Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium customarily
used for software interchange.
<li>Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a written
offer, valid for at least three years and valid for as long as you
offer spare parts or customer support for that product model, to give
anyone who possesses the object code either (1) a copy of the
Corresponding Source for all the software in the product that is
covered by this License, on a durable physical medium customarily used
for software interchange, for a price no more than your reasonable
cost of physically performing this conveying of source, or (2) access
to copy the Corresponding Source from a network server at no charge.
<li>Convey individual copies of the object code with a copy of the written
offer to provide the Corresponding Source. This alternative is
allowed only occasionally and noncommercially, and only if you
received the object code with such an offer, in accord with subsection
6b.
<li>Convey the object code by offering access from a designated place
(gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to copy
the object code is a network server, the Corresponding Source may be
on a different server (operated by you or a third party) that supports
equivalent copying facilities, provided you maintain clear directions
next to the object code saying where to find the Corresponding Source.
Regardless of what server hosts the Corresponding Source, you remain
obligated to ensure that it is available for as long as needed to
satisfy these requirements.
<li>Convey the object code using peer-to-peer transmission, provided you
inform other peers where the object code and Corresponding Source of
the work are being offered to the general public at no charge under
subsection 6d.
</ol>
<p>A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
<p>A “User Product” is either (1) a “consumer product”, which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
“normally used” refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
<p>“Installation Information” for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
<p>If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
<p>The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
<p>Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
<li>Additional Terms.
<p>“Additional permissions” are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
<p>When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
<p>Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
<ol type=a start=1>
<li>Disclaiming warranty or limiting liability differently from the terms
of sections 15 and 16 of this License; or
<li>Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices
displayed by works containing it; or
<li>Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
<li>Limiting the use for publicity purposes of names of licensors or
authors of the material; or
<li>Declining to grant rights under trademark law for use of some trade
names, trademarks, or service marks; or
<li>Requiring indemnification of licensors and authors of that material by
anyone who conveys the material (or modified versions of it) with
contractual assumptions of liability to the recipient, for any
liability that these contractual assumptions directly impose on those
licensors and authors.
</ol>
<p>All other non-permissive additional terms are considered “further
restrictions” within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
<p>If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
<p>Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
<li>Termination.
<p>You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
<p>However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.
<p>Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
<p>Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
<li>Acceptance Not Required for Having Copies.
<p>You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
<li>Automatic Licensing of Downstream Recipients.
<p>Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
<p>An “entity transaction” is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
<p>You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
<li>Patents.
<p>A “contributor” is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's “contributor version”.
<p>A contributor's “essential patent claims” are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, “control” includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
<p>In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To “grant” such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
<p>If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. “Knowingly relying” means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
<p>If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
<p>A patent license is “discriminatory” if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.
<p>Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
<li>No Surrender of Others' Freedom.
<p>If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey
a covered work so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree
to terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
<li>Use with the GNU Affero General Public License.
<p>Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
<li>Revised Versions of this License.
<p>The Free Software Foundation may publish revised and/or new versions
of the GNU General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
<p>Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU General Public
License “or any later version” applies to it, you have the option of
following the terms and conditions either of that numbered version or
of any later version published by the Free Software Foundation. If
the Program does not specify a version number of the GNU General
Public License, you may choose any version ever published by the Free
Software Foundation.
<p>If the Program specifies that a proxy can decide which future versions
of the GNU General Public License can be used, that proxy's public
statement of acceptance of a version permanently authorizes you to
choose that version for the Program.
<p>Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
<li>Disclaimer of Warranty.
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
<li>Limitation of Liability.
<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
<li>Interpretation of Sections 15 and 16.
<p>If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
</ol>
<h3 class="heading">END OF TERMS AND CONDITIONS</h3>
<h3 class="heading">How to Apply These Terms to Your New Programs</h3>
<p>If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
<p>To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the “copyright” line and a pointer to where the full notice is found.
<pre class="smallexample"> <var>one line to give the program's name and a brief idea of what it does.</var>
Copyright (C) <var>year</var> <var>name of author</var>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>.
</pre>
<p>Also add information on how to contact you by electronic and paper mail.
<p>If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<pre class="smallexample"> <var>program</var> Copyright (C) <var>year</var> <var>name of author</var>
This program comes with ABSOLUTELY NO WARRANTY; for details type ‘<samp><span class="samp">show w</span></samp>’.
This is free software, and you are welcome to redistribute it
under certain conditions; type ‘<samp><span class="samp">show c</span></samp>’ for details.
</pre>
<p>The hypothetical commands ‘<samp><span class="samp">show w</span></samp>’ and ‘<samp><span class="samp">show c</span></samp>’ should show
the appropriate parts of the General Public License. Of course, your
program's commands might be different; for a GUI interface, you would
use an “about box”.
<p>You should also get your employer (if you work as a programmer) or school,
if any, to sign a “copyright disclaimer” for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>.
<p>The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use
the GNU Lesser General Public License instead of this License. But
first, please read <a href="http://www.gnu.org/philosophy/why-not-lgpl.html">http://www.gnu.org/philosophy/why-not-lgpl.html</a>.
<!-- man end -->
<!-- -->
<!-- GFDL -->
<!-- -->
<!-- Special handling for inclusion in the install manual. -->
<!-- man begin DESCRIPTION -->
</body></html>
|
sahdman/rpi_android_kernel
|
toolchain/gcc-arm-none-eabi-4_6-2012q2/share/doc/html/gcc/Copying.html
|
HTML
|
mit
| 39,442
|
'use strict';
const cleanup = require('rollup-plugin-cleanup');
const common = require('rollup-plugin-commonjs');
const node = require('rollup-plugin-node-resolve');
const path = require('path');
const pkg = require('../package.json');
const rollup = require('rollup').rollup;
/**
* Wrap a bundled dependency for consumption by the Compiler.
* @param {Object} ext Details from the `ext` object in package.json.
* @return {Object} A rollup plugin.
*/
function wrap(ext) {
return {
name: 'googup',
transformBundle: function(source) {
let name = `ol.ext.${ext.name || ext.module}`;
let postamble = '';
if (ext.import) {
name += '.' + ext.import;
} else {
postamble = `${name} = ${name}.default;\n`;
}
return `
/**
* @fileoverview
* @suppress {accessControls, ambiguousFunctionDecl, checkDebuggerStatement, checkRegExp, checkTypes, checkVars, const, constantProperty, deprecated, duplicate, es5Strict, fileoverviewTags, missingProperties, nonStandardJsDocs, strictModuleDepCheck, suspiciousCode, undefinedNames, undefinedVars, unknownDefines, unusedLocalVariables, uselessCode, visibility}
*/
goog.provide('${name}');
/** @typedef {function(*)} */
${name} = function() {};
(function() {${source}}).call(ol.ext);
${postamble}`;
}
};
}
/**
* Build all external modules.
* @return {Promise} Resolves on successful completion.
*/
function main() {
return Promise.all(pkg.ext.map(ext => {
const moduleName = ext.name || ext.module;
const options = {
extend: true,
entry: require.resolve(ext.module),
dest: `${path.join(__dirname, '..', 'build', 'ol.ext', moduleName.toLowerCase())}.js`,
format: 'iife',
moduleName: moduleName,
exports: 'named',
plugins: [
node(),
common(),
cleanup(),
wrap(ext)
]
};
return rollup(options).then(bundle => bundle.write(options));
}));
}
if (require.main === module) {
main().catch(err => {
process.stderr.write(`${err.message}\n`, () => process.exit(1));
});
}
module.exports = main;
|
gistnu/tru-workshop
|
bower_components/openlayers/tasks/build-ext.js
|
JavaScript
|
mit
| 2,100
|
# Lotus
A complete web framework for Ruby
## v0.3.0 - 2015-03-23
### Added
- [Luca Guidi] Introduced action generator. Eg. `bundle exec lotus generate action web dashboard#index`
- [Alfonso Uceda Pompa] Allow to specify default coookies options in application configuration. Eg. `cookies true, { domain: 'lotusrb.org' }`
- [Tom Kadwill] Include `Lotus::Helpers` in views.
- [Linus Pettersson] Allow to specify `--database` CLI option when generate a new application. Eg. `lotus new bookshelf --database=postgresql`
- [Linus Pettersson] Initialize a Git repository when generating a new application
- [Alfonso Uceda Pompa] Produce `.lotusrc` when generating a new application
- [Alfonso Uceda Pompa] Security HTTP headers. `X-Frame-Options` and `Content-Security-Policy` are now enabled by default.
- [Linus Pettersson] Database console. Run with `bundle exec lotus db console`
- [Luca Guidi] Dynamic finders for relative and absolute routes. It implements method missing: `Web::Routes.home_path` will resolve to `Web::Routes.path(:home)`.
### Changed
– [Alfonso Uceda Pompa] Cookies will send `HttpOnly` by default. This is for security reasons.
- [Jan Lelis] Enable `templates` configuration for new generated apps
- [Mark Connell] Change SQLite file extension from `.db` to `.sqlite3`
## v0.2.1 - 2015-02-06
### Added
- [Huy Đỗ] Introduced `Lotus::Logger`
- [Jimmy Zhang] `lotus new` accepts a `--path` argument
- [Jimmy Zhang] Application generator for the current directory (`lotus new .`). This is useful to provide a web deliverable for existing Ruby gems.
- [Trung Lê] Add example mapping file for application generator: `lib/config/mapping.rb`
- [Hiếu Nguyễn] RSpec support for application generator: `--test=rspec` or `--test=minitest` (default)
### Fixed
- [Luca Guidi] `lotus version` to previx `v` (eg `v0.2.1`)
- [Rob Yurkowski] Ensure application name doesn't contain special or forbidden characters
- [Luca Guidi] Ensure all the applications are loaded in console
- [Trung Lê] Container architecture: preload only `lib/<appname>/**/*.rb`
- [Hiếu Nguyễn] Fixed `lotus new` to print usage when application name isn't provided
## v0.2.0 - 2014-06-23
### Added
- [Luca Guidi] Introduced `lotus new` as a command to generate applications. It supports "container" architecture for now.
- [Luca Guidi] Show a welcome page when the application doesn't have routes
- [Luca Guidi] Introduced `Lotus::Application.preload!` to preload all the Lotus applications in a given Ruby process. (Bulk `Lotus::Application.load!`)
- [Trung Lê] Allow browsers to fake non `GET`/`POST` requests via `Rack::MethodOverride`
- [Josue Abreu] Allow to define body parses for non `GET` HTTP requests (`body_parsers` configuration)
- [Alfonso Uceda Pompa] Allow to toggle static assets serving (`serve_assets` configuration)
- [Alfonso Uceda Pompa] Allow to serve assets from multiple sources (`assets` configuration)
- [Luca Guidi] Allow to configure `ENV` vars with per environment `.env` files
- [Alfonso Uceda Pompa] Introduced `lotus routes` command
- [Luca Guidi] Allow to configure low level settings for MVC frameworks (`model`, `view` and `controller` configuration)
- [Luca Guidi] Introduced `Lotus::Container`
- [Trung Lê] Include `Lotus::Presenter` as part of the duplicated modules
- [Trung Lê] Include `Lotus::Entity` and `Lotus::Repository` as part of the duplicated modules
- [Luca Guidi] Introduced code reloading for `lotus server`
- [Trung Lê] Allow to configure database adapter (`adapter` configuration)
- [Luca Guidi & Trung Lê] Allow to configure database mapping (`mapping` configuration)
- [Piotr Kurek] Introduced custom templates for non successful responses
- [Luca Guidi] Allow to configure exceptions handling (`handle_exceptions` configuration)
- [Michal Muskala] Allow to configure sessions (`sessions` configuration)
- [Josue Abreu] Allow to configure cookies (`cookies` configuration)
- [Piotr Kurek] Allow to yield multiple configurations per application, according to the current environment
- [David Celis] Allow to configure Rack middleware stack (`middleware` configuration)
- [David Celis] Introduced `lotus console` command. It runs the REPL configured in `Gemfile` (eg. pry or ripl). Defaults to IRb.
- [Luca Guidi] Introduced `Lotus::Environment` which holds the informations about the current environment, and CLI arguments
- [Luca Guidi] Introduced `Lotus::Application.load!` to load and configure an application without requiring user defined code (controllers, views, etc.)
- [Leonard Garvey] Introduced `lotus server` command. It runs the application with the Rack server declared in `Gemfile` (eg. puma, thin, unicorn). It defaults to `WEBRick`.
- [Luca Guidi] Official support for MRI 2.1 and 2.2
### Changed
- [Alfonso Uceda Pompa] Changed semantic of `assets` configuration. Now it's only used to set the sources for the assets. Static serving assets has now a new configuration: `serve_assets`.
### Fixed
- [Luca Guidi] Ensure `HEAD` requests return empty body
## v0.1.0 - 2014-06-23
### Added
- [Luca Guidi] Allow to run multiple Lotus applications in the same Ruby process (framework duplication)
- [Luca Guidi] Introduced `Lotus::Routes` as factory to generate application URLs
- [Luca Guidi] Allow to configure scheme, host and port (`scheme`, `host` and `port` configuration)
- [Luca Guidi] Allow to configure a layout to use for all the views of an application (`layout` configuration)
- [Luca Guidi] Allow to configure routes (`routes` configuration)
- [Luca Guidi] Allow to configure several load paths for Ruby source files (`load_paths` configuration)
- [Luca Guidi] Allow to serve static files (`assets` configuration)
- [Luca Guidi] Render default pages for non successful responses (eg `404` or `500`)
- [Luca Guidi] Allow to configure the root of an application (`root` configuration)
- [Luca Guidi] Introduced `Lotus::Configuration`
- [Luca Guidi] Introduced `Lotus::Application`
- [Luca Guidi] Official support for MRI 2.0
|
nguyenngoc2505/lotus
|
CHANGELOG.md
|
Markdown
|
mit
| 6,004
|
#!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test NULLDUMMY softfork.
Connect to a single node.
Generate 2 blocks (save the coinbases for later).
Generate 427 more blocks.
[Policy/Consensus] Check that NULLDUMMY compliant transactions are accepted in the 430th block.
[Policy] Check that non-NULLDUMMY transactions are rejected before activation.
[Consensus] Check that the new NULLDUMMY rules are not enforced on the 431st block.
[Policy/Consensus] Check that the new NULLDUMMY rules are enforced on the 432nd block.
"""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block, add_witness_commitment
from test_framework.script import CScript
from io import BytesIO
import time
NULLDUMMY_ERROR = "64: non-mandatory-script-verify-flag (Dummy CHECKMULTISIG argument must be zero)"
def trueDummy(tx):
scriptSig = CScript(tx.vin[0].scriptSig)
newscript = []
for i in scriptSig:
if (len(newscript) == 0):
assert(len(i) == 0)
newscript.append(b'\x51')
else:
newscript.append(i)
tx.vin[0].scriptSig = CScript(newscript)
tx.rehash()
class NULLDUMMYTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 1
self.setup_clean_chain = True
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir,
extra_args=[['-whitelist=127.0.0.1', '-walletprematurewitness']])
def run_test(self):
self.address = self.nodes[0].getnewaddress()
self.ms_address = self.nodes[0].addmultisigaddress(1,[self.address])
self.wit_address = self.nodes[0].addwitnessaddress(self.address)
self.wit_ms_address = self.nodes[0].addwitnessaddress(self.ms_address)
NetworkThread().start() # Start up network handling in another thread
self.coinbase_blocks = self.nodes[0].generate(2) # Block 2
coinbase_txid = []
for i in self.coinbase_blocks:
coinbase_txid.append(self.nodes[0].getblock(i)['tx'][0])
self.nodes[0].generate(427) # Block 429
self.lastblockhash = self.nodes[0].getbestblockhash()
self.tip = int("0x" + self.lastblockhash, 0)
self.lastblockheight = 429
self.lastblocktime = int(time.time()) + 429
self.log.info("Test 1: NULLDUMMY compliant base transactions should be accepted to mempool and mined before activation [430]")
test1txs = [self.create_transaction(self.nodes[0], coinbase_txid[0], self.ms_address, 49)]
txid1 = self.nodes[0].sendrawtransaction(bytes_to_hex_str(test1txs[0].serialize_with_witness()), True)
test1txs.append(self.create_transaction(self.nodes[0], txid1, self.ms_address, 48))
txid2 = self.nodes[0].sendrawtransaction(bytes_to_hex_str(test1txs[1].serialize_with_witness()), True)
test1txs.append(self.create_transaction(self.nodes[0], coinbase_txid[1], self.wit_ms_address, 49))
txid3 = self.nodes[0].sendrawtransaction(bytes_to_hex_str(test1txs[2].serialize_with_witness()), True)
self.block_submit(self.nodes[0], test1txs, False, True)
self.log.info("Test 2: Non-NULLDUMMY base multisig transaction should not be accepted to mempool before activation")
test2tx = self.create_transaction(self.nodes[0], txid2, self.ms_address, 47)
trueDummy(test2tx)
assert_raises_jsonrpc(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test2tx.serialize_with_witness()), True)
self.log.info("Test 3: Non-NULLDUMMY base transactions should be accepted in a block before activation [431]")
self.block_submit(self.nodes[0], [test2tx], False, True)
self.log.info ("Test 4: Non-NULLDUMMY base multisig transaction is invalid after activation")
test4tx = self.create_transaction(self.nodes[0], test2tx.hash, self.address, 46)
test6txs=[CTransaction(test4tx)]
trueDummy(test4tx)
assert_raises_jsonrpc(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test4tx.serialize_with_witness()), True)
self.block_submit(self.nodes[0], [test4tx])
print ("Test 5: Non-NULLDUMMY P2WSH multisig transaction invalid after activation")
test5tx = self.create_transaction(self.nodes[0], txid3, self.wit_address, 48)
test6txs.append(CTransaction(test5tx))
test5tx.wit.vtxinwit[0].scriptWitness.stack[0] = b'\x01'
assert_raises_jsonrpc(-26, NULLDUMMY_ERROR, self.nodes[0].sendrawtransaction, bytes_to_hex_str(test5tx.serialize_with_witness()), True)
self.block_submit(self.nodes[0], [test5tx], True)
self.log.info("Test 6: NULLDUMMY compliant base/witness transactions should be accepted to mempool and in block after activation [432]")
for i in test6txs:
self.nodes[0].sendrawtransaction(bytes_to_hex_str(i.serialize_with_witness()), True)
self.block_submit(self.nodes[0], test6txs, True, True)
def create_transaction(self, node, txid, to_address, amount):
inputs = [{ "txid" : txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = BytesIO(hex_str_to_bytes(signresult['hex']))
tx.deserialize(f)
return tx
def block_submit(self, node, txs, witness = False, accept = False):
block = create_block(self.tip, create_coinbase(self.lastblockheight + 1), self.lastblocktime + 1)
block.nVersion = 4
for tx in txs:
tx.rehash()
block.vtx.append(tx)
block.hashMerkleRoot = block.calc_merkle_root()
witness and add_witness_commitment(block)
block.rehash()
block.solve()
node.submitblock(bytes_to_hex_str(block.serialize(True)))
if (accept):
assert_equal(node.getbestblockhash(), block.hash)
self.tip = block.sha256
self.lastblockhash = block.hash
self.lastblocktime += 1
self.lastblockheight += 1
else:
assert_equal(node.getbestblockhash(), self.lastblockhash)
if __name__ == '__main__':
NULLDUMMYTest().main()
|
isle2983/bitcoin
|
qa/rpc-tests/nulldummy.py
|
Python
|
mit
| 6,648
|
@font-face {
font-family: 'shabnam';
src: url('../fonts/Shabnam.eot');
src: url('../fonts/Shabnam.eot?#iefix') format('embedded-opentype'),
url('../fonts/Shabnam.woff') format('woff'),
url('../fonts/Shabnam.ttf') format('truetype');
font-style: normal;
font-weight: normal;
}
@font-face {
font-family: 'shabnam';
src: url('../fonts/Shabnam-Bold.eot');
src: url('../fonts/Shabnam-Bold.eot?#iefix') format('embedded-opentype'),
url('../fonts/Shabnam-Bold.woff') format('woff'),
url('../fonts/Shabnam-Bold.ttf') format('truetype');
font-style: normal;
font-weight: bold;
}
html,
body {
margin: 0;
padding: 0;
position: relative;
}
body {
font-family: 'shabnam', serif;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-moz-font-feature-settings: "liga" on;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: 'shabnam', sans-serif;
color: #222;
}
a {
outline: none;
}
.wrapper {
overflow: hidden;
position: relative;
}
.header {
padding: 20px 0;
position: relative;
background: #f5f5f5;
border-bottom: 1px solid #eaeaea;
}
.nav {
max-width: 800px;
margin: 0 auto;
padding: 0 15px;
font-family: 'shabnam', sans-serif;
text-align: left;
}
.nav-logo {
float: right;
margin-top: -11px;
transition: transform 150ms ease-out;
}
.nav-logo:hover {
transform: scale(1.1);
}
.nav-logo img {
display: block;
max-height: 40px;
width: auto;
border-radius: 50%;
}
.nav-links {
margin: 0;
padding: 0;
font-size: 14px;
list-style: none;
}
.nav-links li {
display: inline-block;
margin: 0 0 0 15px;
}
.nav-links li:first-child {
margin-left: 0;
}
.nav-links a {
text-decoration: none;
color: #111;
}
.nav-links a:hover {
color: #000;
}
.content {
max-width: 700px;
margin: 60px auto 80px;
padding: 0 15px;
font-size: 16px;
line-height: 1.7;
color: #555;
}
.article-title {
font-size: 34px;
color: #222;
margin: 0;
line-height: 1.3;
}
.article-date {
color: #ccc;
}
.archive-content {
font-weight: normal;
margin: 30px 0;
color: #888;
}
.article-duration {
margin-top: 12px;
float: left;
font-size: 10px;
font-family: 'shabnam', sans-serif;
padding: 1px 5px;
font-weight: bold;
border-radius: 3px;
background: #bbb;
color: #fff
}
.article-content p {
margin: 5px 0 5px;
}
.article-content a {
text-decoration: none;
color: inherit;
border-bottom: 3px solid #CBF8DF;
box-shadow: inset 0 -4px 0 #CBF8DF;
background: transparent;
transition: background 150ms ease;
}
.article-content a:hover,
.article-content a:focus {
background: #CBF8DF;
}
.article-content hr {
width: 150px;
margin: 50px auto;
height: 1px;
overflow: hidden;
border: none;
background: #e5e5e5;
}
.highlight {
border-radius: 3px;
position: relative;
margin: 40px 0;
font-size: 14px;
}
.highlight pre {
padding: 10px;
}
.archive {
margin: 0;
padding: 0;
list-style: none;
line-height: 1.3em;
text-align: center;
color: #111;
}
.archive-title {
font-size: 32px;
margin-top: 60px;
}
.archive-item {
margin: 5px 0 15px;
padding: 0;
}
.archive-item-date {
color: #ccc;
font-size: 14px;
padding: 5px 0;
margin-top: 5px;
display: block;
}
.archive-item-link {
display: inline-block;
text-decoration: none;
font-size: 30px;
font-family: 'Lato', sans-serif;
font-weight: bold;
color: #222;
padding: 5px 0;
border-bottom: 1px solid #ddd;
}
.archive-item-link:hover {
border-bottom-color: #222;
}
.footer {
padding: 25px 0;
text-align: center;
font-family: 'shabnam', sans-serif;
}
.footer-links {
list-style: none;
margin: 0;
padding: 0;
color: #ccc;
font-size: 14px;
}
.footer-links li {
margin: 0;
padding: 0;
display: inline-block;
}
.footer-links a {
color: #888;
text-decoration: none;
transition: color 150ms ease;
margin: 0 15px;
}
.footer-links a:hover,
.footer-links a:focus {
color: #222;
}
.footer-links li::before {
content: '/';
position: relative;
left: -2px;
}
.footer-links li:first-child::before {
display: none;
}
.footer-links-kudos img {
position: relative;
top: 6px;
margin-left: 2px;
}
@media (min-width: 600px) {
.header {
padding: 25px 0;
}
.nav-logo {
margin-top: -13px;
}
.nav-logo img {
max-height: 50px;
}
.nav-links {
font-size: 18px;
}
.nav-links li {
margin: 0 30px 0 0;
}
.content {
font-size: 19px;
line-height: 1.8;
margin: 100px auto;
}
.highlight {
font-size: 16px;
margin: 40px -20px;
}
.archive {
text-align: right;
}
.archive-title {
font-size: 38px;
}
.archive-item-date {
font-size: 19px;
text-align: left;
float: left;
}
.article-title {
font-size: 42px;
}
.article-duration {
font-size: 12px;
}
.footer-links {
font-size: inherit;
}
}
|
MahdiMajidzadeh/qomlug
|
static/css/main.css
|
CSS
|
mit
| 4,924
|
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Starforge.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Starforge.qhc"
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Starforge"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Starforge"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
|
galaxyproject/starforge
|
docs/Makefile
|
Makefile
|
mit
| 7,421
|
# -*- coding: utf-8 -*-
# Copyright (c) 2012 Fabian Barkhau <fabian.barkhau@gmail.com>
# License: MIT (see LICENSE.TXT file)
import os
from django.core.exceptions import PermissionDenied
from apps.gallery.models import Gallery
from apps.gallery.models import Picture
from apps.team.utils import assert_member
from apps.team import control as team_control
def can_edit(account, gallery):
return not ((gallery.team and not team_control.is_member(account, gallery.team)) or
(not gallery.team and gallery.created_by != account))
def _assert_can_edit(account, gallery):
if not can_edit(account, gallery):
raise PermissionDenied
def delete(account, gallery):
""" Delete gallery and all pictures belonging to it. """
_assert_can_edit(account, gallery)
for picture in gallery.pictures.all():
remove(account, picture)
gallery.delete()
def remove(account, picture):
""" Remove picture from the gallery and delete the image file on server. """
gallery = picture.gallery
_assert_can_edit(account, gallery)
if gallery.primary == picture:
gallery.primary = None
gallery.updated_by = account
gallery.save()
os.remove(picture.image.path)
os.remove(picture.preview.path)
os.remove(picture.thumbnail.path)
picture.delete()
return gallery
def setprimary(account, picture):
""" Set picture as the galleries primary picture. """
gallery = picture.gallery
_assert_can_edit(account, gallery)
gallery.primary = picture
gallery.save()
def add(account, image, gallery):
""" Add a picture to the gallery. """
_assert_can_edit(account, gallery)
picture = Picture()
picture.image = image
picture.preview = image
picture.thumbnail = image
picture.gallery = gallery
picture.created_by = account
picture.updated_by = account
picture.save()
return picture
def create(account, image, team):
""" Create a new gallery. """
if team:
assert_member(account, team)
gallery = Gallery()
gallery.created_by = account
gallery.updated_by = account
gallery.team = team
gallery.save()
picture = add(account, image, gallery)
gallery.primary = picture
gallery.save()
return gallery
|
F483/bikesurf.org
|
apps/gallery/control.py
|
Python
|
mit
| 2,303
|
/*
newroot.c
Replace the current root with a new one
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
void usage(void) {
fprintf(stderr, "Usage: newroot [-i] <block-special>\n");
fprintf(stderr, "-i: copy mfs binary from boot image to memory\n");
exit(1);
}
int main(int argc, char *argv[])
{
int r;
char *dev;
int mountflags;
r = 0;
mountflags = 0; /* !read-only */
if (argc != 2 && argc != 3) usage();
if(argc == 2) {
dev = argv[1];
} else if(argc == 3) {
/* -i flag was supposedly entered. Verify.*/
if(strcmp(argv[1], "-i") != 0) usage();
mountflags |= MS_REUSE;
dev = argv[2];
}
r = mount(dev, "/", mountflags, NULL, NULL);
if (r != 0) {
fprintf(stderr, "newroot: mount failed: %s\n",strerror(errno));
exit(1);
}
return 0;
}
|
ducis/operating-system-labs
|
src.clean/commands/newroot/newroot.c
|
C
|
mit
| 874
|
---
title: "Using Logstash with OpenBMP"
date: 2017-01-04T15:04:10.000Z
---
# Using Logstash with OpenBMP
## Installing Logstash
[Visit download page](https://www.elastic.co/downloads/logstash)
## Starting logstash
Go to your logstash installation location, and run
`logstash -f openbmp-logstash.conf`
## Expanding
With logstash, you can easily get a variety of [possible outputs](https://www.elastic.co/guide/en/logstash/current/output-plugins.html). Here we provide elasticsearch output configuration with openBMP kafka input. To use other outputs or add custom data processing, add other plugins to **filter** section and **output** section. Note that **plugins execute in the order they appear**.
## Logstash config
```
input{
kafka{
zk_connect=>"localhost:2181"
topic_id=>"openbmp.parsed.collector"
group_id=>"cra-logstash"
codec=>plain
add_field=>{
"TOPIC"=>"openbmp.parsed.collector"
"TYPE"=>"collector"
}
}
kafka{
zk_connect=>"localhost:2181"
topic_id=>"openbmp.parsed.router"
group_id=>"cra-logstash"
codec=>plain
add_field=>{
"TOPIC"=>"openbmp.parsed.router"
"TYPE"=>"router"
}
}
kafka{
zk_connect=>"localhost:2181"
topic_id=>"openbmp.parsed.peer"
group_id=>"cra-logstash"
codec=>plain
add_field=>{
"TOPIC"=>"openbmp.parsed.peer"
"TYPE"=>"peer"
}
}
kafka{
zk_connect=>"localhost:2181"
topic_id=>"openbmp.parsed.bmp_stat"
group_id=>"cra-logstash"
codec=>plain
add_field=>{
"TOPIC"=>"openbmp.parsed.bmp_stat"
"TYPE"=>"bmp-stat"
}
}
kafka{
zk_connect=>"localhost:2181"
topic_id=>"openbmp.parsed.base_attribute"
group_id=>"cra-logstash"
codec=>plain
add_field=>{
"TOPIC"=>"openbmp.parsed.base_attribute"
"TYPE"=>"base-attribute"
}
}
kafka{
zk_connect=>"localhost:2181"
topic_id=>"openbmp.parsed.unicast_prefix"
group_id=>"cra-logstash"
codec=>plain
add_field=>{
"TOPIC"=>"openbmp.parsed.unicast_prefix"
"TYPE"=>"unicast-prefix"
}
}
kafka{
zk_connect=>"localhost:2181"
topic_id=>"openbmp.parsed.ls_node"
group_id=>"cra-logstash"
codec=>plain
add_field=>{
"TOPIC"=>"openbmp.parsed.ls_node"
"TYPE"=>"ls-node"
}
}
kafka{
zk_connect=>"localhost:2181"
topic_id=>"openbmp.parsed.ls_link"
group_id=>"cra-logstash"
codec=>plain
add_field=>{
"TOPIC"=>"openbmp.parsed.ls_link"
"TYPE"=>"ls-link"
}
}
kafka{
zk_connect=>"localhost:2181"
topic_id=>"openbmp.parsed.ls_prefix"
group_id=>"cra-logstash"
codec=>plain
add_field=>{
"TOPIC"=>"openbmp.parsed.ls_prefix"
"TYPE"=>"ls-prefix"
}
}
}
filter{
mutate{
split=>["message","
"]
add_field=>{"HEADER"=>"%{message[0]}"}
}
split{
field=>"message[1]"
terminator=>"
"
}
if [TOPIC] == "openbmp.parsed.collector" {
csv{
columns=>["action","sequence","admin_id","hash","routers","router_count","timestamp"]
convert=>{
"sequence"=>"integer"
"router_count"=>"integer"
}
separator=>" "
source=>"message[1]"
remove_field=>["message"]
}
}
if [TOPIC] == "openbmp.parsed.router" {
csv{
columns=>["action","sequence","name","hash","ip_address","description","term_code","term_reason","init_data","term_data","timestamp"]
convert=>{
"sequence"=>"integer"
"term_code"=>"integer"
}
separator=>" "
source=>"message[1]"
remove_field=>["message"]
}
}
if [TOPIC] == "openbmp.parsed.peer" {
csv{
columns=>["action","sequence","hash","router_hash","name","remote_bgp_id","router_ip","timestamp","remote_asn","remote_ip","peer_rd","remote_port","local_asn","local_ip","local_port","local_bgp_id","info_data","adv_cap","recv_cap","remote_holddown","adv_holddown","bmp_reason","bgp_error_code","bgp_error_subcode","error_text","is_L3VPN","is_pre_policy","is_IPv4"]
convert=>{
"sequence"=>"integer"
}
separator=>" "
source=>"message[1]"
remove_field=>["message"]
}
}
if [TOPIC] == "openbmp.parsed.bmp_stat" {
csv{
columns=>["action","sequence","router_hash","router_ip","peer_hash","peer_ip","peer_asn","timestamp","prefixes_rejected","known_dup_updates","known_dup_withdraws","invalid_cluster_list","invalid_as_path","invalid_originator_id","invalid_as_confed","prefixes_pre_policy","prefixes_post_policy"]
convert=>{
"sequence"=>"integer"
"prefixes_rejected"=>"integer"
"known_dup_updates"=>"integer"
"known_dup_withdraws"=>"integer"
"invalid_cluster_list"=>"integer"
"invalid_as_path"=>"integer"
"invalid_originator_id"=>"integer"
"invalid_as_confed"=>"integer"
"prefixes_pre_policy"=>"integer"
"prefixes_post_policy"=>"integer"
}
separator=>" "
source=>"message[1]"
remove_field=>["message"]
}
}
if [TOPIC] == "openbmp.parsed.base_attribute" {
csv{
columns=>["action","sequence","hash","router_hash","router_ip","peer_hash","peer_ip","peer_asn","timestamp","origin","as_path","as_path_count","origin_as","next_hop","MED","local_pref","aggregator","community_list","ext_community_list","cluster_list","is_atomic_agg","is_next_hop_IPv4","originator_id"]
convert=>{
"sequence"=>"integer"
"as_path_count"=>"integer"
"MED"=>"integer"
"local_pref"=>"integer"
}
separator=>" "
source=>"message[1]"
remove_field=>["message"]
}
}
if [TOPIC] == "openbmp.parsed.unicast_prefix" {
csv{
columns=>["action","sequence","hash","router_hash","router_ip","base_attr_hash","peer_hash","peer_ip","peer_asn","timestamp","prefix","prefix_len","is_IPv4","origin","as_path","as_path_count","origin_as","next_hop","MED","local_pref","aggregator","community_list","ext_community_list","cluster_list","is_atomic_agg","is_next_hop_IPv4","originator_id"]
convert=>{
"sequence"=>"integer"
"prefix_len"=>"integer"
"as_path_count"=>"integer"
"MED"=>"integer"
"local_pref"=>"integer"
}
separator=>" "
source=>"message[1]"
add_field=>{"prefix_full"=>"%{prefix}/%{prefix_len}"}
remove_field=>["message"]
}
}
if [TOPIC] == "openbmp.parsed.ls_node" {
csv{
columns=>["action","sequence","hash","base_attr_hash","router_hash","router_ip","peer_hash","peer_ip","peer_asn","timestamp","igp_router_id","router_id","routing_id","ls_id","mt_id","ospf_area_id","isis_area_id","protocol","igp_flags","as_path","local_pref","MED","next_hop","name"]
convert=>{
"sequence"=>"integer"
"MED"=>"integer"
"local_pref"=>"integer"
}
separator=>" "
source=>"message[1]"
remove_field=>["message"]
}
}
if [TOPIC] == "openbmp.parsed.ls_link" {
csv{
columns=>["action","sequence","hash","base_attr_hash","router_hash","router_ip","peer_hash","peer_ip","peer_asn","timestamp","igp_router_id","router_id","routing_id","ls_id","ospf_area_id","isis_area_id","protocol","as_path","local_pref","MED","next_hop","mt_id","local_link_id","remote_link_id","interface_ip","neighbor_ip","igp_metric","admin_group","max_link_bw","max_resv_bw","unreserved_bw","te_default_metric","link_protection","mpls_proto_mask","srlg","link_name","remote_node_hash","local_node_hash"]
convert=>{
"sequence"=>"integer"
"MED"=>"integer"
"local_pref"=>"integer"
"igp_metric"=>"integer"
"te_default_metric"=>"integer"
"max_link_bw"=>"float"
"max_resv_bw"=>"float"
}
separator=>" "
source=>"message[1]"
remove_field=>["message"]
}
}
if [TOPIC] == "openbmp.parsed.ls_prefix" {
csv{
columns=>["action","sequence","hash","base_attr_hash","router_hash","router_ip","peer_hash","peer_ip","peer_asn","timestamp","igp_router_id","router_id","routing_id","ls_id","ospf_area_id","isis_area_id","protocol","as_path","local_pref","MED","next_hop","local_node_hash","mt_id","ospf_route_type","igp_flags","route_tag","ext_route_tag","ospf_fwd_addr","igp_metric","prefix","prefix_len"]
convert=>{
"sequence"=>"integer"
"MED"=>"integer"
"local_pref"=>"integer"
"igp_metric"=>"integer"
"prefix_len"=>"integer"
"route_tag"=>"integer"
"ext_route_tag"=>"integer"
}
separator=>" "
source=>"message[1]"
add_field=>{"prefix_full"=>"%{prefix}/%{prefix_len}"}
remove_field=>["message"]
}
}
date{
match => ["timestamp", "YYYY-MM-dd HH:mm:ss.SSSSSS"]
remove_field => ["timestamp"]
}
}
output{
# stdout{
# codec=>"json_lines"
# }
elasticsearch{
index=>"openbmp"
document_type=>"%{TYPE}"
}
}
```
|
SNAS/website
|
site/content/docs/logstash.md
|
Markdown
|
mit
| 8,291
|
var gulp = require('gulp');
var paths = require('../paths');
var tslint = require('gulp-tslint');
gulp.task('lint', function () {
return gulp.src(paths.source)
.pipe(tslint({
formatter: "verbose"
}))
.pipe(tslint.report())
});
|
abeven/aurelia-oauth
|
build/tasks/lint.js
|
JavaScript
|
mit
| 247
|
using Skybrud.Social.Json;
namespace Skybrud.Social.Instagram.Objects {
public class InstagramImageSummary : SocialJsonObject {
#region Properties
public InstagramMediaSummary LowResolution { get; private set; }
public InstagramMediaSummary Thumbnail { get; private set; }
public InstagramMediaSummary StandardResolution { get; private set; }
#endregion
#region Constructors
private InstagramImageSummary(JsonObject obj) : base(obj) {
// Hide default constructor
}
#endregion
#region Static methods
public static InstagramImageSummary Parse(JsonObject obj) {
if (obj == null) return new InstagramImageSummary(null) {
LowResolution = new InstagramMediaSummary(null),
Thumbnail = new InstagramMediaSummary(null),
StandardResolution = new InstagramMediaSummary(null)
};
return new InstagramImageSummary(obj) {
LowResolution = obj.GetObject("low_resolution", InstagramMediaSummary.Parse),
Thumbnail = obj.GetObject("thumbnail", InstagramMediaSummary.Parse),
StandardResolution = obj.GetObject("standard_resolution", InstagramMediaSummary.Parse)
};
}
#endregion
}
}
|
emilmoe/Skybrud.Social
|
src/Skybrud.Social/Instagram/Objects/InstagramImageSummary.cs
|
C#
|
mit
| 1,341
|
using System;
using System.Text;
using Bloom.Api;
using Bloom.ErrorReporter;
using Bloom.MiscUI;
using Bloom.web.controllers;
using BloomTests.DataBuilders;
using Moq;
using NUnit.Framework;
using SIL.Reporting;
namespace BloomTests.ErrorReporter
{
[TestFixture]
public class HtmlErrorReporterTests
{
private string _testValue = "";
[NUnit.Framework.SetUp]
public void Setup()
{
// doesn't make it true, but allows the methods we're testing to use the
// error reporting paths designed for when it is.
BloomServer.ServerIsListening = true;
}
[NUnit.Framework.TearDown]
public void TearDown()
{
BloomServer.ServerIsListening = false;
}
private Mock<IReactDialogFactory> GetDefaultMockReactDialogFactory()
{
var mockFactory = new Mock<IReactDialogFactory>();
var mockBrowserDialog = new Mock<IBrowserDialog>();
mockFactory.Setup(x => x.CreateReactDialog(It.IsAny<string>(), It.IsAny<object>())).Returns(mockBrowserDialog.Object);
return mockFactory;
}
#region GetMessage tests
[Test]
public void GetMessage_OnlyText()
{
var result = HtmlErrorReporter.GetMessage("message text", null);
Assert.AreEqual("message text", result);
}
[Test]
public void GetMessage_OnlyException()
{
var exception = new ApplicationException("fake exception");
var result = HtmlErrorReporter.GetMessage(null, exception);
Assert.AreEqual("fake exception", result);
}
[Test]
public void GetMessage_TextAndException_ReturnsTextOnly()
{
var exception = new ApplicationException("fake exception");
var result = HtmlErrorReporter.GetMessage("message text", exception);
Assert.AreEqual("message text", result);
}
#endregion
#region NotifyUserOfProblem tests
[Test]
public void NotifyUserOfProblem_UnsafeMessage()
{
var mockFactory = GetDefaultMockReactDialogFactory();
var reporter = new HtmlErrorReporterBuilder()
.WithTestValues()
.BrowserDialogFactory(mockFactory.Object)
.Build();
// System Under Test
reporter.NotifyUserOfProblem(new ShowAlwaysPolicy(), "", ErrorResult.Yes, "<b>Tags should not be encoded</b>");
mockFactory.Verify(x => x.CreateReactDialog(
It.Is<string>(b=> b == "problemReportBundle"),
It.Is<object>(props => (string)props.GetType().GetProperty("level").GetValue(props) == ProblemLevel.kNotify &&
(string)props.GetType().GetProperty("message").GetValue(props) == "<b>Tags should not be encoded</b>")
));
}
[Test]
public void NotifyUserOfProblem_LongMessage()
{
var messageTextBuilder = new StringBuilder();
for (int i = 0; i < 3000; ++i)
{
messageTextBuilder.Append('a');
}
var messageText = messageTextBuilder.ToString();
var mockFactory = GetDefaultMockReactDialogFactory();
var reporter = new HtmlErrorReporterBuilder()
.WithTestValues()
.BrowserDialogFactory(mockFactory.Object)
.Build();
// System Under Test
reporter.NotifyUserOfProblem(new ShowAlwaysPolicy(), "", ErrorResult.Yes, messageText);
// Verification
mockFactory.Verify(x => x.CreateReactDialog(
It.Is<string>(b => b == "problemReportBundle"),
It.Is<object>(props => (string)props.GetType().GetProperty("level").GetValue(props) == ProblemLevel.kNotify &&
(string)props.GetType().GetProperty("message").GetValue(props) == messageText)
));
}
[TestCase("Report")]
[TestCase("CustomReport")]
public void NotifyUserOfProblem_ReportButton(string reportLabel)
{
var mockFactory = GetDefaultMockReactDialogFactory();
var reporter = new HtmlErrorReporterBuilder()
.WithTestValues()
.BrowserDialogFactory(mockFactory.Object)
.Build();
// System Under Test
reporter.NotifyUserOfProblem(new ShowAlwaysPolicy(), reportLabel, ErrorResult.Yes, "message");
mockFactory.Verify(x =>
x.CreateReactDialog(
It.Is<string>(b => b == "problemReportBundle"),
It.Is<object>(props => (string)props.GetType().GetProperty("level").GetValue(props) == ProblemLevel.kNotify &&
(string)props.GetType().GetProperty("reportLabel").GetValue(props) == reportLabel &&
(string)props.GetType().GetProperty("message").GetValue(props) == "message")
)
);
}
/// <summary>
/// We want to automatically convert the hard-coded "Details" parameter that ErrorReport.cs passes in
/// to the new default
/// </summary>
[Test]
public void NotifyUserOfProblem_IfParamIsDetailsThenConvertedToReport()
{
var mockFactory = GetDefaultMockReactDialogFactory();
var reporter = new HtmlErrorReporterBuilder()
.WithTestValues()
.BrowserDialogFactory(mockFactory.Object)
.Build();
// System Under Test
reporter.NotifyUserOfProblem(new ShowAlwaysPolicy(), "Details", ErrorResult.Yes, "message");
mockFactory.Verify(x => x.
CreateReactDialog(
It.Is<string>(b => b == "problemReportBundle"),
It.Is<object>(props => (string)props.GetType().GetProperty("level").GetValue(props) == ProblemLevel.kNotify &&
(string)props.GetType().GetProperty("reportLabel").GetValue(props) == "Report" &&
(string)props.GetType().GetProperty("message").GetValue(props) == "message")
)
);
}
#endregion
#region CustomNotifyUserAuto tests
/// <summary>
/// Test the workaround for if you truly want it to say "Details"
/// </summary>
[Test]
public void CustomNotifyUserAuto_IfInstanceVarIsDetailsThenStaysDetails()
{
var mockFactory = GetDefaultMockReactDialogFactory();
var reporter = new HtmlErrorReporterBuilder()
.WithTestValues()
.BrowserDialogFactory(mockFactory.Object)
.Build();
// CustomNotifyUserAuto calls ErrorReport, so we should set it up
ErrorReport.SetErrorReporter(reporter);
// System Under Test
reporter.CustomNotifyUserAuto("Details", null, null, null, "message");
mockFactory.Verify(x =>
x.CreateReactDialog(
It.Is<string>(b => b == "problemReportBundle"),
It.Is<object>(props => (string)props.GetType().GetProperty("level").GetValue(props) == ProblemLevel.kNotify &&
(string)props.GetType().GetProperty("reportLabel").GetValue(props) == "Details" &&
(string)props.GetType().GetProperty("message").GetValue(props) == "message")
)
);
}
/// <summary>
/// Tests that you can use this function to add a secondary action button with the desired text
/// </summary>
[Test]
public void CustomNotifyUserAuto_SecondaryActionButtonLabel()
{
var mockFactory = GetDefaultMockReactDialogFactory();
var reporter = new HtmlErrorReporterBuilder()
.WithTestValues()
.BrowserDialogFactory(mockFactory.Object)
.Build();
// CustomNotifyUserAuto calls ErrorReport, so we should set it up
ErrorReport.SetErrorReporter(reporter);
// System Under Test
reporter.CustomNotifyUserAuto("", "Retry", null, null, "message");
// Verification
mockFactory.Verify(x => x.CreateReactDialog(
It.Is<string>(b => b == "problemReportBundle"),
It.Is<object>(props => (string)props.GetType().GetProperty("level").GetValue(props) == ProblemLevel.kNotify &&
(string)props.GetType().GetProperty("secondaryLabel").GetValue(props) == "Retry" &&
(string)props.GetType().GetProperty("message").GetValue(props) == "message")
));
}
[Test]
public void CustomNotifyUserAuto_SecondaryActionAutoInvoked()
{
// Simulate click on a button
var mockFactory = new Mock<IReactDialogFactory>();
var mockBrowserDialog = new Mock<IBrowserDialog>();
mockBrowserDialog.SetupAllProperties(); // This is necessary for properties like CloseSource to set their values.
mockBrowserDialog.Setup(x => x.ShowDialog()).Callback(delegate {
mockBrowserDialog.Object.CloseSource = "closedByAlternateButton";
});
mockFactory.Setup(x => x.CreateReactDialog(It.IsAny<string>(), It.IsAny<object>()))
.Returns(mockBrowserDialog.Object);
var reporter = new HtmlErrorReporterBuilder()
.WithTestValues()
.BrowserDialogFactory(mockFactory.Object)
.Build();
// CustomNotifyUserAuto calls ErrorReport, so we should set it up
ErrorReport.SetErrorReporter(reporter);
_testValue = "";
Action<Exception, string> action = delegate (Exception e, string s)
{
_testValue = "Retry was pressed";
};
// System Under Test
reporter.CustomNotifyUserAuto("", "Retry", action, null, "message");
// Verification
Assert.AreEqual("Retry was pressed", _testValue);
// Cleanup
_testValue = "";
}
#endregion
#region CustomNotifyUserManual tests
[Test]
public void CustomNotifyUserManual_WhenSecondaryActionButtonClicked_ThenSecondaryActionResultReturned()
{
// Simulate click on a button
var mockFactory = new Mock<IReactDialogFactory>();
var mockBrowserDialog = new Mock<IBrowserDialog>();
mockBrowserDialog.SetupAllProperties(); // This is necessary for properties like CloseSource to set their values.
mockBrowserDialog.Setup(x => x.ShowDialog()).Callback(delegate
{
mockBrowserDialog.Object.CloseSource = "closedByAlternateButton";
});
mockFactory.Setup(x => x.CreateReactDialog( It.IsAny<string>(),It.IsAny<object>())).Returns(mockBrowserDialog.Object);
var reporter = new HtmlErrorReporterBuilder()
.WithTestValues()
.BrowserDialogFactory(mockFactory.Object)
.Build();
// CustomNotifyUserManual calls ErrorReport, so we should set it up
ErrorReport.SetErrorReporter(reporter);
// System Under Test
var result = reporter.CustomNotifyUserManual(new ShowAlwaysPolicy(),
"Report", ErrorResult.Yes,
"Retry", ErrorResult.Retry,
"message");
// Verification
Assert.AreEqual(ErrorResult.Retry, result);
// Cleanup
}
[Test]
public void CustomNotifyUserManual_WhenReportButtonClicked_ThenReportResultReturned()
{
// Simulate click on a button
var mockFactory = new Mock<IReactDialogFactory>();
var mockBrowserDialog = new Mock<IBrowserDialog>();
mockBrowserDialog.SetupAllProperties(); // This is necessary for properties like CloseSource to set their values.
mockBrowserDialog.Setup(x => x.ShowDialog()).Callback(delegate
{
mockBrowserDialog.Object.CloseSource = "closedByReportButton";
});
mockFactory.Setup(x => x.CreateReactDialog( It.IsAny<string>(), It.IsAny<object>()))
.Returns(mockBrowserDialog.Object);
var reporter = new HtmlErrorReporterBuilder()
.WithTestValues()
.BrowserDialogFactory(mockFactory.Object)
.Build();
// CustomNotifyUserManual calls ErrorReport, so we should set it up
ErrorReport.SetErrorReporter(reporter);
// System Under Test
var result = reporter.CustomNotifyUserManual(new ShowAlwaysPolicy(),
"Report", ErrorResult.Yes,
"Retry", ErrorResult.Retry,
"message");
// Verification
Assert.AreEqual(ErrorResult.Yes, result);
}
[Test]
public void CustomNotifyUserManual_WhenCloseButtonClicked_ThenOKReturned()
{
// Simulate click on a button
var mockFactory = new Mock<IReactDialogFactory>();
var mockBrowserDialog = new Mock<IBrowserDialog>();
mockBrowserDialog.Setup(x => x.ShowDialog()).Callback(delegate
{
mockBrowserDialog.Object.CloseSource = null;
});
mockFactory.Setup(x => x.CreateReactDialog(It.IsAny<string>(), It.IsAny<object>()))
.Returns(mockBrowserDialog.Object);
var reporter = new HtmlErrorReporterBuilder()
.WithTestValues()
.BrowserDialogFactory(mockFactory.Object)
.Build();
// CustomNotifyUserManual calls ErrorReport, so we should set it up
ErrorReport.SetErrorReporter(reporter);
// System Under Test
var result = reporter.CustomNotifyUserManual(new ShowAlwaysPolicy(),
"Report", ErrorResult.Yes,
"Retry", ErrorResult.Retry,
"message");
// Verification
Assert.AreEqual(ErrorResult.OK, result);
}
#endregion
}
}
|
StephenMcConnel/BloomDesktop
|
src/BloomTests/ErrorReporter/HtmlErrorReporterTests.cs
|
C#
|
mit
| 11,772
|
---
title: Pristavi u Novom zavetu
date: 29/01/2018
---
I u Starom i u Novom zavetu pojam pristava određuje se po tome šta radi. Posebno Novi zavet opisuje pristava u smislu odgovornosti (Luka 12,48) i očekivanja (1. Korinćanima 4,2). Stari zavet je više usredsređen na objavljivanje Božjeg vlasništva nego na neposredno definisanje nas kao Njegovih pristava. Dakle, iako je pojam pristava veoma sličan u oba zaveta, Novi zavet proširuje koncept izvan samog upravljanja domaćinstvom.
U priči o nepravednom sluzi (Luka 16,1-15), Isus proširuje definiciju pristava. Njegova pouka ne govori samo o pristavu koji je izbegao finansijsku katastrofu. Ona se, takođe, može primeniti na one koji izbegavaju duhovnu katastrofu mudrim ispoljavanjem vere. Mudar pristav će se pripremiti za budući Isusov dolazak (Matej 25,21).
`Pročitajte sledeće tekstove: 1. Korinćanima 4,1.2; Titu 1,7; 1. Petrova 4,10. Šta ovi stihovi govore o pristavima i pristavskoj službi?`
»Da li ću otvoriti svoje srce Svetom Duhu da svaki dar i sposobnost mogu biti pokrenuti, koje mi je Bog poverio? Ja sam Hristova svojina, i radim u Njegovoj službi. Ja sam pristav Njegove blagodati.« (Elen Vajt, Fundamentals of Christian Education, str. 301)
U Luka 12,35-48, Isus koristi izraz »pristav« u metaforičnom smislu. On priča o mudrom slugi koji je bio spreman za povratak sina čovečijeg, i opisuje nevernog pristava kao onog koji je prestao da vrši svoje dužnosti zato što je gospodar odložio svoj povratak. Neverni pristav se pretvorio u tiranina koji se rđavo ophodio prema ljudima oko sebe. On više nije bio uzor dobrih dela ili upravitelj blagodati.
Kada prihvatimo Hrista, mi smo pristavi, pozvani da upravljamo Božjim sredstvima. Ali što je još važnije, treba da upravljamo duhovnom stvarnosti hrišćanskog života pripremajući se za Nebo.
`Pročitajte Luka 12,45. Zašto mi kao adventistički hrišćani, koji se često bore sa osećanjem »kašnjenja«, moramo biti naročito pažljivi da ne posrnemo u ovu zabludu?`
|
PrJared/sabbath-school-lessons
|
src/sr/2018-01/05/03.md
|
Markdown
|
mit
| 2,044
|
/*
* The MIT License
*
* Copyright (c) 2010, Winston.Prakash@oracle.com, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.views;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionPoint;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.View;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.annotation.Nonnull;
import jenkins.model.GlobalConfiguration;
import jenkins.model.Jenkins;
import hudson.model.ListView;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.StaplerRequest;
/**
* Extension point for adding a ViewsTabBar header to Projects {@link ListView}.
*
* <p>
* This object must have the <tt>viewTabs.jelly</tt>. This view
* is called once when the project views main panel is built.
* The "views" attribute is set to the "Collection of views".
*
* <p>
* There also must be a default constructor, which is invoked to create a Views TabBar in
* the default configuration.
*
* @author Winston Prakash
* @since 1.381
* @see ViewsTabBarDescriptor
*/
public abstract class ViewsTabBar extends AbstractDescribableImpl<ViewsTabBar> implements ExtensionPoint {
/**
* Returns all the registered {@link ViewsTabBar} descriptors.
*/
public static DescriptorExtensionList<ViewsTabBar, Descriptor<ViewsTabBar>> all() {
return Jenkins.getInstance().<ViewsTabBar, Descriptor<ViewsTabBar>>getDescriptorList(ViewsTabBar.class);
}
@Override
public ViewsTabBarDescriptor getDescriptor() {
return (ViewsTabBarDescriptor)super.getDescriptor();
}
/**
* Sorts the views by {@link View#getDisplayName()}.
*
* @param views the views.
* @return the sorted views
* @since 2.37
*/
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // invoked from stapler view
public List<View> sort(@Nonnull List<? extends View> views) {
List<View> result = new ArrayList<View>(views);
Collections.sort(result, new Comparator<View>() {
@Override
public int compare(View o1, View o2) {
return o1.getDisplayName().compareTo(o2.getDisplayName());
}
});
return result;
}
/**
* Configures {@link ViewsTabBar} in the system configuration.
*
* @author Kohsuke Kawaguchi
*/
@Extension(ordinal=310) @Symbol("viewsTabBar")
public static class GlobalConfigurationImpl extends GlobalConfiguration {
public ViewsTabBar getViewsTabBar() {
return Jenkins.get().getViewsTabBar();
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
// for compatibility reasons, the actual value is stored in Jenkins
Jenkins j = Jenkins.get();
if (json.has("viewsTabBar")) {
j.setViewsTabBar(req.bindJSON(ViewsTabBar.class,json.getJSONObject("viewsTabBar")));
} else {
j.setViewsTabBar(new DefaultViewsTabBar());
}
return true;
}
}
}
|
aldaris/jenkins
|
core/src/main/java/hudson/views/ViewsTabBar.java
|
Java
|
mit
| 4,437
|
---
title: Pendalaman
date: 03/11/2017
---
Bacalah buku Ellen G. White, “Christ the Center of the Message,” hlm. 388, dalam Selected Messages, jld. 1; “Panggilan kepada Abraham,” hlm. 136-144; “Hukum dan Perjanjian,” hlm. 430-444, dalam Alfa dan Omega, jld. 1; “Khotbah dia Atas Bukit,” Alfa dan Omega jld. 5, hlm. 317-335; “Pertentangan,” hlm. 227-237; “ ‘Sudah Selesai,’ ” hlm. 410-418;, dalam Alfa dan Omega, jld. 6.
“Kalau ada orang yang bekerja, upahnya tidak diperhitungkan sebagai hadiah, tetapi sebagai haknya (Roma 4:4). Rasul di sini menjelaskan pasal yang dikutip (Kej. 15:4-6) Untuk menyimpulkan dan membuktikan dari pasal itu bahwa pembenaran adalah oleh iman dan bukan oleh perbuatan. Ini yang ia lakukan pertama-tama dengan menerangkan arti dari kata ‘itu diperhitungkan kepadanya sebagai kebenaran.’ Kata-kata ini menjelaskan bahwa Allah menerima (orang-orang berdosa) oaleh kasih karunia dan bukan karena perbuatan mereka.” —Martin Luther, Commentary on Romans, hlm. 82.
“Jika Setan berhasil dalam menuntun manusia untuk menempatkan nilai terhadap perbuatannya sendiri sebagai perbuatan jasa dan kebenaran, dia tahu bahwa dia dapat mengalahkannya dengan pencobaannya, dan menjadikan dia korban dan mangsanya. . . . Bubuhi palang pintumu dengan darah Anak Domba Golgota, dan Anda akan selamat.”—Ellen G. White, Advent Review and Sabbath Herald, Sept. 3, 1889.
**Pertanyaan-pertanyaan untuk Didiskusikan**:
`Mengapakah begitu penting untuk memahami keselamatan oleh iman saja tanpa penurutan terhadap hukum? Dari kesalahan-kesalahan apa saja pengetahuan tentang hal tersebut dapat melindungi kita? Bahaya apakah yang sedang menanti mereka yang kehilangan pandangan terhadap ajaran Alkitab yang begitu penting ini?`
`Apakah alasan lain yang dapat Anda berikan untuk keabsahan hukuman Allah yang berkelanjutan, bahkan ketika kita mengerti bahwa hukum dan penurutan hukum tidak dapat menyelamatkan kita?`
`Isu utama pada inti reformasi adalah bagaimanakah kita diselamatkan? Cara-cara apakah sehingga kita dapat secara terbuka dan terus terang berbicara tentang perbedaan antar Protestan dan katolik sehubungan dengan pembahasan penting ini, dengan tidak menyerang pribadi seseorang?`
`Sebagai orang-orang berdosa yang telah dibenarkan, kita telah dijadikan sebagai penerima kasih karunia dan mendapatkan kebaikan Allah yang sebenarnya tidak layak kita terima, yang kepada-Nya kita telah berdosa. Bagaimanakah realitas ini berdampak pada bagaimana kita berhubungan dengan orang lain? Bagaimanakah kita harus penuh rahmat dan kebaikan kepada mereka yang telah bersalah kepada kita dan sebenarnya tidak layak menerima anugerah dan kebaikan kita?`
|
PrJared/sabbath-school-lessons
|
src/in/2017-04/05/07.md
|
Markdown
|
mit
| 2,711
|
/*******************************************************************************
* ENdoSnipe 5.0 - (https://github.com/endosnipe)
*
* The MIT License (MIT)
*
* Copyright (c) 2012 Acroquest Technology Co.,Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package jp.co.acroquest.endosnipe.web.explorer.entity;
/**
* 計測項目詳細オブジェクト
* @author fujii
*
*/
public class MeasurementData
{
/** タイムスタンプ */
public long timestamp_;
/** 計測項目詳細 */
public MeasurementDetailData measurementItem_;
/**
* コンストラクタ
*/
public MeasurementData()
{
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
return "MeasurementData [measurement_item=" + measurementItem_.toString() + ", timestamp="
+ timestamp_ + "]";
}
}
|
t-hiramatsu/ENdoSnipe
|
Dashboard/src/main/java/jp/co/acroquest/endosnipe/web/explorer/entity/MeasurementData.java
|
Java
|
mit
| 2,051
|
---
layout: post
title: 键盘那些事,hhkb开箱
category: 生活
tags: 键盘
keywords: keyboard,hhkb,电容键盘,机械键盘
description:
---
最为一个有追求的程序员,一块好的键盘是非常有必要的,键盘对于程序员,就好比是篮球运动员的球鞋,斯诺克球手的球杆,f1赛车手的方向盘,歌手的麦克风等等,好的键盘只有一个感觉,让你敲起来很爽。借着这次新入手的一块hhkb type-s,和大家聊聊自己对键盘的一些个人感受。
就像鼠标一样,根据原理,可以分为机械鼠标,光电鼠标,激光鼠标。键盘按照原理,可以分为薄膜键盘、机械键盘、电容键盘。从外观上是看不出来三种键盘的区别的,他们的区别在于键盘每个键的下方。薄膜键盘下是一层薄膜,机械键盘下是一个键轴,电容键盘下是电容键盘的设备(不知道该如何形容,其实电容只是翻译过来的名称,和我们所知道的电容关系也不大)。
##薄膜键盘
---
薄膜键盘最常见,99%以上的键盘都是薄膜键盘,最具性价比。品牌有很多,什么dell,微软,还有很多国产品牌,都非常便宜。我最喜欢的薄膜键盘是戴尔8115,100来块钱,好的很。
##机械键盘
---
2013年,我买了第一块机械键盘,filco 87忍者 黑轴。机械键盘主流的分为四种轴,黑、红、茶、青。不同轴之间的手感可谓是千差万别。黑轴红轴按键无段落感,直上直下。茶轴青轴有段落感,键按下一半时会有“咔”的确认感。 黑轴最硬(压力克数高),红轴软(压力克数低),茶轴压力可数适中,所以买的人最多,青轴压力克数最低,手感最软,但是确认感最强,声音最大。我当时买黑轴的原因是,我觉得我手指力度比较大,敲键盘力度大,不喜欢键太软,也因为黑轴最快的触发(1.5mm)。
再来说说机械键盘的品牌的个人感觉。在我看来机械键盘品牌只有三种。1:cherry 2:filco 3:杂牌。
cherry是机械键盘中古老的传说,永远的经典。现在几乎所有好点的机械键盘,最核心的部件键轴都是cherry的轴。cherry的键盘造型都是很复古的大键盘,造型比较土。
filco是我最喜欢的机械键盘品牌,特点在于细腻,细腻的你能感觉到钱都花哪儿了。它的87圣手系列,87个键的短键盘,字母有正刻、侧刻、无刻三种。filco的价格比杂牌的机械键盘高不少,但是值得。有一次我键盘脏了就把键盘每一个键帽都拆下来清洗,发现每一个键的键帽高度和手指凹凸的弧度都不相同。所以说手感好并不完全是因为轴的手感,是由许许多多的细节才决定的。这不是一些杂牌,弄点cherry轴就可以比的了的哦。最后吐槽下filco。filco键盘买的人不算很多,但是货似乎更少。白色的圣手系列,一年前就已经买不到了,白色圣手茶轴和红轴是最稀缺的,2年前就已经买不到新的了。现在市面只能买的到黑色的和粉色的。filco为什么不出白色圣手而出个那么丑的粉红色到底是何居心?
杂牌:除了上面2个牌子以外我个人觉得都是杂牌。但其实杂牌里面还是有一些大牌的,价格也不菲。比如赛睿SteelSeries,雷蛇razer。但是这些都是鼠标大牛的品牌,键盘还是不行,而且造型炫酷的接收不了啊。。。另外有些国产二三百的机械键盘,我就很怀疑这些机械键盘算机械键盘嘛。
##电容键盘
---
以前买机械键盘的时候听说过电容键盘,听说是linux程序员专用,听说很贵。那时候我只是个.net程序员,很少会去弄linux,所以看都没去看它。直到上个月和同事讨论有没有mac专用的机械键盘时候,才发现了它,hhkb。
电容键盘是日本topre的专利技术,只有他家做的键盘才能叫做电容键盘。他有两个重要的系列,HHKB和RealFroce(后面简称rf)。rf是topre自己的产品,hhkb是他给PFU代工的产品。pfu是富士通的全资子公司(关于pfu和topre的关系找了好多资料才找到)。hhkb和rf最大的区别是,rf大多数键盘都是按照window的习惯做,比较符合大众,而hhkb是按照linux和mac的键位风格做,专为程序员设计的。
hhkb是简称,它的霸气全称是:**Happy Hacking keyboard** 快乐黑客键盘,这名字牛不牛 !!!hhkb主要分为 pro和type-s两种,type-s是在pro的基础上做了静音,叫做静电容键盘,所以价格也比pro高出不少。很多测评的人说手感也会有所不同。我是没试过pro,但是我分析是因为types的按键的高度比pro矮了几毫米导致的吧。文章最后有一段视频大家可以打开看看对比下两者声音上的区别。
##hhkb开箱
---
终于到了重点,来直播一下hhkb第一手的开箱照片。我直接在日本亚马逊入手的,通过转运公司转运到中国,一共用了一周时间吧,还是挺快的。

一起买的还有hhkb原厂的键盘包,键帽和拔键器,还有个travel笔记本


键盘的盒子,type-s盒子和pro的盒子区别就在右上角有个type-s的标,我看了别人晒的开箱图,有的type-s标还是蓝色的,型号是kb400ws,那个是白色字母正刻的型号,我买的是 kb400wns,白色无刻,所以是红色标。




键盘拿出来了



type-s和pro外观外观唯一的区别在于右上角的type-s

hhkb的背面,那幅图是键盘的跳线说明,通过跳线可以修改键盘的按钮分布规则,可以适配mac和windows。我是mac机器用,跳线2、3位打开,其他关闭



hhkb的键帽和拔键器


拆下两个键可以看到电容键盘下的结构.静电容使用了无触点的电容式开关,静电容量是利用电容容量的变化来判断按键的开和关,在按下按键后,开关中电容容量发生改变,从而实现触发,整个过程不需要开关的闭合,无物理接触点就可以实现敲击操作,因而磨损更小,使用寿命更长


换了两个红色的键帽。hhkb的键盘材质是PBT,它要比ABS高端一点,触感有细微不同,键帽上的刻字更不容易磨损。大多机械键盘的键帽都是ABS材质的,包括前面说的filco这么高端的机械键盘品牌的键帽都是ABS的。


把我的filco拿过来和他拍个照对比一下。filco已经是87键的短键盘了,但是hhkb比filco更短,hhkb只有60个键,大量的键通过fn功能键实现,包括上下左右的方向键。





hhkb键盘包登场。本来买这个包是想既可以装hhkb又可以装filco87圣手的,结果这个包尺寸是按照hhkb设计的,正好放得下hhkb,放不下filco87。包还是很硬正的,质感很好。


最后包里装着键盘,带到了单位使用。毕竟在单位敲键盘的时间更多一些。来几张在单位拍的照片


用了一天后,来谈谈大家最关心的问题。到底好不好用,手感行不行?
很多人说到hhkb就会拿去和机械键盘去对比,说和红轴比较像,比较软,又有点像薄膜键盘,但是比薄膜键盘手感更细腻。如果硬要去比较的话,我觉得上面两句说的都很准确。但其实3种键盘完全是不同结构的东西。就像你比较包菜和大白菜,你说包菜口感更脆一些,大白菜甜度更细腻一些。说的也不错,听着好像就是那么回事。但是2种东西可以比较的维度太多了,很难对比这个那个的。还是谁用谁知道。就手感上来说,hhkb还是很特别的,但是很舒服,键盘敲起来也很爽。
再来说说hhkb的键位。这款键盘叫做**Happy Hacking keyboard** 快乐黑客键盘,一切键位设计都很符合mac和linux的使用习惯。 我的键盘是无刻的看不出来什么,来张张有字的。
没有方向键,方向键通过fn加他相邻左侧的四个键组成。并且方向键左侧还有上一页下一页页首页尾。通过fn这样就把所以这些方向控制键集合在一起了,很人性化的设计。通过fn的设计,剪裁掉了许多键。
注意ctrl的位置,ctrl放那真的合理吗?至少我用mac觉得ctrl在那个位置很合理。mac中command其实相当于windows里面的ctrl。复制粘贴就是command+c和command+v,刚开始window用喜欢也觉得那个位置不好。但是mac用一段时间之后,觉得这个位置更科学,因为mac用大拇指按command键,windows用小拇指按ctrl。习惯后会觉得大拇指按的更舒服。ctrl在mac里面是辅助键,所以在mac里经常需要command+ctrl一起按,mac键盘里面ctrl和command中间之隔一个键,所以你2个手指去按这两个键就觉得很变扭。再看hhkb的键位,ctrl和command就是自然手型的位置,大拇指放在command上,无名指和中指都自然的在ctrl上了。在原先的mac键盘的这个位置是caps lock。这个键又不会和command组合使用,把它干掉换成ctrl是非常舒服的。在有的vim的教程里面,也会推荐你使用工具去把caps lock和ctrl互换位置。

最后说说hhkb的按键的声音,types的按键声音很低调,噗噗噗的,但是很有感觉,下面有段视频,大家可以打开听一听。[types和pro的声音对比](http://www.tudou.com/programs/view/O4KNR_VTW70)
写了那么多关于hhkb,那到底会不会推荐大家使用呢?针对普通人群来说,我并不推荐该款键盘,因为你用不上他的卖点,也就只会是一款较为特别的键盘。对于使用mac的程序员或者经常需要在mac上进行文字输入的人群,还是非常不错的选择。
hhkb被键盘发烧友叫做退烧神器,觉得拥有它了,一切就已经完美了。我觉得还不至于吧,以后会有很多更好更有特色的键盘出现的,比如这款叫做Optimus Maximus万键之王的东西,大哥,你一按shift,你键盘上的所有字母变成大写的了。。。找了个视频,大家随意看看。[Optimus Maximus万键之王](http://www.tudou.com/programs/view/UMk69iYNoSo)
|
cnbin/coolnameismy.github.io
|
_posts/life/2015-08-23-life-keyboardAndHHKB.md
|
Markdown
|
mit
| 12,086
|
import * as Cookies from 'js-cookie';
import axios from 'axios';
import { route } from 'preact-router';
function storeUserCredentials({ user, accessToken, expires }) {
Cookies.set('crendentials', { user, accessToken }, { expires: new Date(expires) });
}
export function getUserCredentials() {
return Cookies.getJSON('crendentials');
}
export function isAuthenticated() {
const crendentials = getUserCredentials();
return !(crendentials === null || crendentials === undefined);
}
export function onLogin(response) {
storeUserCredentials(response);
route('/', true);
}
export function logout() {
Cookies.remove('crendentials');
route('/login', true);
}
export function authenticate(params = {}) {
axios
.post(`/auth/${params.network}`, { access_token: params.access_token })
.then(response => response.data)
.then(onLogin)
.catch((error) => {
alert('User could not login');
console.error(error);
});
}
|
josuemontano/API-platform
|
src/assets/js/utils/auth.js
|
JavaScript
|
mit
| 956
|
<div class="basic-merge-blanks">
<div>
<p>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd
gubergren, no sea takimata sanctus est Lorem ipsum dolor sit. Lorem ipsum
dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd
gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
</p>
</div>
<div>
<p>
Lorem
ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd
gubergren, no sea takimata sanctus est Lorem ipsum dolor sit. Lorem ipsum
dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd
gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
Loremipsum <!-- Words without whitespace shouldn't be marked -->
</p>
</div>
</div>
|
julmot/jquery.mark
|
test/fixtures/basic/merge-blanks.html
|
HTML
|
mit
| 1,610
|
---
title: Для подальшого дослідження
date: 22/09/2017
---
«Божий Дух стримує зло за допомогою совісті людини. Коли людина звеличує себе над Святим Духом, вона пожинає плоди свого беззаконня. Вплив Духа на таку людину зменшується, і Йому стає все складніше стримувати непослух, який вона всюди сіє. Застереження для неї стають безсилими. Вона поступово втрачає Божий страх. Вона сіє для свого тіла і від тіла пожне тління. Урожай посіяного людиною насіння незабаром дозріє. Вона нехтує святими Божими Заповідями. Її тілесне серце кам’яніє. Опір істині утверджує людину в беззаконні. Через те, що люди сіяли насіння зла, у допотопному світі процвітали беззаконня, злочини й насильство.
Усі мають знати про дії, які руйнують душу. Це відбувається не тому, що Бог видав якусь постанову проти людини. Не Він робить людину духовно сліпою. Бог дає людині достатньо світла й доказів, щоб вона могла відрізнити істину від омани. Проте Він не змушує людину приймати істину. Він залишає за нею свободу обирати добро або зло. Якщо людина відкидає свідчення, достатні, аби скеровувати її думки в правильному напрямку, й обирає зло, то їй легше буде повторити це вдруге. Утретє їй буде ще простіше піти від Бога й долучитися до сатани. Так вона продовжуватиме доти, доки не укорениться в гріху й не повірить неправді, яку плекатиме як істину. Її впертість принесла свій плід» (Е. Уайт. Рукопис 126, 1901 р. // Біблійний коментар АСД, т. 6, с. 1112).
#### Питання для обговорення:
`Що практично означає «виправити» брата по вірі, який згрішив? Як «масштаби» зробленого гріха впливають на процес виправлення? Чи означає це, що в деяких випадках (наприклад, «масштаби» гріха невеликі) виправлення не потрібне і все може залишатися, як і раніше? Обговоріть ваші відповіді.`
`Оскільки певний тягар люди повинні нести самі (Гал. 6:5), як віруючому визначити, чи може він допомогти іншому в конкретному випадку?`
`Як ваша церква виконує вказівки Павла, записані в Гал. 6? Що ви особисто можете зробити, аби покращити ситуацію?`
**Висновок**: Присутність Бога серед Його народу виявляється через Дух Христа, який панує в Церкві. Про це можна судити з того, як поширюється прощення й виправлення на членів, котрі схибили, як віруючі допомагають один одному у випробуваннях та звершують добрі діла один для одного й оточуючих.
|
PrJared/sabbath-school-lessons
|
src/uk/2017-03/13/07.md
|
Markdown
|
mit
| 4,130
|
#ifdef HAVE_CONFIG_H
#include "../ext_config.h"
#endif
#include <php.h>
#include "../php_ext.h"
#include "../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
#include "kernel/memory.h"
#include "kernel/fcall.h"
#include "kernel/operators.h"
/**
* Arithmetic operations
*/
ZEPHIR_INIT_CLASS(Test_Range) {
ZEPHIR_REGISTER_CLASS(Test, Range, test, range, test_range_method_entry, 0);
return SUCCESS;
}
PHP_METHOD(Test_Range, inclusive1) {
zval *_4 = NULL;
int ZEPHIR_LAST_CALL_STATUS;
zephir_nts_static zephir_fcall_cache_entry *_3 = NULL;
zval _0, _1, *_2 = NULL;
ZEPHIR_MM_GROW();
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 0);
ZEPHIR_SINIT_VAR(_1);
ZVAL_LONG(&_1, 10);
ZEPHIR_CALL_FUNCTION(&_2, "range", &_3, &_0, &_1);
zephir_check_call_status();
zephir_get_arrval(_4, _2);
RETURN_CTOR(_4);
}
PHP_METHOD(Test_Range, exclusive1) {
zval *_4 = NULL;
int ZEPHIR_LAST_CALL_STATUS;
zephir_nts_static zephir_fcall_cache_entry *_3 = NULL;
zval _0, _1, *_2 = NULL;
ZEPHIR_MM_GROW();
ZEPHIR_SINIT_VAR(_0);
ZVAL_LONG(&_0, 0);
ZEPHIR_SINIT_VAR(_1);
ZVAL_LONG(&_1, 10);
ZEPHIR_CALL_FUNCTION(&_2, "range", &_3, &_0, &_1);
zephir_check_call_status();
zephir_get_arrval(_4, _2);
RETURN_CTOR(_4);
}
|
imadige/zephirbuild
|
zephir/ext/test/range.zep.c
|
C
|
mit
| 1,311
|
import _curry2 from './_curry2.js';
import _xfBase from './_xfBase.js';
function XDropLast(n, xf) {
this.xf = xf;
this.pos = 0;
this.full = false;
this.acc = new Array(n);
}
XDropLast.prototype['@@transducer/init'] = _xfBase.init;
XDropLast.prototype['@@transducer/result'] = function(result) {
this.acc = null;
return this.xf['@@transducer/result'](result);
};
XDropLast.prototype['@@transducer/step'] = function(result, input) {
if (this.full) {
result = this.xf['@@transducer/step'](result, this.acc[this.pos]);
}
this.store(input);
return result;
};
XDropLast.prototype.store = function(input) {
this.acc[this.pos] = input;
this.pos += 1;
if (this.pos === this.acc.length) {
this.pos = 0;
this.full = true;
}
};
var _xdropLast = _curry2(function _xdropLast(n, xf) { return new XDropLast(n, xf); });
export default _xdropLast;
|
CrossEye/ramda
|
source/internal/_xdropLast.js
|
JavaScript
|
mit
| 874
|
class F001_Annotations {
{
@SuppressWarnings("all")
int i = 5;
@SuppressWarnings({"all", "non-existent"})
int more = 5;
@SuppressWarnings(value = "all")
int single = 5;
@SuppressWarnings(value = {"all", "non-existent"})
int full = 5;
}
@Override
public String toString() {
return null;
}
@SuppressWarnings("serial")
@Override
public int hashCode() {
return 0;
}
@SuppressWarnings("all")
void foo() {
}
}
|
rzwitserloot/lombok.ast
|
test/resources/idempotency/F001_Annotations.java
|
Java
|
mit
| 546
|
import {Component, ViewEncapsulation} from '@angular/core';
import {BaCard, BaAmChart} from '../../../../theme/components';
import {LineMapsService} from './lineMaps.service';
@Component({
selector: 'line-maps',
pipes: [],
providers: [LineMapsService],
encapsulation: ViewEncapsulation.None,
styles: [require('./lineMaps.scss')],
template: require('./lineMaps.html'),
directives: [BaCard, BaAmChart],
})
export class LineMaps {
chartData:Object;
constructor(private _lineMapsService:LineMapsService) {
this.chartData = this._lineMapsService.getData();
}
}
|
nvoleau/sondage
|
src/app/pages/maps/components/lineMaps/lineMaps.component.ts
|
TypeScript
|
mit
| 584
|
(function() {
var $, Builder, Events, SelfClosingTags, Tags, View, callAttachHook, docEl, exports, idCounter, jQuery, matches, matchesSelector, methodName, originalCleanData, _, _fn, _fn1, _i, _j, _len, _len1, _ref, _ref1,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
if (typeof require === 'function') {
_ = require('underscore-plus');
$ = jQuery = require('../vendor/jquery');
} else {
_ = window._, jQuery = window.jQuery;
$ = jQuery;
}
Tags = 'a abbr address article aside audio b bdi bdo blockquote body button canvas\
caption cite code colgroup datalist dd del details dfn dialog div dl dt em\
fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header html i\
iframe ins kbd label legend li main map mark menu meter nav noscript object\
ol optgroup option output p pre progress q rp rt ruby s samp script section\
select small span strong style sub summary sup table tbody td textarea tfoot\
th thead time title tr u ul var video area base br col command embed hr img\
input keygen link meta param source track wbr'.split(/\s+/);
SelfClosingTags = {};
'area base br col command embed hr img input keygen link meta param\
source track wbr'.split(/\s+/).forEach(function(tag) {
return SelfClosingTags[tag] = true;
});
Events = 'blur change click dblclick error focus input keydown\
keypress keyup load mousedown mousemove mouseout mouseover\
mouseup resize scroll select submit unload'.split(/\s+/);
docEl = document.documentElement;
matches = docEl.matchesSelector || docEl.mozMatchesSelector || docEl.webkitMatchesSelector || docEl.oMatchesSelector || docEl.msMatchesSelector;
matchesSelector = matches ? (function(elem, selector) {
return matches.call(elem[0], selector);
}) : (function(elem, selector) {
return elem.is(selector);
});
idCounter = 0;
View = (function(_super) {
__extends(View, _super);
View.builderStack = null;
Tags.forEach(function(tagName) {
return View[tagName] = function() {
var args, _ref;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return (_ref = this.currentBuilder).tag.apply(_ref, [tagName].concat(__slice.call(args)));
};
});
View.subview = function(name, view) {
return this.currentBuilder.subview(name, view);
};
View.text = function(string) {
return this.currentBuilder.text(string);
};
View.tag = function() {
var args, tagName, _ref;
tagName = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return (_ref = this.currentBuilder).tag.apply(_ref, [tagName].concat(__slice.call(args)));
};
View.raw = function(string) {
return this.currentBuilder.raw(string);
};
View.pushBuilder = function() {
var builder;
builder = new Builder;
if (this.builderStack == null) {
this.builderStack = [];
}
this.builderStack.push(builder);
return this.currentBuilder = builder;
};
View.popBuilder = function() {
this.currentBuilder = this.builderStack[this.builderStack.length - 2];
return this.builderStack.pop();
};
View.buildHtml = function(fn) {
var html, postProcessingSteps, _ref;
this.pushBuilder();
fn.call(this);
return _ref = this.popBuilder().buildHtml(), html = _ref[0], postProcessingSteps = _ref[1], _ref;
};
View.render = function(fn) {
var div, fragment, html, postProcessingSteps, step, _i, _len, _ref;
_ref = this.buildHtml(fn), html = _ref[0], postProcessingSteps = _ref[1];
div = document.createElement('div');
div.innerHTML = html;
fragment = $(div.childNodes);
for (_i = 0, _len = postProcessingSteps.length; _i < _len; _i++) {
step = postProcessingSteps[_i];
step(fragment);
}
return fragment;
};
function View() {
var args, element, html, postProcessingSteps, step, _i, _j, _len, _len1, _ref, _ref1;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
_ref = this.constructor.buildHtml(function() {
return this.content.apply(this, args);
}), html = _ref[0], postProcessingSteps = _ref[1];
jQuery.fn.init.call(this, html);
if (this.length !== 1) {
throw new Error("View markup must have a single root element");
}
this.wireOutlets(this);
this.bindEventHandlers(this);
jQuery.data(this[0], 'view', this);
_ref1 = this[0].getElementsByTagName('*');
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
element = _ref1[_i];
jQuery.data(element, 'view', this);
}
this[0].setAttribute('callAttachHooks', true);
for (_j = 0, _len1 = postProcessingSteps.length; _j < _len1; _j++) {
step = postProcessingSteps[_j];
step(this);
}
if (typeof this.initialize === "function") {
this.initialize.apply(this, args);
}
}
View.prototype.buildHtml = function(params) {
var html, postProcessingSteps, _ref;
this.constructor.builder = new Builder;
this.constructor.content(params);
_ref = this.constructor.builder.buildHtml(), html = _ref[0], postProcessingSteps = _ref[1];
this.constructor.builder = null;
return postProcessingSteps;
};
View.prototype.wireOutlets = function(view) {
var element, outlet, _i, _len, _ref;
_ref = view[0].querySelectorAll('[outlet]');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
element = _ref[_i];
outlet = element.getAttribute('outlet');
view[outlet] = $(element);
element.removeAttribute('outlet');
}
return void 0;
};
View.prototype.bindEventHandlers = function(view) {
var element, eventName, methodName, selector, _fn, _i, _j, _len, _len1, _ref;
for (_i = 0, _len = Events.length; _i < _len; _i++) {
eventName = Events[_i];
selector = "[" + eventName + "]";
_ref = view[0].querySelectorAll(selector);
_fn = function(element) {
var methodName;
methodName = element.getAttribute(eventName);
element = $(element);
return element.on(eventName, function(event) {
return view[methodName](event, element);
});
};
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
element = _ref[_j];
_fn(element);
}
if (matchesSelector(view, selector)) {
methodName = view[0].getAttribute(eventName);
(function(methodName) {
return view.on(eventName, function(event) {
return view[methodName](event, view);
});
})(methodName);
}
}
return void 0;
};
View.prototype.pushStack = function(elems) {
var ret;
ret = jQuery.merge(jQuery(), elems);
ret.prevObject = this;
ret.context = this.context;
return ret;
};
View.prototype.end = function() {
var _ref;
return (_ref = this.prevObject) != null ? _ref : jQuery(null);
};
View.prototype.command = function(commandName, selector, options, handler) {
return View.__super__.command.call(this, commandName, selector, options, handler);
};
View.prototype.preempt = function(eventName, handler) {
return View.__super__.preempt.call(this, eventName, handler);
};
return View;
})(jQuery);
Builder = (function() {
function Builder() {
this.document = [];
this.postProcessingSteps = [];
}
Builder.prototype.buildHtml = function() {
return [this.document.join(''), this.postProcessingSteps];
};
Builder.prototype.tag = function() {
var args, name, options;
name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
options = this.extractOptions(args);
this.openTag(name, options.attributes);
if (SelfClosingTags.hasOwnProperty(name)) {
if ((options.text != null) || (options.content != null)) {
throw new Error("Self-closing tag " + name + " cannot have text or content");
}
} else {
if (typeof options.content === "function") {
options.content();
}
if (options.text) {
this.text(options.text);
}
return this.closeTag(name);
}
};
Builder.prototype.openTag = function(name, attributes) {
var attributeName, attributePairs, attributesString, value;
attributePairs = (function() {
var _results;
_results = [];
for (attributeName in attributes) {
value = attributes[attributeName];
_results.push("" + attributeName + "=\"" + value + "\"");
}
return _results;
})();
attributesString = attributePairs.length ? " " + attributePairs.join(" ") : "";
return this.document.push("<" + name + attributesString + ">");
};
Builder.prototype.closeTag = function(name) {
return this.document.push("</" + name + ">");
};
Builder.prototype.text = function(string) {
var escapedString;
escapedString = string.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
return this.document.push(escapedString);
};
Builder.prototype.raw = function(string) {
return this.document.push(string);
};
Builder.prototype.subview = function(outletName, subview) {
var subviewId;
subviewId = "subview-" + (++idCounter);
this.tag('div', {
id: subviewId
});
return this.postProcessingSteps.push(function(view) {
view[outletName] = subview;
subview.parentView = view;
return view.find("div#" + subviewId).replaceWith(subview);
});
};
Builder.prototype.extractOptions = function(args) {
var arg, options, _i, _len;
options = {};
for (_i = 0, _len = args.length; _i < _len; _i++) {
arg = args[_i];
switch (typeof arg) {
case 'function':
options.content = arg;
break;
case 'string':
case 'number':
options.text = arg.toString();
break;
default:
options.attributes = arg;
}
}
return options;
};
return Builder;
})();
callAttachHook = function(element) {
var child, elementsWithHooks, onDom, _i, _j, _len, _len1, _ref, _ref1, _results;
if (!(element instanceof jQuery && element[0])) {
return;
}
onDom = (typeof element.parents === "function" ? element.parents('html').length : void 0) > 0;
elementsWithHooks = [];
if (element[0].getAttribute('callAttachHooks')) {
elementsWithHooks.push(element[0]);
}
if (onDom) {
_ref = element[0].querySelectorAll('[callAttachHooks]');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
child = _ref[_i];
elementsWithHooks.push(child);
}
}
_results = [];
for (_j = 0, _len1 = elementsWithHooks.length; _j < _len1; _j++) {
element = elementsWithHooks[_j];
_results.push((_ref1 = $(element).view()) != null ? typeof _ref1.afterAttach === "function" ? _ref1.afterAttach(onDom) : void 0 : void 0);
}
return _results;
};
_ref = ['append', 'prepend', 'after', 'before'];
_fn = function(methodName) {
var originalMethod;
originalMethod = $.fn[methodName];
return jQuery.fn[methodName] = function() {
var arg, args, flatArgs, result, _j, _len1, _ref1;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
flatArgs = (_ref1 = []).concat.apply(_ref1, args);
result = originalMethod.apply(this, flatArgs);
for (_j = 0, _len1 = flatArgs.length; _j < _len1; _j++) {
arg = flatArgs[_j];
callAttachHook(arg);
}
return result;
};
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
methodName = _ref[_i];
_fn(methodName);
}
_ref1 = ['prependTo', 'appendTo', 'insertAfter', 'insertBefore'];
_fn1 = function(methodName) {
var originalMethod;
originalMethod = jQuery.fn[methodName];
return jQuery.fn[methodName] = function() {
var args, result;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
result = originalMethod.apply(this, args);
callAttachHook(this);
return result;
};
};
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
methodName = _ref1[_j];
_fn1(methodName);
}
originalCleanData = jQuery.cleanData;
jQuery.cleanData = function(elements) {
var element, view, _k, _len2;
for (_k = 0, _len2 = elements.length; _k < _len2; _k++) {
element = elements[_k];
view = $(element).view();
if (view && (view != null ? view[0] : void 0) === element) {
if (typeof view.beforeRemove === "function") {
view.beforeRemove();
}
}
}
return originalCleanData(elements);
};
$.fn.view = function() {
return this.data('view');
};
$.fn.views = function() {
return this.toArray().map(function(elt) {
var $elt, _ref2;
$elt = $(elt);
return (_ref2 = $elt.view()) != null ? _ref2 : $elt;
});
};
$.fn.containingView = function() {
var element, view;
element = this;
while (element.length > 0) {
if (view = element.data('view')) {
return view;
}
element = element.parent();
}
};
$.fn.scrollBottom = function(newValue) {
if (newValue != null) {
return this.scrollTop(newValue - this.height());
} else {
return this.scrollTop() + this.height();
}
};
$.fn.scrollDown = function() {
return this.scrollTop(this.scrollTop() + $(window).height() / 20);
};
$.fn.scrollUp = function() {
return this.scrollTop(this.scrollTop() - $(window).height() / 20);
};
$.fn.scrollToTop = function() {
return this.scrollTop(0);
};
$.fn.scrollToBottom = function() {
return this.scrollTop(this.prop('scrollHeight'));
};
$.fn.scrollRight = function(newValue) {
if (newValue != null) {
return this.scrollLeft(newValue - this.width());
} else {
return this.scrollLeft() + this.width();
}
};
$.fn.pageUp = function() {
return this.scrollTop(this.scrollTop() - this.height());
};
$.fn.pageDown = function() {
return this.scrollTop(this.scrollTop() + this.height());
};
$.fn.isOnDom = function() {
return this.closest(document.body).length === 1;
};
$.fn.isVisible = function() {
return !this.isHidden();
};
$.fn.isHidden = function() {
var style;
style = this[0].style;
if (style.display === 'none' || !this.isOnDom()) {
return true;
} else if (style.display) {
return false;
} else {
return getComputedStyle(this[0]).display === 'none';
}
};
$.fn.isDisabled = function() {
return !!this.attr('disabled');
};
$.fn.enable = function() {
return this.removeAttr('disabled');
};
$.fn.disable = function() {
return this.attr('disabled', 'disabled');
};
$.fn.insertAt = function(index, element) {
var target;
target = this.children(":eq(" + index + ")");
if (target.length) {
return $(element).insertBefore(target);
} else {
return this.append(element);
}
};
$.fn.removeAt = function(index) {
return this.children(":eq(" + index + ")").remove();
};
$.fn.indexOf = function(child) {
return this.children().toArray().indexOf($(child)[0]);
};
$.fn.containsElement = function(element) {
return (element[0].compareDocumentPosition(this[0]) & 8) === 8;
};
$.fn.preempt = function(eventName, handler) {
var eventNameWithoutNamespace, handlers, wrappedHandler, _ref2,
_this = this;
wrappedHandler = function() {
var args, e;
e = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (handler.apply(null, [e].concat(__slice.call(args))) === false) {
return e.stopImmediatePropagation();
}
};
this.on(eventName, wrappedHandler);
eventNameWithoutNamespace = eventName.split('.')[0];
handlers = (_ref2 = this.handlers()[eventNameWithoutNamespace]) != null ? _ref2 : [];
handlers.unshift(handlers.pop());
return {
off: function() {
return _this.off(eventName, wrappedHandler);
}
};
};
$.fn.handlers = function(eventName) {
var handlers, _ref2, _ref3;
handlers = this.length ? (_ref2 = $._data(this[0], 'events')) != null ? _ref2 : {} : {};
if (arguments.length === 1) {
handlers = (_ref3 = handlers[eventName]) != null ? _ref3 : [];
}
return handlers;
};
$.fn.hasParent = function() {
return this.parent()[0] != null;
};
$.fn.hasFocus = function() {
return this.is(':focus') || this.is(':has(:focus)');
};
$.fn.flashError = function() {
var removeErrorClass,
_this = this;
this.addClass('error');
removeErrorClass = function() {
return _this.removeClass('error');
};
return window.setTimeout(removeErrorClass, 300);
};
$.fn.trueHeight = function() {
return this[0].getBoundingClientRect().height;
};
$.fn.trueWidth = function() {
return this[0].getBoundingClientRect().width;
};
$.fn.document = function(eventName, docString) {
var eventDescriptions;
eventDescriptions = {};
eventDescriptions[eventName] = docString;
if (!this.data('documentation')) {
this.data('documentation', {});
}
return _.extend(this.data('documentation'), eventDescriptions);
};
$.fn.events = function() {
var documentation, eventName, events, _ref2, _ref3;
documentation = (_ref2 = this.data('documentation')) != null ? _ref2 : {};
events = {};
for (eventName in this.handlers()) {
events[eventName] = (_ref3 = documentation[eventName]) != null ? _ref3 : null;
}
if (this.hasParent()) {
return _.extend(this.parent().events(), events);
} else {
return events;
}
};
$.fn.command = function(eventName, selector, options, handler) {
if (options == null) {
handler = selector;
selector = null;
} else if (handler == null) {
handler = options;
options = null;
}
if ((selector != null) && typeof selector === 'object') {
options = selector;
selector = null;
}
this.document(eventName, _.humanizeEventName(eventName, options != null ? options['doc'] : void 0));
return this.on(eventName, selector, options != null ? options['data'] : void 0, handler);
};
$.fn.iconSize = function(size) {
return this.width(size).height(size).css('font-size', size);
};
$.fn.intValue = function() {
return parseInt(this.text());
};
$.Event.prototype.abortKeyBinding = function() {};
$.Event.prototype.currentTargetView = function() {
return $(this.currentTarget).containingView();
};
$.Event.prototype.targetView = function() {
return $(this.target).containingView();
};
exports = exports != null ? exports : this;
exports.View = View;
exports.jQuery = jQuery;
exports.$ = $;
exports.$$ = function(fn) {
return View.render.call(View, fn);
};
exports.$$$ = function(fn) {
return View.buildHtml.call(View, fn)[0];
};
}).call(this);
|
atom/space-pen
|
dist/space-pen.js
|
JavaScript
|
mit
| 19,758
|
<?php
/**
* Created by PhpStorm.
* User: faustos
* Date: 31.03.14
* Time: 21:28
*/
namespace Tixi\ApiBundle\Shared\DataGrid\Tile;
use Tixi\ApiBundle\Shared\DataGrid\DataGridOutputState;
use Tixi\ApiBundle\Tile\AbstractTile;
/**
* Class DataGridRowTableTile
* @package Tixi\ApiBundle\Shared\DataGrid\Tile
*/
class DataGridRowTableTile extends AbstractTile{
protected $dataGridOutputState;
/**
* @param DataGridOutputState $dataGridOutputState
*/
public function __construct(DataGridOutputState $dataGridOutputState) {
$this->dataGridOutputState = $dataGridOutputState;
}
/**
* @return array
*/
public function getViewParameters()
{
return array('gridState'=>$this->dataGridOutputState);
}
/**
* @return mixed|string
*/
public function getTemplateName()
{
return 'TixiApiBundle:Tile:datagridrowstable.html.twig';
}
/**
* @return mixed|string
*/
public function getName()
{
return 'datagridrowstable';
}
}
|
TIXI24/sfitixi
|
src/Tixi/ApiBundle/Shared/DataGrid/Tile/DataGridRowTableTile.php
|
PHP
|
mit
| 1,055
|
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the -uacomment option."""
from test_framework.test_framework import PivxTestFramework
from test_framework.util import assert_equal
class UacommentTest(PivxTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
def run_test(self):
self.log.info("test multiple -uacomment")
test_uacomment = self.nodes[0].getnetworkinfo()["subversion"][-12:-1]
assert_equal(test_uacomment, "(testnode0)")
self.restart_node(0, ["-uacomment=foo"])
foo_uacomment = self.nodes[0].getnetworkinfo()["subversion"][-17:-1]
assert_equal(foo_uacomment, "(testnode0; foo)")
self.log.info("test -uacomment max length")
self.stop_node(0)
expected = "exceeds maximum length (256). Reduce the number or size of uacomments."
self.assert_start_raises_init_error(0, ["-uacomment=" + 'a' * 256], expected)
self.log.info("test -uacomment unsafe characters")
for unsafe_char in ['/', ':', '(', ')']:
expected = "User Agent comment (" + unsafe_char + ") contains unsafe characters"
self.assert_start_raises_init_error(0, ["-uacomment=" + unsafe_char], expected)
if __name__ == '__main__':
UacommentTest().main()
|
Mrs-X/PIVX
|
test/functional/feature_uacomment.py
|
Python
|
mit
| 1,480
|
module.exports = require('regenerate')().addRange(0x10350, 0x1037A);
|
Engineering-Robert/personal-website
|
plugins/gatsby-plugin-feed-custom/node_modules/regenerate-unicode-properties/Script/Old_Permic.js
|
JavaScript
|
mit
| 69
|
<p>Welcome</p>
|
przemek-nowicki/widget-project
|
src/home/home.ctrl.html
|
HTML
|
mit
| 14
|
# -*- python -*-
# Copyright (C) 2009 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import gdb
import os
import os.path
pythondir = '/mingw32tdm/share/gcc-4.5.2/python'
libdir = '/mingw32tdm/lib/gcc/mingw32/4.5.2'
# This file might be loaded when there is no current objfile. This
# can happen if the user loads it manually. In this case we don't
# update sys.path; instead we just hope the user managed to do that
# beforehand.
if gdb.current_objfile () is not None:
# Update module path. We want to find the relative path from libdir
# to pythondir, and then we want to apply that relative path to the
# directory holding the objfile with which this file is associated.
# This preserves relocatability of the gcc tree.
# Do a simple normalization that removes duplicate separators.
pythondir = os.path.normpath (pythondir)
libdir = os.path.normpath (libdir)
prefix = os.path.commonprefix ([libdir, pythondir])
# In some bizarre configuration we might have found a match in the
# middle of a directory name.
if prefix[-1] != '/':
prefix = os.path.dirname (prefix) + '/'
# Strip off the prefix.
pythondir = pythondir[len (prefix):]
libdir = libdir[len (prefix):]
# Compute the ".."s needed to get from libdir to the prefix.
dotdots = ('..' + os.sep) * len (libdir.split (os.sep))
objfile = gdb.current_objfile ().filename
dir = os.path.join (os.path.dirname (objfile), dotdots, pythondir)
if not dir in sys.path:
sys.path.insert(0, dir)
# Load the pretty-printers.
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (gdb.current_objfile ())
|
ljnissen/shop_engine
|
mingw/lib/gcc/mingw32/4.5.2/libstdc++.dll.a-gdb.py
|
Python
|
mit
| 2,316
|
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright(C) 2022 Marvell.
*/
#include "cn10k_worker.h"
#include "cnxk_eventdev.h"
#include "cnxk_worker.h"
#define R(name, flags) \
SSO_CMN_DEQ_SEG_BURST(cn10k_sso_hws_deq_seg_burst_##name, \
cn10k_sso_hws_deq_seg_##name, flags) \
SSO_CMN_DEQ_SEG_BURST(cn10k_sso_hws_reas_deq_seg_burst_##name, \
cn10k_sso_hws_reas_deq_seg_##name, flags | NIX_RX_REAS_F)
NIX_RX_FASTPATH_MODES_64_79
#undef R
|
john-mcnamara-intel/dpdk
|
drivers/event/cnxk/deq/cn10k/deq_64_79_seg_burst.c
|
C
|
mit
| 546
|
/*
CryptoJS v3.1.2
enc-base64.js
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
|
edewit/sync-app
|
www/lib/fh-js-sdk/libs/cryptojs/cryptojs-enc-base64.js
|
JavaScript
|
mit
| 2,871
|
(function ($) {
/* -------- *
* DOM LOAD *
* -------- */
$(document).ready(function() {
// Slider
$('.slider').slider({full_width: true});
// Carousel
$('.carousel.carousel-slider').carousel({full_width: true});
$('.carousel').carousel();
});
}(jQuery));
|
si-quimera/avante
|
webroot/js/pages/js_media.js
|
JavaScript
|
mit
| 285
|
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
//sidebar
.state('news', {
url: "/news",
abstract: true,
templateUrl: "templates/sidebar-menu.html"
})
// Blog page
.state('news.home', {
url: "/home",
cache : false,
views: {
'menuWorPress' :{
templateUrl: "templates/home.html",
controller: "HomeCtrl"
}
}
})
// articles page wordpress
.state('news.post', {
url: "/post/:catId/:offset/:index/:type",
views: {
'menuWorPress' :{
templateUrl: "templates/post.html",
controller: "PostCtrl"
}
}
})
// Blog page
.state('news.categories', {
url: "/categories",
views: {
'menuWorPress' :{
templateUrl: "templates/categories.html",
controller: "CategoriesCtrl"
}
}
})
// Blog page
.state('news.category', {
url: "/category/:category/:categoryName",
cache : false,
views: {
'menuWorPress' :{
templateUrl: "templates/home.html",
controller: "CategoryCtrl"
}
}
})
// Blog page
.state('news.search', {
url: "/search",
cache : false,
views: {
'menuWorPress' :{
templateUrl: "templates/search.html",
controller: "SearchCtrl"
}
}
})
.state('news.settings', {
url: "/settings",
views: {
'menuWorPress' :{
templateUrl: "templates/settings.html",
controller: "SettingsCtrl"
}
}
})
.state('news.contact', {
url: "/contact",
views: {
'menuWorPress' :{
templateUrl: "templates/contact.html",
controller: "ContactCtrl"
}
}
})
.state('news.about', {
url: "/about",
views: {
'menuWorPress' :{
templateUrl: "templates/about.html",
controller: "AboutCtrl"
}
}
})
.state('news.admob', {
url: "/admob",
views: {
'menuWorPress' :{
templateUrl: "templates/admob.html",
controller: "AdmobCtrl"
}
}
})
$urlRouterProvider.otherwise("/news/home");
})
|
bipinu2/AfnaiNews
|
www/js/router.js
|
JavaScript
|
mit
| 2,203
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Runtime.CompilerServices;
#if SIGN
[assembly: InternalsVisibleTo("Microsoft.R.Host.Client, PublicKey=002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")]
[assembly: InternalsVisibleTo("Microsoft.R.Common.Core.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")]
[assembly: InternalsVisibleTo("Microsoft.VisualStudio.R.Package.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")]
[assembly: InternalsVisibleTo("Microsoft.VisualStudio.R.Interactive.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")]
#else
[assembly: InternalsVisibleTo("Microsoft.R.Host.Client")]
[assembly: InternalsVisibleTo("Microsoft.R.Common.Core.Test")]
[assembly: InternalsVisibleTo("Microsoft.VisualStudio.R.Package.Test")]
[assembly: InternalsVisibleTo("Microsoft.VisualStudio.R.Interactive.Test")]
#endif
|
AlexanderSher/RTVS
|
src/Common/Core/Impl/Properties/AssemblyInfo.cs
|
C#
|
mit
| 2,084
|
/* Copyright (c) 2016 Nordic Semiconductor. All Rights Reserved.
*
* The information contained herein is property of Nordic Semiconductor ASA.
* Terms and conditions of usage are described in detail in NORDIC
* SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
*
* Licensees are granted free, non-transferable use of the information. NO
* WARRANTY of ANY KIND is provided. This heading must NOT be removed from
* the file.
*
*/
#include "nrf_drv_adc.h"
#include "app_error.h"
#include "es_battery_voltage.h"
static uint16_t m_batt_lvl_in_milli_volts;
#define ADC_REF_VOLTAGE_IN_MILLIVOLTS 600 // /< Reference voltage (in milli volts) used by ADC while doing conversion.
#define DIODE_FWD_VOLT_DROP_MILLIVOLTS 270 // /< Typical forward voltage drop of the diode (Part no: SD103ATW-7-F) that is connected in series with the voltage supply. This is the voltage drop when the forward current is 1mA. Source: Data sheet of 'SURFACE MOUNT SCHOTTKY BARRIER DIODE ARRAY' available at www.diodes.com.
#define ADC_RES_10BIT 1024 // /< Maximum digital value for 10-bit ADC conversion.
#define ADC_PRE_SCALING_COMPENSATION 6 // /< The ADC is configured to use VDD with 1/3 prescaling as input. And hence the result of conversion is to be multiplied by 3 to get the actual value of the battery voltage.
#define ADC_REF_VBG_VOLTAGE_IN_MILLIVOLTS 1200 // /< Value in millivolts for voltage used as reference in ADC conversion on NRF51.
#define ADC_INPUT_PRESCALER 3 // /< Input prescaler for ADC convestion on NRF51.
static nrf_adc_value_t adc_buf[1];
#define ADC_RESULT_IN_MILLI_VOLTS(ADC_VALUE) \
((((ADC_VALUE) *ADC_REF_VBG_VOLTAGE_IN_MILLIVOLTS) / ADC_RES_10BIT) * ADC_INPUT_PRESCALER)
static void adc_event_handler(nrf_drv_adc_evt_t const * p_event)
{
if (p_event->type == NRF_DRV_ADC_EVT_DONE)
{
nrf_adc_value_t adc_result;
uint32_t err_code;
adc_result = p_event->data.done.p_buffer[0];
err_code = nrf_drv_adc_buffer_convert(p_event->data.done.p_buffer, 1);
APP_ERROR_CHECK(err_code);
m_batt_lvl_in_milli_volts = ADC_RESULT_IN_MILLI_VOLTS(adc_result) +
DIODE_FWD_VOLT_DROP_MILLIVOLTS;
}
}
void es_battery_voltage_init(void)
{
ret_code_t err_code = nrf_drv_adc_init(NULL, adc_event_handler);
APP_ERROR_CHECK(err_code);
static nrf_drv_adc_channel_t channel = NRF_DRV_ADC_DEFAULT_CHANNEL(
NRF_ADC_CONFIG_INPUT_DISABLED);
channel.config.config.input = (uint32_t)NRF_ADC_CONFIG_SCALING_SUPPLY_ONE_THIRD;
nrf_drv_adc_channel_enable(&channel);
err_code = nrf_drv_adc_buffer_convert(&adc_buf[0], 1);
APP_ERROR_CHECK(err_code);
nrf_drv_adc_sample();
}
void es_battery_voltage_get(uint16_t * p_vbatt)
{
*p_vbatt = m_batt_lvl_in_milli_volts;
if (!nrf_adc_is_busy())
{
nrf_drv_adc_sample();
}
}
|
lab11/nrf5x-base
|
sdk/nrf5_sdk_12.2.0/components/libraries/experimental_eddystone/es_battery_voltage_adc.c
|
C
|
mit
| 3,002
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreRoot.h"
#include "OgreGLPlugin.h"
#ifndef OGRE_STATIC_LIB
namespace Ogre {
static GLPlugin* plugin;
extern "C" void _OgreGLExport dllStartPlugin(void) throw()
{
plugin = new GLPlugin();
Root::getSingleton().installPlugin(plugin);
}
extern "C" void _OgreGLExport dllStopPlugin(void)
{
Root::getSingleton().uninstallPlugin(plugin);
delete plugin;
}
}
#endif
|
xsilium-frameworks/xsilium-engine
|
Library/Ogre/RenderSystems/GL/src/OgreGLEngineDll.cpp
|
C++
|
mit
| 1,775
|
<?php
namespace GingerPayments\Payment\Order;
final class Extra
{
/**
* @var array|null
*/
private $extra;
/**
* @param array $details
* @return Extra
*/
public static function fromArray(array $details)
{
return new static($details);
}
/**
* @return array
*/
public function toArray()
{
return $this->extra();
}
/**
* @return array|null
*/
public function extra()
{
return $this->extra;
}
/**
* @param array $extra
*/
private function __construct(array $extra = null)
{
$this->extra = $extra;
}
}
|
gingerpayments/ginger-opencart
|
upload/system/library/gingerpayments/ginger-php/src/Order/Extra.php
|
PHP
|
mit
| 662
|
import {
GraphQLScalarType,
GraphQLFieldResolver,
GraphQLTypeResolver,
GraphQLIsTypeOfFn,
} from 'graphql';
import { makeExecutableSchemaWithCacheControlSupport } from './cacheControlSupport';
import { CacheScope } from '../';
import { collectCacheControlHints } from './collectCacheControlHints';
export interface GraphQLResolvers {
[fieldName: string]: (() => any) | GraphQLResolverObject | GraphQLScalarType;
}
export type GraphQLResolverObject = {
[fieldName: string]: GraphQLFieldResolver<any, any> | GraphQLResolverOptions;
};
export interface GraphQLResolverOptions {
resolve?: GraphQLFieldResolver<any, any>;
subscribe?: GraphQLFieldResolver<any, any>;
__resolveType?: GraphQLTypeResolver<any, any>;
__isTypeOf?: GraphQLIsTypeOfFn<any, any>;
}
describe('dynamic cache control', () => {
it('should set the maxAge for a field from a dynamic cache hint', async () => {
const typeDefs = `
type Query {
droid(id: ID!): Droid
}
type Droid {
id: ID!
name: String!
}
`;
const resolvers: GraphQLResolvers = {
Query: {
droid: (_source, _args, _context, { cacheControl }) => {
cacheControl.setCacheHint({ maxAge: 60 });
return {
id: 2001,
name: 'R2-D2',
};
},
},
};
const schema = makeExecutableSchemaWithCacheControlSupport({
typeDefs,
resolvers,
});
const hints = await collectCacheControlHints(
schema,
`
query {
droid(id: 2001) {
name
}
}
`,
{ defaultMaxAge: 10 },
);
expect(hints).toContainEqual({ path: ['droid'], maxAge: 60 });
});
it('should set the scope for a field from a dynamic cache hint', async () => {
const typeDefs = `
type Query {
droid(id: ID!): Droid @cacheControl(maxAge: 60)
}
type Droid {
id: ID!
name: String!
}
`;
const resolvers: GraphQLResolvers = {
Query: {
droid: (_source, _args, _context, { cacheControl }) => {
cacheControl.setCacheHint({ scope: CacheScope.Private });
return {
id: 2001,
name: 'R2-D2',
};
},
},
};
const schema = makeExecutableSchemaWithCacheControlSupport({
typeDefs,
resolvers,
});
const hints = await collectCacheControlHints(
schema,
`
query {
droid(id: 2001) {
name
}
}
`,
{ defaultMaxAge: 10 },
);
expect(hints).toContainEqual({
path: ['droid'],
maxAge: 60,
scope: CacheScope.Private,
});
});
it('should override the maxAge set for a field from a dynamic cache hint', async () => {
const typeDefs = `
type Query {
droid(id: ID!): Droid @cacheControl(maxAge: 60)
}
type Droid {
id: ID!
name: String!
}
`;
const resolvers: GraphQLResolvers = {
Query: {
droid: (_source, _args, _context, { cacheControl }) => {
cacheControl.setCacheHint({ maxAge: 120 });
return {
id: 2001,
name: 'R2-D2',
};
},
},
};
const schema = makeExecutableSchemaWithCacheControlSupport({
typeDefs,
resolvers,
});
const hints = await collectCacheControlHints(
schema,
`
query {
droid(id: 2001) {
name
}
}
`,
{ defaultMaxAge: 10 },
);
expect(hints).toContainEqual({ path: ['droid'], maxAge: 120 });
});
});
|
AntonyThorpe/knockout-apollo
|
tests/node_modules/apollo-cache-control/src/__tests__/dynamicCacheControl.test.ts
|
TypeScript
|
mit
| 3,655
|
class Key;
class Value;
class SortAlgorithm;
class DefaultSort;
class T;
class X;
class Y;
class Bar;
class Foo {
template<class Bar> void fum(int i);
};
// TEMPLATE_STRUCT
template<class Key, class Value, class SortAlgorithm=DefaultSort>
struct Map
{
Key* keys;
Value* values;
SortAlgorithm* sortAlgorithm;
Map();
};
// TEMPLATE_CLASS
template<class T> class nonVector {
private:
T* head;
public:
nonVector() { head =new T(); }
int length() { return 1; }
const T& first();
};
// TEMPLATE_UNION
template<class X, class Y, int size=16>
union ArrayOverlay {
public:
X x[size];
Y y[size];
static int<X,Y> numArrays;
};
// TEMPLATE_METHODS
class TemplateContainer {
// these are in an enclosing class
template<class Bar> void fum(int i);
template<int> void scrum(void) {};
};
// TEMPLATE_FUNCTION
template<class T> const T& nonVector<T>::first() const
{
return *head;
}
template<class X> bool IsGreaterThan(X,X);
template<class Bar> void Foo::fum(int i) {}
// TEMPLATE_VARIABLES
template <bool threads, int inst> char* default_alloc_template<threads, inst>::S_start_free = 0;
// an instantiation, not a template:
complex<float> cf(0,0);
//template<class Language, class CharacterSet, class SortAlgorithm<CharacterSet> >
//Dictionary* TheSpellCheckDictionary;
int success;
|
Yuerr14/RepeatedFixes
|
RepeatedFixes/resources/cmodel/ITemplate.cpp
|
C++
|
mit
| 1,304
|
<section class="mainbar">
<section class="matter">
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="btn-group pull-right">
<button class="btn btn-info btn-form-md"
data-ng-click="vm.refresh()">
<i class="fa fa-refresh"></i>Refresh
</button>
<a class="btn btn-info btn-form-md"
href="#/product/new"><i class="fa fa-plus">
</i><span>Add Product</span>
</a>
<button class="btn btn-info btn-form-md"
ng-click="vm.cancel()" ng-disabled="!vm.canSave">
<i class="fa fa-undo"></i>Cancel
</button>
<button class="btn btn-success btn-form-md"
ng-click="vm.save()" ng-disabled="!vm.canSave">
<i class="fa fa-save"></i>Save
</button>
<button class="btn btn-danger btn-form-md" ng-click="vm.reset()">
<i class="fa fa-trash-o"></i>Reset
</button>
<!--Need ng-hide for show/hide animations-->
<span ng-show="vm.canSave" class="dissolve-animation ng-hide flag-haschanges">
<i class="fa fa-asterisk fa fa-asterisk-large" rel="tooltip" title="You have changes"></i>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="widget worange">
<div data-cc-widget-header title="Products"></div>
<div class="widget-content text-left text-info">
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Supplier</th>
<th>Unit Price</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="p in vm.products" ng-click="vm.gotoProduct(p)" class="clickable EState {{p.entityAspect.entityState.name}}">
<td>{{p.productName}}</td>
<td>{{p.category.categoryName}}</td>
<td>{{p.supplier.companyName}}</td>
<td>{{p.unitPrice | currency}}</td>
</tr>
</tbody>
</table>
</div>
<div class="widget-foot">
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
</section>
</section>
|
kyroskoh/breeze.js.samples
|
net/ngNorthwind/src/client/app/products/products.html
|
HTML
|
mit
| 3,353
|
import { expect } from 'chai';
import votesReducer from './';
describe('votesReducer', () => {
describe('#votesReducer()', () => {
it('should increment party votes by 1', () => {
const newState = votesReducer({ PARTY_CODE: 25 }, { type: 'VOTE', partyCode: 'PARTY_CODE' });
expect(newState).to.deep.equal({ PARTY_CODE: 26 });
});
});
});
|
aruberto/political-party-app
|
stages/stage-4.3/reducers/test.js
|
JavaScript
|
mit
| 364
|
class AddIndicesToForeignKeys < ActiveRecord::Migration
def change
add_index :anchor_url_certs, :anchor_url_id
add_index :anchor_urls, :trusted_anchor_id
add_index :auth_certs, :security_server_id
add_index :ca_infos, :top_ca_id
add_index :ca_infos, :intermediate_ca_id
add_index :central_services, :target_service_id
add_index :configuration_signing_keys, :configuration_source_id
add_index :configuration_sources, :active_key_id
add_index :global_group_members, :global_group_id
add_index :global_group_members, :group_member_id
add_index :ocsp_infos, :ca_info_id
add_index :requests, :security_server_id
add_index :requests, :sec_serv_user_id
add_index :requests, :request_processing_id
add_index :security_server_client_names, :client_identifier_id
add_index :security_server_clients, :xroad_member_id
add_index :security_server_clients, :member_class_id
add_index :security_server_clients, :server_client_id
add_index :security_servers, :xroad_member_id
# We cannot use default name here, as it will be too long (over 63 characters).
add_index :security_servers_security_categories, :security_server_id, :name => "index_server_category_to_server_id"
# We cannot use default name here, as it will be too long (over 63 characters).
add_index :security_servers_security_categories, :security_category_id, :name => "index_server_to_category"
add_index :server_clients, :security_server_id
add_index :server_clients, :security_server_client_id
end
end
|
ria-ee/X-Road
|
src/center-common/db/migrate/20150505101824_add_indices_to_foreign_keys.rb
|
Ruby
|
mit
| 1,558
|
<?php namespace Anomaly\Streams\Platform\Model;
use Anomaly\Streams\Platform\Support\Hydrator;
use Anomaly\Streams\Platform\Traits\FiresCallbacks;
use Illuminate\Contracts\Container\Container;
use Illuminate\Foundation\Bus\DispatchesJobs;
/**
* Class EloquentFactory
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <support@pyrocms.com>
* @author Ryan Thompson <ryan@pyrocms.com>
*/
class EloquentFactory
{
use DispatchesJobs;
use FiresCallbacks;
/**
* The hydrator utility.
*
* @var Hydrator
*/
protected $hydrator;
/**
* The service container.
*
* @var Container
*/
protected $container;
/**
* Create a new EloquentFactory instance.
*
* @param Hydrator $hydrator
* @param Container $container
*/
public function __construct(Hydrator $hydrator, Container $container)
{
$this->hydrator = $hydrator;
$this->container = $container;
}
/**
* Make a new EntryBuilder instance.
*
* @param $model
* @param string $method
* @return EloquentCriteria|null
*/
public function make($model, $method = 'get')
{
if (!$model) {
$model = EloquentModel::class;
}
/* @var EloquentModel $model */
$model = $this->container->make($model);
$criteria = $model->getCriteriaName();
$query = $model->newQuery();
return $this->container->make(
$criteria,
[
'query' => $query,
'method' => $method,
]
);
}
}
|
vileopratama/portal-toyotadjakarta
|
vendor/anomaly/streams-platform/src/Model/EloquentFactory.php
|
PHP
|
mit
| 1,629
|
@extends("layout")
@section("content")
{{ Form::open([
"url" => URL::full(),
"autocomplete" => "off"
]) }}
{{ Form::field([
"name" => "name",
"label" => "Name",
"form" => $form,
"placeholder" => "new group",
"value" => $group->name
])}}
@include("user/assign")
@include("resource/assign")
{{ Form::submit("save") }}
{{ Form::close() }}
@stop
@section("footer")
@parent
<script src="//polyfill.io"></script>
@stop
|
deannariddlespur/tutorial
|
app/views/group/edit.blade.php
|
PHP
|
mit
| 583
|
//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the MachO-specific dumper for llvm-objdump.
//
//===----------------------------------------------------------------------===//
#include "llvm-objdump.h"
#include "llvm-c/Disassembler.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Config/config.h"
#include "llvm/DebugInfo/DIContext.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/MachO.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cstring>
#include <system_error>
#if HAVE_CXXABI_H
#include <cxxabi.h>
#endif
using namespace llvm;
using namespace object;
static cl::opt<bool>
UseDbg("g",
cl::desc("Print line information from debug info if available"));
static cl::opt<std::string> DSYMFile("dsym",
cl::desc("Use .dSYM file for debug info"));
static cl::opt<bool> FullLeadingAddr("full-leading-addr",
cl::desc("Print full leading address"));
static cl::opt<bool> NoLeadingAddr("no-leading-addr",
cl::desc("Print no leading address"));
cl::opt<bool> llvm::UniversalHeaders("universal-headers",
cl::desc("Print Mach-O universal headers "
"(requires -macho)"));
cl::opt<bool>
llvm::ArchiveHeaders("archive-headers",
cl::desc("Print archive headers for Mach-O archives "
"(requires -macho)"));
cl::opt<bool>
ArchiveMemberOffsets("archive-member-offsets",
cl::desc("Print the offset to each archive member for "
"Mach-O archives (requires -macho and "
"-archive-headers)"));
cl::opt<bool>
llvm::IndirectSymbols("indirect-symbols",
cl::desc("Print indirect symbol table for Mach-O "
"objects (requires -macho)"));
cl::opt<bool>
llvm::DataInCode("data-in-code",
cl::desc("Print the data in code table for Mach-O objects "
"(requires -macho)"));
cl::opt<bool>
llvm::LinkOptHints("link-opt-hints",
cl::desc("Print the linker optimization hints for "
"Mach-O objects (requires -macho)"));
cl::opt<bool>
llvm::InfoPlist("info-plist",
cl::desc("Print the info plist section as strings for "
"Mach-O objects (requires -macho)"));
cl::opt<bool>
llvm::DylibsUsed("dylibs-used",
cl::desc("Print the shared libraries used for linked "
"Mach-O files (requires -macho)"));
cl::opt<bool>
llvm::DylibId("dylib-id",
cl::desc("Print the shared library's id for the dylib Mach-O "
"file (requires -macho)"));
cl::opt<bool>
llvm::NonVerbose("non-verbose",
cl::desc("Print the info for Mach-O objects in "
"non-verbose or numeric form (requires -macho)"));
cl::opt<bool>
llvm::ObjcMetaData("objc-meta-data",
cl::desc("Print the Objective-C runtime meta data for "
"Mach-O files (requires -macho)"));
cl::opt<std::string> llvm::DisSymName(
"dis-symname",
cl::desc("disassemble just this symbol's instructions (requires -macho"));
static cl::opt<bool> NoSymbolicOperands(
"no-symbolic-operands",
cl::desc("do not symbolic operands when disassembling (requires -macho)"));
static cl::list<std::string>
ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
cl::ZeroOrMore);
bool ArchAll = false;
static std::string ThumbTripleName;
static const Target *GetTarget(const MachOObjectFile *MachOObj,
const char **McpuDefault,
const Target **ThumbTarget) {
// Figure out the target triple.
if (TripleName.empty()) {
llvm::Triple TT("unknown-unknown-unknown");
llvm::Triple ThumbTriple = Triple();
TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
TripleName = TT.str();
ThumbTripleName = ThumbTriple.str();
}
// Get the target specific parser.
std::string Error;
const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
if (TheTarget && ThumbTripleName.empty())
return TheTarget;
*ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
if (*ThumbTarget)
return TheTarget;
errs() << "llvm-objdump: error: unable to get target for '";
if (!TheTarget)
errs() << TripleName;
else
errs() << ThumbTripleName;
errs() << "', see --version and --triple.\n";
return nullptr;
}
struct SymbolSorter {
bool operator()(const SymbolRef &A, const SymbolRef &B) {
uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue();
uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue();
return AAddr < BAddr;
}
};
// Types for the storted data in code table that is built before disassembly
// and the predicate function to sort them.
typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
typedef std::vector<DiceTableEntry> DiceTable;
typedef DiceTable::iterator dice_table_iterator;
// This is used to search for a data in code table entry for the PC being
// disassembled. The j parameter has the PC in j.first. A single data in code
// table entry can cover many bytes for each of its Kind's. So if the offset,
// aka the i.first value, of the data in code table entry plus its Length
// covers the PC being searched for this will return true. If not it will
// return false.
static bool compareDiceTableEntries(const DiceTableEntry &i,
const DiceTableEntry &j) {
uint16_t Length;
i.second.getLength(Length);
return j.first >= i.first && j.first < i.first + Length;
}
static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
unsigned short Kind) {
uint32_t Value, Size = 1;
switch (Kind) {
default:
case MachO::DICE_KIND_DATA:
if (Length >= 4) {
if (!NoShowRawInsn)
dumpBytes(makeArrayRef(bytes, 4), outs());
Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
outs() << "\t.long " << Value;
Size = 4;
} else if (Length >= 2) {
if (!NoShowRawInsn)
dumpBytes(makeArrayRef(bytes, 2), outs());
Value = bytes[1] << 8 | bytes[0];
outs() << "\t.short " << Value;
Size = 2;
} else {
if (!NoShowRawInsn)
dumpBytes(makeArrayRef(bytes, 2), outs());
Value = bytes[0];
outs() << "\t.byte " << Value;
Size = 1;
}
if (Kind == MachO::DICE_KIND_DATA)
outs() << "\t@ KIND_DATA\n";
else
outs() << "\t@ data in code kind = " << Kind << "\n";
break;
case MachO::DICE_KIND_JUMP_TABLE8:
if (!NoShowRawInsn)
dumpBytes(makeArrayRef(bytes, 1), outs());
Value = bytes[0];
outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
Size = 1;
break;
case MachO::DICE_KIND_JUMP_TABLE16:
if (!NoShowRawInsn)
dumpBytes(makeArrayRef(bytes, 2), outs());
Value = bytes[1] << 8 | bytes[0];
outs() << "\t.short " << format("%5u", Value & 0xffff)
<< "\t@ KIND_JUMP_TABLE16\n";
Size = 2;
break;
case MachO::DICE_KIND_JUMP_TABLE32:
case MachO::DICE_KIND_ABS_JUMP_TABLE32:
if (!NoShowRawInsn)
dumpBytes(makeArrayRef(bytes, 4), outs());
Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
outs() << "\t.long " << Value;
if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
outs() << "\t@ KIND_JUMP_TABLE32\n";
else
outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
Size = 4;
break;
}
return Size;
}
static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
std::vector<SectionRef> &Sections,
std::vector<SymbolRef> &Symbols,
SmallVectorImpl<uint64_t> &FoundFns,
uint64_t &BaseSegmentAddress) {
for (const SymbolRef &Symbol : MachOObj->symbols()) {
ErrorOr<StringRef> SymName = Symbol.getName();
if (std::error_code EC = SymName.getError())
report_fatal_error(EC.message());
if (!SymName->startswith("ltmp"))
Symbols.push_back(Symbol);
}
for (const SectionRef &Section : MachOObj->sections()) {
StringRef SectName;
Section.getName(SectName);
Sections.push_back(Section);
}
bool BaseSegmentAddressSet = false;
for (const auto &Command : MachOObj->load_commands()) {
if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
// We found a function starts segment, parse the addresses for later
// consumption.
MachO::linkedit_data_command LLC =
MachOObj->getLinkeditDataLoadCommand(Command);
MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
} else if (Command.C.cmd == MachO::LC_SEGMENT) {
MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
StringRef SegName = SLC.segname;
if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
BaseSegmentAddressSet = true;
BaseSegmentAddress = SLC.vmaddr;
}
}
}
}
static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
uint32_t n, uint32_t count,
uint32_t stride, uint64_t addr) {
MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
uint32_t nindirectsyms = Dysymtab.nindirectsyms;
if (n > nindirectsyms)
outs() << " (entries start past the end of the indirect symbol "
"table) (reserved1 field greater than the table size)";
else if (n + count > nindirectsyms)
outs() << " (entries extends past the end of the indirect symbol "
"table)";
outs() << "\n";
uint32_t cputype = O->getHeader().cputype;
if (cputype & MachO::CPU_ARCH_ABI64)
outs() << "address index";
else
outs() << "address index";
if (verbose)
outs() << " name\n";
else
outs() << "\n";
for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
if (cputype & MachO::CPU_ARCH_ABI64)
outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
else
outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
outs() << "LOCAL\n";
continue;
}
if (indirect_symbol ==
(MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
outs() << "LOCAL ABSOLUTE\n";
continue;
}
if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
outs() << "ABSOLUTE\n";
continue;
}
outs() << format("%5u ", indirect_symbol);
if (verbose) {
MachO::symtab_command Symtab = O->getSymtabLoadCommand();
if (indirect_symbol < Symtab.nsyms) {
symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
SymbolRef Symbol = *Sym;
ErrorOr<StringRef> SymName = Symbol.getName();
if (std::error_code EC = SymName.getError())
report_fatal_error(EC.message());
outs() << *SymName;
} else {
outs() << "?";
}
}
outs() << "\n";
}
}
static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
for (const auto &Load : O->load_commands()) {
if (Load.C.cmd == MachO::LC_SEGMENT_64) {
MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
for (unsigned J = 0; J < Seg.nsects; ++J) {
MachO::section_64 Sec = O->getSection64(Load, J);
uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
section_type == MachO::S_SYMBOL_STUBS) {
uint32_t stride;
if (section_type == MachO::S_SYMBOL_STUBS)
stride = Sec.reserved2;
else
stride = 8;
if (stride == 0) {
outs() << "Can't print indirect symbols for (" << Sec.segname << ","
<< Sec.sectname << ") "
<< "(size of stubs in reserved2 field is zero)\n";
continue;
}
uint32_t count = Sec.size / stride;
outs() << "Indirect symbols for (" << Sec.segname << ","
<< Sec.sectname << ") " << count << " entries";
uint32_t n = Sec.reserved1;
PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
}
}
} else if (Load.C.cmd == MachO::LC_SEGMENT) {
MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
for (unsigned J = 0; J < Seg.nsects; ++J) {
MachO::section Sec = O->getSection(Load, J);
uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
section_type == MachO::S_SYMBOL_STUBS) {
uint32_t stride;
if (section_type == MachO::S_SYMBOL_STUBS)
stride = Sec.reserved2;
else
stride = 4;
if (stride == 0) {
outs() << "Can't print indirect symbols for (" << Sec.segname << ","
<< Sec.sectname << ") "
<< "(size of stubs in reserved2 field is zero)\n";
continue;
}
uint32_t count = Sec.size / stride;
outs() << "Indirect symbols for (" << Sec.segname << ","
<< Sec.sectname << ") " << count << " entries";
uint32_t n = Sec.reserved1;
PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
}
}
}
}
}
static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
outs() << "Data in code table (" << nentries << " entries)\n";
outs() << "offset length kind\n";
for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
++DI) {
uint32_t Offset;
DI->getOffset(Offset);
outs() << format("0x%08" PRIx32, Offset) << " ";
uint16_t Length;
DI->getLength(Length);
outs() << format("%6u", Length) << " ";
uint16_t Kind;
DI->getKind(Kind);
if (verbose) {
switch (Kind) {
case MachO::DICE_KIND_DATA:
outs() << "DATA";
break;
case MachO::DICE_KIND_JUMP_TABLE8:
outs() << "JUMP_TABLE8";
break;
case MachO::DICE_KIND_JUMP_TABLE16:
outs() << "JUMP_TABLE16";
break;
case MachO::DICE_KIND_JUMP_TABLE32:
outs() << "JUMP_TABLE32";
break;
case MachO::DICE_KIND_ABS_JUMP_TABLE32:
outs() << "ABS_JUMP_TABLE32";
break;
default:
outs() << format("0x%04" PRIx32, Kind);
break;
}
} else
outs() << format("0x%04" PRIx32, Kind);
outs() << "\n";
}
}
static void PrintLinkOptHints(MachOObjectFile *O) {
MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
uint32_t nloh = LohLC.datasize;
outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
for (uint32_t i = 0; i < nloh;) {
unsigned n;
uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
i += n;
outs() << " identifier " << identifier << " ";
if (i >= nloh)
return;
switch (identifier) {
case 1:
outs() << "AdrpAdrp\n";
break;
case 2:
outs() << "AdrpLdr\n";
break;
case 3:
outs() << "AdrpAddLdr\n";
break;
case 4:
outs() << "AdrpLdrGotLdr\n";
break;
case 5:
outs() << "AdrpAddStr\n";
break;
case 6:
outs() << "AdrpLdrGotStr\n";
break;
case 7:
outs() << "AdrpAdd\n";
break;
case 8:
outs() << "AdrpLdrGot\n";
break;
default:
outs() << "Unknown identifier value\n";
break;
}
uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
i += n;
outs() << " narguments " << narguments << "\n";
if (i >= nloh)
return;
for (uint32_t j = 0; j < narguments; j++) {
uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
i += n;
outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
if (i >= nloh)
return;
}
}
}
static void PrintDylibs(MachOObjectFile *O, bool JustId) {
unsigned Index = 0;
for (const auto &Load : O->load_commands()) {
if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
(!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
Load.C.cmd == MachO::LC_LOAD_DYLIB ||
Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
if (dl.dylib.name < dl.cmdsize) {
const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
if (JustId)
outs() << p << "\n";
else {
outs() << "\t" << p;
outs() << " (compatibility version "
<< ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
<< ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
<< (dl.dylib.compatibility_version & 0xff) << ",";
outs() << " current version "
<< ((dl.dylib.current_version >> 16) & 0xffff) << "."
<< ((dl.dylib.current_version >> 8) & 0xff) << "."
<< (dl.dylib.current_version & 0xff) << ")\n";
}
} else {
outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
if (Load.C.cmd == MachO::LC_ID_DYLIB)
outs() << "LC_ID_DYLIB ";
else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
outs() << "LC_LOAD_DYLIB ";
else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
outs() << "LC_LOAD_WEAK_DYLIB ";
else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
outs() << "LC_LAZY_LOAD_DYLIB ";
else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
outs() << "LC_REEXPORT_DYLIB ";
else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
outs() << "LC_LOAD_UPWARD_DYLIB ";
else
outs() << "LC_??? ";
outs() << "command " << Index++ << "\n";
}
}
}
}
typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
static void CreateSymbolAddressMap(MachOObjectFile *O,
SymbolAddressMap *AddrMap) {
// Create a map of symbol addresses to symbol names.
for (const SymbolRef &Symbol : O->symbols()) {
SymbolRef::Type ST = Symbol.getType();
if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
ST == SymbolRef::ST_Other) {
uint64_t Address = Symbol.getValue();
ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
if (std::error_code EC = SymNameOrErr.getError())
report_fatal_error(EC.message());
StringRef SymName = *SymNameOrErr;
if (!SymName.startswith(".objc"))
(*AddrMap)[Address] = SymName;
}
}
}
// GuessSymbolName is passed the address of what might be a symbol and a
// pointer to the SymbolAddressMap. It returns the name of a symbol
// with that address or nullptr if no symbol is found with that address.
static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
const char *SymbolName = nullptr;
// A DenseMap can't lookup up some values.
if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
StringRef name = AddrMap->lookup(value);
if (!name.empty())
SymbolName = name.data();
}
return SymbolName;
}
static void DumpCstringChar(const char c) {
char p[2];
p[0] = c;
p[1] = '\0';
outs().write_escaped(p);
}
static void DumpCstringSection(MachOObjectFile *O, const char *sect,
uint32_t sect_size, uint64_t sect_addr,
bool print_addresses) {
for (uint32_t i = 0; i < sect_size; i++) {
if (print_addresses) {
if (O->is64Bit())
outs() << format("%016" PRIx64, sect_addr + i) << " ";
else
outs() << format("%08" PRIx64, sect_addr + i) << " ";
}
for (; i < sect_size && sect[i] != '\0'; i++)
DumpCstringChar(sect[i]);
if (i < sect_size && sect[i] == '\0')
outs() << "\n";
}
}
static void DumpLiteral4(uint32_t l, float f) {
outs() << format("0x%08" PRIx32, l);
if ((l & 0x7f800000) != 0x7f800000)
outs() << format(" (%.16e)\n", f);
else {
if (l == 0x7f800000)
outs() << " (+Infinity)\n";
else if (l == 0xff800000)
outs() << " (-Infinity)\n";
else if ((l & 0x00400000) == 0x00400000)
outs() << " (non-signaling Not-a-Number)\n";
else
outs() << " (signaling Not-a-Number)\n";
}
}
static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
uint32_t sect_size, uint64_t sect_addr,
bool print_addresses) {
for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
if (print_addresses) {
if (O->is64Bit())
outs() << format("%016" PRIx64, sect_addr + i) << " ";
else
outs() << format("%08" PRIx64, sect_addr + i) << " ";
}
float f;
memcpy(&f, sect + i, sizeof(float));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(f);
uint32_t l;
memcpy(&l, sect + i, sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(l);
DumpLiteral4(l, f);
}
}
static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
double d) {
outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
uint32_t Hi, Lo;
Hi = (O->isLittleEndian()) ? l1 : l0;
Lo = (O->isLittleEndian()) ? l0 : l1;
// Hi is the high word, so this is equivalent to if(isfinite(d))
if ((Hi & 0x7ff00000) != 0x7ff00000)
outs() << format(" (%.16e)\n", d);
else {
if (Hi == 0x7ff00000 && Lo == 0)
outs() << " (+Infinity)\n";
else if (Hi == 0xfff00000 && Lo == 0)
outs() << " (-Infinity)\n";
else if ((Hi & 0x00080000) == 0x00080000)
outs() << " (non-signaling Not-a-Number)\n";
else
outs() << " (signaling Not-a-Number)\n";
}
}
static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
uint32_t sect_size, uint64_t sect_addr,
bool print_addresses) {
for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
if (print_addresses) {
if (O->is64Bit())
outs() << format("%016" PRIx64, sect_addr + i) << " ";
else
outs() << format("%08" PRIx64, sect_addr + i) << " ";
}
double d;
memcpy(&d, sect + i, sizeof(double));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(d);
uint32_t l0, l1;
memcpy(&l0, sect + i, sizeof(uint32_t));
memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost) {
sys::swapByteOrder(l0);
sys::swapByteOrder(l1);
}
DumpLiteral8(O, l0, l1, d);
}
}
static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
outs() << format("0x%08" PRIx32, l0) << " ";
outs() << format("0x%08" PRIx32, l1) << " ";
outs() << format("0x%08" PRIx32, l2) << " ";
outs() << format("0x%08" PRIx32, l3) << "\n";
}
static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
uint32_t sect_size, uint64_t sect_addr,
bool print_addresses) {
for (uint32_t i = 0; i < sect_size; i += 16) {
if (print_addresses) {
if (O->is64Bit())
outs() << format("%016" PRIx64, sect_addr + i) << " ";
else
outs() << format("%08" PRIx64, sect_addr + i) << " ";
}
uint32_t l0, l1, l2, l3;
memcpy(&l0, sect + i, sizeof(uint32_t));
memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost) {
sys::swapByteOrder(l0);
sys::swapByteOrder(l1);
sys::swapByteOrder(l2);
sys::swapByteOrder(l3);
}
DumpLiteral16(l0, l1, l2, l3);
}
}
static void DumpLiteralPointerSection(MachOObjectFile *O,
const SectionRef &Section,
const char *sect, uint32_t sect_size,
uint64_t sect_addr,
bool print_addresses) {
// Collect the literal sections in this Mach-O file.
std::vector<SectionRef> LiteralSections;
for (const SectionRef &Section : O->sections()) {
DataRefImpl Ref = Section.getRawDataRefImpl();
uint32_t section_type;
if (O->is64Bit()) {
const MachO::section_64 Sec = O->getSection64(Ref);
section_type = Sec.flags & MachO::SECTION_TYPE;
} else {
const MachO::section Sec = O->getSection(Ref);
section_type = Sec.flags & MachO::SECTION_TYPE;
}
if (section_type == MachO::S_CSTRING_LITERALS ||
section_type == MachO::S_4BYTE_LITERALS ||
section_type == MachO::S_8BYTE_LITERALS ||
section_type == MachO::S_16BYTE_LITERALS)
LiteralSections.push_back(Section);
}
// Set the size of the literal pointer.
uint32_t lp_size = O->is64Bit() ? 8 : 4;
// Collect the external relocation symbols for the literal pointers.
std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
for (const RelocationRef &Reloc : Section.relocations()) {
DataRefImpl Rel;
MachO::any_relocation_info RE;
bool isExtern = false;
Rel = Reloc.getRawDataRefImpl();
RE = O->getRelocation(Rel);
isExtern = O->getPlainRelocationExternal(RE);
if (isExtern) {
uint64_t RelocOffset = Reloc.getOffset();
symbol_iterator RelocSym = Reloc.getSymbol();
Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
}
}
array_pod_sort(Relocs.begin(), Relocs.end());
// Dump each literal pointer.
for (uint32_t i = 0; i < sect_size; i += lp_size) {
if (print_addresses) {
if (O->is64Bit())
outs() << format("%016" PRIx64, sect_addr + i) << " ";
else
outs() << format("%08" PRIx64, sect_addr + i) << " ";
}
uint64_t lp;
if (O->is64Bit()) {
memcpy(&lp, sect + i, sizeof(uint64_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(lp);
} else {
uint32_t li;
memcpy(&li, sect + i, sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(li);
lp = li;
}
// First look for an external relocation entry for this literal pointer.
auto Reloc = std::find_if(
Relocs.begin(), Relocs.end(),
[&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
if (Reloc != Relocs.end()) {
symbol_iterator RelocSym = Reloc->second;
ErrorOr<StringRef> SymName = RelocSym->getName();
if (std::error_code EC = SymName.getError())
report_fatal_error(EC.message());
outs() << "external relocation entry for symbol:" << *SymName << "\n";
continue;
}
// For local references see what the section the literal pointer points to.
auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
[&](const SectionRef &R) {
return lp >= R.getAddress() &&
lp < R.getAddress() + R.getSize();
});
if (Sect == LiteralSections.end()) {
outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
continue;
}
uint64_t SectAddress = Sect->getAddress();
uint64_t SectSize = Sect->getSize();
StringRef SectName;
Sect->getName(SectName);
DataRefImpl Ref = Sect->getRawDataRefImpl();
StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
outs() << SegmentName << ":" << SectName << ":";
uint32_t section_type;
if (O->is64Bit()) {
const MachO::section_64 Sec = O->getSection64(Ref);
section_type = Sec.flags & MachO::SECTION_TYPE;
} else {
const MachO::section Sec = O->getSection(Ref);
section_type = Sec.flags & MachO::SECTION_TYPE;
}
StringRef BytesStr;
Sect->getContents(BytesStr);
const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
switch (section_type) {
case MachO::S_CSTRING_LITERALS:
for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
i++) {
DumpCstringChar(Contents[i]);
}
outs() << "\n";
break;
case MachO::S_4BYTE_LITERALS:
float f;
memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
uint32_t l;
memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost) {
sys::swapByteOrder(f);
sys::swapByteOrder(l);
}
DumpLiteral4(l, f);
break;
case MachO::S_8BYTE_LITERALS: {
double d;
memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
uint32_t l0, l1;
memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost) {
sys::swapByteOrder(f);
sys::swapByteOrder(l0);
sys::swapByteOrder(l1);
}
DumpLiteral8(O, l0, l1, d);
break;
}
case MachO::S_16BYTE_LITERALS: {
uint32_t l0, l1, l2, l3;
memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
sizeof(uint32_t));
memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
sizeof(uint32_t));
memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost) {
sys::swapByteOrder(l0);
sys::swapByteOrder(l1);
sys::swapByteOrder(l2);
sys::swapByteOrder(l3);
}
DumpLiteral16(l0, l1, l2, l3);
break;
}
}
}
}
static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
uint32_t sect_size, uint64_t sect_addr,
SymbolAddressMap *AddrMap,
bool verbose) {
uint32_t stride;
stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
for (uint32_t i = 0; i < sect_size; i += stride) {
const char *SymbolName = nullptr;
if (O->is64Bit()) {
outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
uint64_t pointer_value;
memcpy(&pointer_value, sect + i, stride);
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(pointer_value);
outs() << format("0x%016" PRIx64, pointer_value);
if (verbose)
SymbolName = GuessSymbolName(pointer_value, AddrMap);
} else {
outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
uint32_t pointer_value;
memcpy(&pointer_value, sect + i, stride);
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(pointer_value);
outs() << format("0x%08" PRIx32, pointer_value);
if (verbose)
SymbolName = GuessSymbolName(pointer_value, AddrMap);
}
if (SymbolName)
outs() << " " << SymbolName;
outs() << "\n";
}
}
static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
uint32_t size, uint64_t addr) {
uint32_t cputype = O->getHeader().cputype;
if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
uint32_t j;
for (uint32_t i = 0; i < size; i += j, addr += j) {
if (O->is64Bit())
outs() << format("%016" PRIx64, addr) << "\t";
else
outs() << format("%08" PRIx64, addr) << "\t";
for (j = 0; j < 16 && i + j < size; j++) {
uint8_t byte_word = *(sect + i + j);
outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
}
outs() << "\n";
}
} else {
uint32_t j;
for (uint32_t i = 0; i < size; i += j, addr += j) {
if (O->is64Bit())
outs() << format("%016" PRIx64, addr) << "\t";
else
outs() << format("%08" PRIx64, sect) << "\t";
for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
j += sizeof(int32_t)) {
if (i + j + sizeof(int32_t) < size) {
uint32_t long_word;
memcpy(&long_word, sect + i + j, sizeof(int32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(long_word);
outs() << format("%08" PRIx32, long_word) << " ";
} else {
for (uint32_t k = 0; i + j + k < size; k++) {
uint8_t byte_word = *(sect + i + j);
outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
}
}
}
outs() << "\n";
}
}
}
static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
StringRef DisSegName, StringRef DisSectName);
static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
uint32_t size, uint32_t addr);
static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
bool verbose) {
SymbolAddressMap AddrMap;
if (verbose)
CreateSymbolAddressMap(O, &AddrMap);
for (unsigned i = 0; i < FilterSections.size(); ++i) {
StringRef DumpSection = FilterSections[i];
std::pair<StringRef, StringRef> DumpSegSectName;
DumpSegSectName = DumpSection.split(',');
StringRef DumpSegName, DumpSectName;
if (DumpSegSectName.second.size()) {
DumpSegName = DumpSegSectName.first;
DumpSectName = DumpSegSectName.second;
} else {
DumpSegName = "";
DumpSectName = DumpSegSectName.first;
}
for (const SectionRef &Section : O->sections()) {
StringRef SectName;
Section.getName(SectName);
DataRefImpl Ref = Section.getRawDataRefImpl();
StringRef SegName = O->getSectionFinalSegmentName(Ref);
if ((DumpSegName.empty() || SegName == DumpSegName) &&
(SectName == DumpSectName)) {
uint32_t section_flags;
if (O->is64Bit()) {
const MachO::section_64 Sec = O->getSection64(Ref);
section_flags = Sec.flags;
} else {
const MachO::section Sec = O->getSection(Ref);
section_flags = Sec.flags;
}
uint32_t section_type = section_flags & MachO::SECTION_TYPE;
StringRef BytesStr;
Section.getContents(BytesStr);
const char *sect = reinterpret_cast<const char *>(BytesStr.data());
uint32_t sect_size = BytesStr.size();
uint64_t sect_addr = Section.getAddress();
outs() << "Contents of (" << SegName << "," << SectName
<< ") section\n";
if (verbose) {
if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
(section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
DisassembleMachO(Filename, O, SegName, SectName);
continue;
}
if (SegName == "__TEXT" && SectName == "__info_plist") {
outs() << sect;
continue;
}
if (SegName == "__OBJC" && SectName == "__protocol") {
DumpProtocolSection(O, sect, sect_size, sect_addr);
continue;
}
switch (section_type) {
case MachO::S_REGULAR:
DumpRawSectionContents(O, sect, sect_size, sect_addr);
break;
case MachO::S_ZEROFILL:
outs() << "zerofill section and has no contents in the file\n";
break;
case MachO::S_CSTRING_LITERALS:
DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
break;
case MachO::S_4BYTE_LITERALS:
DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
break;
case MachO::S_8BYTE_LITERALS:
DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
break;
case MachO::S_16BYTE_LITERALS:
DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
break;
case MachO::S_LITERAL_POINTERS:
DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
!NoLeadingAddr);
break;
case MachO::S_MOD_INIT_FUNC_POINTERS:
case MachO::S_MOD_TERM_FUNC_POINTERS:
DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
verbose);
break;
default:
outs() << "Unknown section type ("
<< format("0x%08" PRIx32, section_type) << ")\n";
DumpRawSectionContents(O, sect, sect_size, sect_addr);
break;
}
} else {
if (section_type == MachO::S_ZEROFILL)
outs() << "zerofill section and has no contents in the file\n";
else
DumpRawSectionContents(O, sect, sect_size, sect_addr);
}
}
}
}
}
static void DumpInfoPlistSectionContents(StringRef Filename,
MachOObjectFile *O) {
for (const SectionRef &Section : O->sections()) {
StringRef SectName;
Section.getName(SectName);
DataRefImpl Ref = Section.getRawDataRefImpl();
StringRef SegName = O->getSectionFinalSegmentName(Ref);
if (SegName == "__TEXT" && SectName == "__info_plist") {
outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
StringRef BytesStr;
Section.getContents(BytesStr);
const char *sect = reinterpret_cast<const char *>(BytesStr.data());
outs() << sect;
return;
}
}
}
// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
// and if it is and there is a list of architecture flags is specified then
// check to make sure this Mach-O file is one of those architectures or all
// architectures were specified. If not then an error is generated and this
// routine returns false. Else it returns true.
static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
bool ArchFound = false;
MachO::mach_header H;
MachO::mach_header_64 H_64;
Triple T;
if (MachO->is64Bit()) {
H_64 = MachO->MachOObjectFile::getHeader64();
T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
} else {
H = MachO->MachOObjectFile::getHeader();
T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
}
unsigned i;
for (i = 0; i < ArchFlags.size(); ++i) {
if (ArchFlags[i] == T.getArchName())
ArchFound = true;
break;
}
if (!ArchFound) {
errs() << "llvm-objdump: file: " + Filename + " does not contain "
<< "architecture: " + ArchFlags[i] + "\n";
return false;
}
}
return true;
}
static void printObjcMetaData(MachOObjectFile *O, bool verbose);
// ProcessMachO() is passed a single opened Mach-O file, which may be an
// archive member and or in a slice of a universal file. It prints the
// the file name and header info and then processes it according to the
// command line options.
static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
StringRef ArchiveMemberName = StringRef(),
StringRef ArchitectureName = StringRef()) {
// If we are doing some processing here on the Mach-O file print the header
// info. And don't print it otherwise like in the case of printing the
// UniversalHeaders or ArchiveHeaders.
if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
outs() << Filename;
if (!ArchiveMemberName.empty())
outs() << '(' << ArchiveMemberName << ')';
if (!ArchitectureName.empty())
outs() << " (architecture " << ArchitectureName << ")";
outs() << ":\n";
}
if (Disassemble)
DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
if (IndirectSymbols)
PrintIndirectSymbols(MachOOF, !NonVerbose);
if (DataInCode)
PrintDataInCodeTable(MachOOF, !NonVerbose);
if (LinkOptHints)
PrintLinkOptHints(MachOOF);
if (Relocations)
PrintRelocations(MachOOF);
if (SectionHeaders)
PrintSectionHeaders(MachOOF);
if (SectionContents)
PrintSectionContents(MachOOF);
if (FilterSections.size() != 0)
DumpSectionContents(Filename, MachOOF, !NonVerbose);
if (InfoPlist)
DumpInfoPlistSectionContents(Filename, MachOOF);
if (DylibsUsed)
PrintDylibs(MachOOF, false);
if (DylibId)
PrintDylibs(MachOOF, true);
if (SymbolTable)
PrintSymbolTable(MachOOF);
if (UnwindInfo)
printMachOUnwindInfo(MachOOF);
if (PrivateHeaders) {
printMachOFileHeader(MachOOF);
printMachOLoadCommands(MachOOF);
}
if (FirstPrivateHeader)
printMachOFileHeader(MachOOF);
if (ObjcMetaData)
printObjcMetaData(MachOOF, !NonVerbose);
if (ExportsTrie)
printExportsTrie(MachOOF);
if (Rebase)
printRebaseTable(MachOOF);
if (Bind)
printBindTable(MachOOF);
if (LazyBind)
printLazyBindTable(MachOOF);
if (WeakBind)
printWeakBindTable(MachOOF);
}
// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
outs() << " cputype (" << cputype << ")\n";
outs() << " cpusubtype (" << cpusubtype << ")\n";
}
// printCPUType() helps print_fat_headers by printing the cputype and
// pusubtype (symbolically for the one's it knows about).
static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
switch (cputype) {
case MachO::CPU_TYPE_I386:
switch (cpusubtype) {
case MachO::CPU_SUBTYPE_I386_ALL:
outs() << " cputype CPU_TYPE_I386\n";
outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
break;
default:
printUnknownCPUType(cputype, cpusubtype);
break;
}
break;
case MachO::CPU_TYPE_X86_64:
switch (cpusubtype) {
case MachO::CPU_SUBTYPE_X86_64_ALL:
outs() << " cputype CPU_TYPE_X86_64\n";
outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
break;
case MachO::CPU_SUBTYPE_X86_64_H:
outs() << " cputype CPU_TYPE_X86_64\n";
outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
break;
default:
printUnknownCPUType(cputype, cpusubtype);
break;
}
break;
case MachO::CPU_TYPE_ARM:
switch (cpusubtype) {
case MachO::CPU_SUBTYPE_ARM_ALL:
outs() << " cputype CPU_TYPE_ARM\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
break;
case MachO::CPU_SUBTYPE_ARM_V4T:
outs() << " cputype CPU_TYPE_ARM\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
break;
case MachO::CPU_SUBTYPE_ARM_V5TEJ:
outs() << " cputype CPU_TYPE_ARM\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
break;
case MachO::CPU_SUBTYPE_ARM_XSCALE:
outs() << " cputype CPU_TYPE_ARM\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
break;
case MachO::CPU_SUBTYPE_ARM_V6:
outs() << " cputype CPU_TYPE_ARM\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
break;
case MachO::CPU_SUBTYPE_ARM_V6M:
outs() << " cputype CPU_TYPE_ARM\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
break;
case MachO::CPU_SUBTYPE_ARM_V7:
outs() << " cputype CPU_TYPE_ARM\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
break;
case MachO::CPU_SUBTYPE_ARM_V7EM:
outs() << " cputype CPU_TYPE_ARM\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
break;
case MachO::CPU_SUBTYPE_ARM_V7K:
outs() << " cputype CPU_TYPE_ARM\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
break;
case MachO::CPU_SUBTYPE_ARM_V7M:
outs() << " cputype CPU_TYPE_ARM\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
break;
case MachO::CPU_SUBTYPE_ARM_V7S:
outs() << " cputype CPU_TYPE_ARM\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
break;
default:
printUnknownCPUType(cputype, cpusubtype);
break;
}
break;
case MachO::CPU_TYPE_ARM64:
switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
case MachO::CPU_SUBTYPE_ARM64_ALL:
outs() << " cputype CPU_TYPE_ARM64\n";
outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
break;
default:
printUnknownCPUType(cputype, cpusubtype);
break;
}
break;
default:
printUnknownCPUType(cputype, cpusubtype);
break;
}
}
static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
bool verbose) {
outs() << "Fat headers\n";
if (verbose)
outs() << "fat_magic FAT_MAGIC\n";
else
outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
uint32_t nfat_arch = UB->getNumberOfObjects();
StringRef Buf = UB->getData();
uint64_t size = Buf.size();
uint64_t big_size = sizeof(struct MachO::fat_header) +
nfat_arch * sizeof(struct MachO::fat_arch);
outs() << "nfat_arch " << UB->getNumberOfObjects();
if (nfat_arch == 0)
outs() << " (malformed, contains zero architecture types)\n";
else if (big_size > size)
outs() << " (malformed, architectures past end of file)\n";
else
outs() << "\n";
for (uint32_t i = 0; i < nfat_arch; ++i) {
MachOUniversalBinary::ObjectForArch OFA(UB, i);
uint32_t cputype = OFA.getCPUType();
uint32_t cpusubtype = OFA.getCPUSubType();
outs() << "architecture ";
for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
uint32_t other_cputype = other_OFA.getCPUType();
uint32_t other_cpusubtype = other_OFA.getCPUSubType();
if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
(cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
(other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
outs() << "(illegal duplicate architecture) ";
break;
}
}
if (verbose) {
outs() << OFA.getArchTypeName() << "\n";
printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
} else {
outs() << i << "\n";
outs() << " cputype " << cputype << "\n";
outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
<< "\n";
}
if (verbose &&
(cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
outs() << " capabilities CPU_SUBTYPE_LIB64\n";
else
outs() << " capabilities "
<< format("0x%" PRIx32,
(cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
outs() << " offset " << OFA.getOffset();
if (OFA.getOffset() > size)
outs() << " (past end of file)";
if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
outs() << "\n";
outs() << " size " << OFA.getSize();
big_size = OFA.getOffset() + OFA.getSize();
if (big_size > size)
outs() << " (past end of file)";
outs() << "\n";
outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
<< ")\n";
}
}
static void printArchiveChild(const Archive::Child &C, bool verbose,
bool print_offset) {
if (print_offset)
outs() << C.getChildOffset() << "\t";
sys::fs::perms Mode = C.getAccessMode();
if (verbose) {
// FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
// But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
outs() << "-";
outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
} else {
outs() << format("0%o ", Mode);
}
unsigned UID = C.getUID();
outs() << format("%3d/", UID);
unsigned GID = C.getGID();
outs() << format("%-3d ", GID);
ErrorOr<uint64_t> Size = C.getRawSize();
if (std::error_code EC = Size.getError())
report_fatal_error(EC.message());
outs() << format("%5" PRId64, Size.get()) << " ";
StringRef RawLastModified = C.getRawLastModified();
if (verbose) {
unsigned Seconds;
if (RawLastModified.getAsInteger(10, Seconds))
outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
else {
// Since cime(3) returns a 26 character string of the form:
// "Sun Sep 16 01:03:52 1973\n\0"
// just print 24 characters.
time_t t = Seconds;
outs() << format("%.24s ", ctime(&t));
}
} else {
outs() << RawLastModified << " ";
}
if (verbose) {
ErrorOr<StringRef> NameOrErr = C.getName();
if (NameOrErr.getError()) {
StringRef RawName = C.getRawName();
outs() << RawName << "\n";
} else {
StringRef Name = NameOrErr.get();
outs() << Name << "\n";
}
} else {
StringRef RawName = C.getRawName();
outs() << RawName << "\n";
}
}
static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
I != E; ++I) {
if (std::error_code EC = I->getError())
report_fatal_error(EC.message());
const Archive::Child &C = **I;
printArchiveChild(C, verbose, print_offset);
}
}
// ParseInputMachO() parses the named Mach-O file in Filename and handles the
// -arch flags selecting just those slices as specified by them and also parses
// archive files. Then for each individual Mach-O file ProcessMachO() is
// called to process the file based on the command line options.
void llvm::ParseInputMachO(StringRef Filename) {
// Check for -arch all and verifiy the -arch flags are valid.
for (unsigned i = 0; i < ArchFlags.size(); ++i) {
if (ArchFlags[i] == "all") {
ArchAll = true;
} else {
if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
"'for the -arch option\n";
return;
}
}
}
// Attempt to open the binary.
ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
if (std::error_code EC = BinaryOrErr.getError())
report_error(Filename, EC);
Binary &Bin = *BinaryOrErr.get().getBinary();
if (Archive *A = dyn_cast<Archive>(&Bin)) {
outs() << "Archive : " << Filename << "\n";
if (ArchiveHeaders)
printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
I != E; ++I) {
if (std::error_code EC = I->getError())
report_error(Filename, EC);
auto &C = I->get();
ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
if (ChildOrErr.getError())
continue;
if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
if (!checkMachOAndArchFlags(O, Filename))
return;
ProcessMachO(Filename, O, O->getFileName());
}
}
return;
}
if (UniversalHeaders) {
if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
printMachOUniversalHeaders(UB, !NonVerbose);
}
if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
// If we have a list of architecture flags specified dump only those.
if (!ArchAll && ArchFlags.size() != 0) {
// Look for a slice in the universal binary that matches each ArchFlag.
bool ArchFound;
for (unsigned i = 0; i < ArchFlags.size(); ++i) {
ArchFound = false;
for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
E = UB->end_objects();
I != E; ++I) {
if (ArchFlags[i] == I->getArchTypeName()) {
ArchFound = true;
ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
I->getAsObjectFile();
std::string ArchitectureName = "";
if (ArchFlags.size() > 1)
ArchitectureName = I->getArchTypeName();
if (ObjOrErr) {
ObjectFile &O = *ObjOrErr.get();
if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
ProcessMachO(Filename, MachOOF, "", ArchitectureName);
} else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
I->getAsArchive()) {
std::unique_ptr<Archive> &A = *AOrErr;
outs() << "Archive : " << Filename;
if (!ArchitectureName.empty())
outs() << " (architecture " << ArchitectureName << ")";
outs() << "\n";
if (ArchiveHeaders)
printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
for (Archive::child_iterator AI = A->child_begin(),
AE = A->child_end();
AI != AE; ++AI) {
if (std::error_code EC = AI->getError())
report_error(Filename, EC);
auto &C = AI->get();
ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
if (ChildOrErr.getError())
continue;
if (MachOObjectFile *O =
dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
}
}
}
}
if (!ArchFound) {
errs() << "llvm-objdump: file: " + Filename + " does not contain "
<< "architecture: " + ArchFlags[i] + "\n";
return;
}
}
return;
}
// No architecture flags were specified so if this contains a slice that
// matches the host architecture dump only that.
if (!ArchAll) {
for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
E = UB->end_objects();
I != E; ++I) {
if (MachOObjectFile::getHostArch().getArchName() ==
I->getArchTypeName()) {
ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
std::string ArchiveName;
ArchiveName.clear();
if (ObjOrErr) {
ObjectFile &O = *ObjOrErr.get();
if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
ProcessMachO(Filename, MachOOF);
} else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
I->getAsArchive()) {
std::unique_ptr<Archive> &A = *AOrErr;
outs() << "Archive : " << Filename << "\n";
if (ArchiveHeaders)
printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
for (Archive::child_iterator AI = A->child_begin(),
AE = A->child_end();
AI != AE; ++AI) {
if (std::error_code EC = AI->getError())
report_error(Filename, EC);
auto &C = AI->get();
ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
if (ChildOrErr.getError())
continue;
if (MachOObjectFile *O =
dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
ProcessMachO(Filename, O, O->getFileName());
}
}
return;
}
}
}
// Either all architectures have been specified or none have been specified
// and this does not contain the host architecture so dump all the slices.
bool moreThanOneArch = UB->getNumberOfObjects() > 1;
for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
E = UB->end_objects();
I != E; ++I) {
ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
std::string ArchitectureName = "";
if (moreThanOneArch)
ArchitectureName = I->getArchTypeName();
if (ObjOrErr) {
ObjectFile &Obj = *ObjOrErr.get();
if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
ProcessMachO(Filename, MachOOF, "", ArchitectureName);
} else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
std::unique_ptr<Archive> &A = *AOrErr;
outs() << "Archive : " << Filename;
if (!ArchitectureName.empty())
outs() << " (architecture " << ArchitectureName << ")";
outs() << "\n";
if (ArchiveHeaders)
printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
AI != AE; ++AI) {
if (std::error_code EC = AI->getError())
report_error(Filename, EC);
auto &C = AI->get();
ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
if (ChildOrErr.getError())
continue;
if (MachOObjectFile *O =
dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
ArchitectureName);
}
}
}
}
return;
}
if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
if (!checkMachOAndArchFlags(O, Filename))
return;
if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
ProcessMachO(Filename, MachOOF);
} else
errs() << "llvm-objdump: '" << Filename << "': "
<< "Object is not a Mach-O file type.\n";
return;
}
llvm_unreachable("Input object can't be invalid at this point");
}
typedef std::pair<uint64_t, const char *> BindInfoEntry;
typedef std::vector<BindInfoEntry> BindTable;
typedef BindTable::iterator bind_table_iterator;
// The block of info used by the Symbolizer call backs.
struct DisassembleInfo {
bool verbose;
MachOObjectFile *O;
SectionRef S;
SymbolAddressMap *AddrMap;
std::vector<SectionRef> *Sections;
const char *class_name;
const char *selector_name;
char *method;
char *demangled_name;
uint64_t adrp_addr;
uint32_t adrp_inst;
BindTable *bindtable;
uint32_t depth;
};
// SymbolizerGetOpInfo() is the operand information call back function.
// This is called to get the symbolic information for operand(s) of an
// instruction when it is being done. This routine does this from
// the relocation information, symbol table, etc. That block of information
// is a pointer to the struct DisassembleInfo that was passed when the
// disassembler context was created and passed to back to here when
// called back by the disassembler for instruction operands that could have
// relocation information. The address of the instruction containing operand is
// at the Pc parameter. The immediate value the operand has is passed in
// op_info->Value and is at Offset past the start of the instruction and has a
// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
// names and addends of the symbolic expression to add for the operand. The
// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
// information is returned then this function returns 1 else it returns 0.
static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
uint64_t Size, int TagType, void *TagBuf) {
struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
uint64_t value = op_info->Value;
// Make sure all fields returned are zero if we don't set them.
memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
op_info->Value = value;
// If the TagType is not the value 1 which it code knows about or if no
// verbose symbolic information is wanted then just return 0, indicating no
// information is being returned.
if (TagType != 1 || !info->verbose)
return 0;
unsigned int Arch = info->O->getArch();
if (Arch == Triple::x86) {
if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
return 0;
if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
// TODO:
// Search the external relocation entries of a fully linked image
// (if any) for an entry that matches this segment offset.
// uint32_t seg_offset = (Pc + Offset);
return 0;
}
// In MH_OBJECT filetypes search the section's relocation entries (if any)
// for an entry for this section offset.
uint32_t sect_addr = info->S.getAddress();
uint32_t sect_offset = (Pc + Offset) - sect_addr;
bool reloc_found = false;
DataRefImpl Rel;
MachO::any_relocation_info RE;
bool isExtern = false;
SymbolRef Symbol;
bool r_scattered = false;
uint32_t r_value, pair_r_value, r_type;
for (const RelocationRef &Reloc : info->S.relocations()) {
uint64_t RelocOffset = Reloc.getOffset();
if (RelocOffset == sect_offset) {
Rel = Reloc.getRawDataRefImpl();
RE = info->O->getRelocation(Rel);
r_type = info->O->getAnyRelocationType(RE);
r_scattered = info->O->isRelocationScattered(RE);
if (r_scattered) {
r_value = info->O->getScatteredRelocationValue(RE);
if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
DataRefImpl RelNext = Rel;
info->O->moveRelocationNext(RelNext);
MachO::any_relocation_info RENext;
RENext = info->O->getRelocation(RelNext);
if (info->O->isRelocationScattered(RENext))
pair_r_value = info->O->getScatteredRelocationValue(RENext);
else
return 0;
}
} else {
isExtern = info->O->getPlainRelocationExternal(RE);
if (isExtern) {
symbol_iterator RelocSym = Reloc.getSymbol();
Symbol = *RelocSym;
}
}
reloc_found = true;
break;
}
}
if (reloc_found && isExtern) {
ErrorOr<StringRef> SymName = Symbol.getName();
if (std::error_code EC = SymName.getError())
report_fatal_error(EC.message());
const char *name = SymName->data();
op_info->AddSymbol.Present = 1;
op_info->AddSymbol.Name = name;
// For i386 extern relocation entries the value in the instruction is
// the offset from the symbol, and value is already set in op_info->Value.
return 1;
}
if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
const char *add = GuessSymbolName(r_value, info->AddrMap);
const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
uint32_t offset = value - (r_value - pair_r_value);
op_info->AddSymbol.Present = 1;
if (add != nullptr)
op_info->AddSymbol.Name = add;
else
op_info->AddSymbol.Value = r_value;
op_info->SubtractSymbol.Present = 1;
if (sub != nullptr)
op_info->SubtractSymbol.Name = sub;
else
op_info->SubtractSymbol.Value = pair_r_value;
op_info->Value = offset;
return 1;
}
return 0;
}
if (Arch == Triple::x86_64) {
if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
return 0;
if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
// TODO:
// Search the external relocation entries of a fully linked image
// (if any) for an entry that matches this segment offset.
// uint64_t seg_offset = (Pc + Offset);
return 0;
}
// In MH_OBJECT filetypes search the section's relocation entries (if any)
// for an entry for this section offset.
uint64_t sect_addr = info->S.getAddress();
uint64_t sect_offset = (Pc + Offset) - sect_addr;
bool reloc_found = false;
DataRefImpl Rel;
MachO::any_relocation_info RE;
bool isExtern = false;
SymbolRef Symbol;
for (const RelocationRef &Reloc : info->S.relocations()) {
uint64_t RelocOffset = Reloc.getOffset();
if (RelocOffset == sect_offset) {
Rel = Reloc.getRawDataRefImpl();
RE = info->O->getRelocation(Rel);
// NOTE: Scattered relocations don't exist on x86_64.
isExtern = info->O->getPlainRelocationExternal(RE);
if (isExtern) {
symbol_iterator RelocSym = Reloc.getSymbol();
Symbol = *RelocSym;
}
reloc_found = true;
break;
}
}
if (reloc_found && isExtern) {
// The Value passed in will be adjusted by the Pc if the instruction
// adds the Pc. But for x86_64 external relocation entries the Value
// is the offset from the external symbol.
if (info->O->getAnyRelocationPCRel(RE))
op_info->Value -= Pc + Offset + Size;
ErrorOr<StringRef> SymName = Symbol.getName();
if (std::error_code EC = SymName.getError())
report_fatal_error(EC.message());
const char *name = SymName->data();
unsigned Type = info->O->getAnyRelocationType(RE);
if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
DataRefImpl RelNext = Rel;
info->O->moveRelocationNext(RelNext);
MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
unsigned TypeNext = info->O->getAnyRelocationType(RENext);
bool isExternNext = info->O->getPlainRelocationExternal(RENext);
unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
op_info->SubtractSymbol.Present = 1;
op_info->SubtractSymbol.Name = name;
symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
Symbol = *RelocSymNext;
ErrorOr<StringRef> SymNameNext = Symbol.getName();
if (std::error_code EC = SymNameNext.getError())
report_fatal_error(EC.message());
name = SymNameNext->data();
}
}
// TODO: add the VariantKinds to op_info->VariantKind for relocation types
// like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
op_info->AddSymbol.Present = 1;
op_info->AddSymbol.Name = name;
return 1;
}
return 0;
}
if (Arch == Triple::arm) {
if (Offset != 0 || (Size != 4 && Size != 2))
return 0;
if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
// TODO:
// Search the external relocation entries of a fully linked image
// (if any) for an entry that matches this segment offset.
// uint32_t seg_offset = (Pc + Offset);
return 0;
}
// In MH_OBJECT filetypes search the section's relocation entries (if any)
// for an entry for this section offset.
uint32_t sect_addr = info->S.getAddress();
uint32_t sect_offset = (Pc + Offset) - sect_addr;
DataRefImpl Rel;
MachO::any_relocation_info RE;
bool isExtern = false;
SymbolRef Symbol;
bool r_scattered = false;
uint32_t r_value, pair_r_value, r_type, r_length, other_half;
auto Reloc =
std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
[&](const RelocationRef &Reloc) {
uint64_t RelocOffset = Reloc.getOffset();
return RelocOffset == sect_offset;
});
if (Reloc == info->S.relocations().end())
return 0;
Rel = Reloc->getRawDataRefImpl();
RE = info->O->getRelocation(Rel);
r_length = info->O->getAnyRelocationLength(RE);
r_scattered = info->O->isRelocationScattered(RE);
if (r_scattered) {
r_value = info->O->getScatteredRelocationValue(RE);
r_type = info->O->getScatteredRelocationType(RE);
} else {
r_type = info->O->getAnyRelocationType(RE);
isExtern = info->O->getPlainRelocationExternal(RE);
if (isExtern) {
symbol_iterator RelocSym = Reloc->getSymbol();
Symbol = *RelocSym;
}
}
if (r_type == MachO::ARM_RELOC_HALF ||
r_type == MachO::ARM_RELOC_SECTDIFF ||
r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
DataRefImpl RelNext = Rel;
info->O->moveRelocationNext(RelNext);
MachO::any_relocation_info RENext;
RENext = info->O->getRelocation(RelNext);
other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
if (info->O->isRelocationScattered(RENext))
pair_r_value = info->O->getScatteredRelocationValue(RENext);
}
if (isExtern) {
ErrorOr<StringRef> SymName = Symbol.getName();
if (std::error_code EC = SymName.getError())
report_fatal_error(EC.message());
const char *name = SymName->data();
op_info->AddSymbol.Present = 1;
op_info->AddSymbol.Name = name;
switch (r_type) {
case MachO::ARM_RELOC_HALF:
if ((r_length & 0x1) == 1) {
op_info->Value = value << 16 | other_half;
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
} else {
op_info->Value = other_half << 16 | value;
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
}
break;
default:
break;
}
return 1;
}
// If we have a branch that is not an external relocation entry then
// return 0 so the code in tryAddingSymbolicOperand() can use the
// SymbolLookUp call back with the branch target address to look up the
// symbol and possiblity add an annotation for a symbol stub.
if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
r_type == MachO::ARM_THUMB_RELOC_BR22))
return 0;
uint32_t offset = 0;
if (r_type == MachO::ARM_RELOC_HALF ||
r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
if ((r_length & 0x1) == 1)
value = value << 16 | other_half;
else
value = other_half << 16 | value;
}
if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
offset = value - r_value;
value = r_value;
}
if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
if ((r_length & 0x1) == 1)
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
else
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
const char *add = GuessSymbolName(r_value, info->AddrMap);
const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
int32_t offset = value - (r_value - pair_r_value);
op_info->AddSymbol.Present = 1;
if (add != nullptr)
op_info->AddSymbol.Name = add;
else
op_info->AddSymbol.Value = r_value;
op_info->SubtractSymbol.Present = 1;
if (sub != nullptr)
op_info->SubtractSymbol.Name = sub;
else
op_info->SubtractSymbol.Value = pair_r_value;
op_info->Value = offset;
return 1;
}
op_info->AddSymbol.Present = 1;
op_info->Value = offset;
if (r_type == MachO::ARM_RELOC_HALF) {
if ((r_length & 0x1) == 1)
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
else
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
}
const char *add = GuessSymbolName(value, info->AddrMap);
if (add != nullptr) {
op_info->AddSymbol.Name = add;
return 1;
}
op_info->AddSymbol.Value = value;
return 1;
}
if (Arch == Triple::aarch64) {
if (Offset != 0 || Size != 4)
return 0;
if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
// TODO:
// Search the external relocation entries of a fully linked image
// (if any) for an entry that matches this segment offset.
// uint64_t seg_offset = (Pc + Offset);
return 0;
}
// In MH_OBJECT filetypes search the section's relocation entries (if any)
// for an entry for this section offset.
uint64_t sect_addr = info->S.getAddress();
uint64_t sect_offset = (Pc + Offset) - sect_addr;
auto Reloc =
std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
[&](const RelocationRef &Reloc) {
uint64_t RelocOffset = Reloc.getOffset();
return RelocOffset == sect_offset;
});
if (Reloc == info->S.relocations().end())
return 0;
DataRefImpl Rel = Reloc->getRawDataRefImpl();
MachO::any_relocation_info RE = info->O->getRelocation(Rel);
uint32_t r_type = info->O->getAnyRelocationType(RE);
if (r_type == MachO::ARM64_RELOC_ADDEND) {
DataRefImpl RelNext = Rel;
info->O->moveRelocationNext(RelNext);
MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
if (value == 0) {
value = info->O->getPlainRelocationSymbolNum(RENext);
op_info->Value = value;
}
}
// NOTE: Scattered relocations don't exist on arm64.
if (!info->O->getPlainRelocationExternal(RE))
return 0;
ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
if (std::error_code EC = SymName.getError())
report_fatal_error(EC.message());
const char *name = SymName->data();
op_info->AddSymbol.Present = 1;
op_info->AddSymbol.Name = name;
switch (r_type) {
case MachO::ARM64_RELOC_PAGE21:
/* @page */
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
break;
case MachO::ARM64_RELOC_PAGEOFF12:
/* @pageoff */
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
break;
case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
/* @gotpage */
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
break;
case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
/* @gotpageoff */
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
break;
case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
/* @tvlppage is not implemented in llvm-mc */
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
break;
case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
/* @tvlppageoff is not implemented in llvm-mc */
op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
break;
default:
case MachO::ARM64_RELOC_BRANCH26:
op_info->VariantKind = LLVMDisassembler_VariantKind_None;
break;
}
return 1;
}
return 0;
}
// GuessCstringPointer is passed the address of what might be a pointer to a
// literal string in a cstring section. If that address is in a cstring section
// it returns a pointer to that string. Else it returns nullptr.
static const char *GuessCstringPointer(uint64_t ReferenceValue,
struct DisassembleInfo *info) {
for (const auto &Load : info->O->load_commands()) {
if (Load.C.cmd == MachO::LC_SEGMENT_64) {
MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
for (unsigned J = 0; J < Seg.nsects; ++J) {
MachO::section_64 Sec = info->O->getSection64(Load, J);
uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
if (section_type == MachO::S_CSTRING_LITERALS &&
ReferenceValue >= Sec.addr &&
ReferenceValue < Sec.addr + Sec.size) {
uint64_t sect_offset = ReferenceValue - Sec.addr;
uint64_t object_offset = Sec.offset + sect_offset;
StringRef MachOContents = info->O->getData();
uint64_t object_size = MachOContents.size();
const char *object_addr = (const char *)MachOContents.data();
if (object_offset < object_size) {
const char *name = object_addr + object_offset;
return name;
} else {
return nullptr;
}
}
}
} else if (Load.C.cmd == MachO::LC_SEGMENT) {
MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
for (unsigned J = 0; J < Seg.nsects; ++J) {
MachO::section Sec = info->O->getSection(Load, J);
uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
if (section_type == MachO::S_CSTRING_LITERALS &&
ReferenceValue >= Sec.addr &&
ReferenceValue < Sec.addr + Sec.size) {
uint64_t sect_offset = ReferenceValue - Sec.addr;
uint64_t object_offset = Sec.offset + sect_offset;
StringRef MachOContents = info->O->getData();
uint64_t object_size = MachOContents.size();
const char *object_addr = (const char *)MachOContents.data();
if (object_offset < object_size) {
const char *name = object_addr + object_offset;
return name;
} else {
return nullptr;
}
}
}
}
}
return nullptr;
}
// GuessIndirectSymbol returns the name of the indirect symbol for the
// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
// an address of a symbol stub or a lazy or non-lazy pointer to associate the
// symbol name being referenced by the stub or pointer.
static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
struct DisassembleInfo *info) {
MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
for (const auto &Load : info->O->load_commands()) {
if (Load.C.cmd == MachO::LC_SEGMENT_64) {
MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
for (unsigned J = 0; J < Seg.nsects; ++J) {
MachO::section_64 Sec = info->O->getSection64(Load, J);
uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
section_type == MachO::S_SYMBOL_STUBS) &&
ReferenceValue >= Sec.addr &&
ReferenceValue < Sec.addr + Sec.size) {
uint32_t stride;
if (section_type == MachO::S_SYMBOL_STUBS)
stride = Sec.reserved2;
else
stride = 8;
if (stride == 0)
return nullptr;
uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
if (index < Dysymtab.nindirectsyms) {
uint32_t indirect_symbol =
info->O->getIndirectSymbolTableEntry(Dysymtab, index);
if (indirect_symbol < Symtab.nsyms) {
symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
SymbolRef Symbol = *Sym;
ErrorOr<StringRef> SymName = Symbol.getName();
if (std::error_code EC = SymName.getError())
report_fatal_error(EC.message());
const char *name = SymName->data();
return name;
}
}
}
}
} else if (Load.C.cmd == MachO::LC_SEGMENT) {
MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
for (unsigned J = 0; J < Seg.nsects; ++J) {
MachO::section Sec = info->O->getSection(Load, J);
uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
section_type == MachO::S_SYMBOL_STUBS) &&
ReferenceValue >= Sec.addr &&
ReferenceValue < Sec.addr + Sec.size) {
uint32_t stride;
if (section_type == MachO::S_SYMBOL_STUBS)
stride = Sec.reserved2;
else
stride = 4;
if (stride == 0)
return nullptr;
uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
if (index < Dysymtab.nindirectsyms) {
uint32_t indirect_symbol =
info->O->getIndirectSymbolTableEntry(Dysymtab, index);
if (indirect_symbol < Symtab.nsyms) {
symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
SymbolRef Symbol = *Sym;
ErrorOr<StringRef> SymName = Symbol.getName();
if (std::error_code EC = SymName.getError())
report_fatal_error(EC.message());
const char *name = SymName->data();
return name;
}
}
}
}
}
}
return nullptr;
}
// method_reference() is called passing it the ReferenceName that might be
// a reference it to an Objective-C method call. If so then it allocates and
// assembles a method call string with the values last seen and saved in
// the DisassembleInfo's class_name and selector_name fields. This is saved
// into the method field of the info and any previous string is free'ed.
// Then the class_name field in the info is set to nullptr. The method call
// string is set into ReferenceName and ReferenceType is set to
// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
// then both ReferenceType and ReferenceName are left unchanged.
static void method_reference(struct DisassembleInfo *info,
uint64_t *ReferenceType,
const char **ReferenceName) {
unsigned int Arch = info->O->getArch();
if (*ReferenceName != nullptr) {
if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
if (info->selector_name != nullptr) {
if (info->method != nullptr)
free(info->method);
if (info->class_name != nullptr) {
info->method = (char *)malloc(5 + strlen(info->class_name) +
strlen(info->selector_name));
if (info->method != nullptr) {
strcpy(info->method, "+[");
strcat(info->method, info->class_name);
strcat(info->method, " ");
strcat(info->method, info->selector_name);
strcat(info->method, "]");
*ReferenceName = info->method;
*ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
}
} else {
info->method = (char *)malloc(9 + strlen(info->selector_name));
if (info->method != nullptr) {
if (Arch == Triple::x86_64)
strcpy(info->method, "-[%rdi ");
else if (Arch == Triple::aarch64)
strcpy(info->method, "-[x0 ");
else
strcpy(info->method, "-[r? ");
strcat(info->method, info->selector_name);
strcat(info->method, "]");
*ReferenceName = info->method;
*ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
}
}
info->class_name = nullptr;
}
} else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
if (info->selector_name != nullptr) {
if (info->method != nullptr)
free(info->method);
info->method = (char *)malloc(17 + strlen(info->selector_name));
if (info->method != nullptr) {
if (Arch == Triple::x86_64)
strcpy(info->method, "-[[%rdi super] ");
else if (Arch == Triple::aarch64)
strcpy(info->method, "-[[x0 super] ");
else
strcpy(info->method, "-[[r? super] ");
strcat(info->method, info->selector_name);
strcat(info->method, "]");
*ReferenceName = info->method;
*ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
}
info->class_name = nullptr;
}
}
}
}
// GuessPointerPointer() is passed the address of what might be a pointer to
// a reference to an Objective-C class, selector, message ref or cfstring.
// If so the value of the pointer is returned and one of the booleans are set
// to true. If not zero is returned and all the booleans are set to false.
static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
struct DisassembleInfo *info,
bool &classref, bool &selref, bool &msgref,
bool &cfstring) {
classref = false;
selref = false;
msgref = false;
cfstring = false;
for (const auto &Load : info->O->load_commands()) {
if (Load.C.cmd == MachO::LC_SEGMENT_64) {
MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
for (unsigned J = 0; J < Seg.nsects; ++J) {
MachO::section_64 Sec = info->O->getSection64(Load, J);
if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
ReferenceValue >= Sec.addr &&
ReferenceValue < Sec.addr + Sec.size) {
uint64_t sect_offset = ReferenceValue - Sec.addr;
uint64_t object_offset = Sec.offset + sect_offset;
StringRef MachOContents = info->O->getData();
uint64_t object_size = MachOContents.size();
const char *object_addr = (const char *)MachOContents.data();
if (object_offset < object_size) {
uint64_t pointer_value;
memcpy(&pointer_value, object_addr + object_offset,
sizeof(uint64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(pointer_value);
if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
selref = true;
else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
classref = true;
else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
ReferenceValue + 8 < Sec.addr + Sec.size) {
msgref = true;
memcpy(&pointer_value, object_addr + object_offset + 8,
sizeof(uint64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(pointer_value);
} else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
cfstring = true;
return pointer_value;
} else {
return 0;
}
}
}
}
// TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
}
return 0;
}
// get_pointer_64 returns a pointer to the bytes in the object file at the
// Address from a section in the Mach-O file. And indirectly returns the
// offset into the section, number of bytes left in the section past the offset
// and which section is was being referenced. If the Address is not in a
// section nullptr is returned.
static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
uint32_t &left, SectionRef &S,
DisassembleInfo *info,
bool objc_only = false) {
offset = 0;
left = 0;
S = SectionRef();
for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
if (SectSize == 0)
continue;
if (objc_only) {
StringRef SectName;
((*(info->Sections))[SectIdx]).getName(SectName);
DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
if (SegName != "__OBJC" && SectName != "__cstring")
continue;
}
if (Address >= SectAddress && Address < SectAddress + SectSize) {
S = (*(info->Sections))[SectIdx];
offset = Address - SectAddress;
left = SectSize - offset;
StringRef SectContents;
((*(info->Sections))[SectIdx]).getContents(SectContents);
return SectContents.data() + offset;
}
}
return nullptr;
}
static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
uint32_t &left, SectionRef &S,
DisassembleInfo *info,
bool objc_only = false) {
return get_pointer_64(Address, offset, left, S, info, objc_only);
}
// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
// the symbol indirectly through n_value. Based on the relocation information
// for the specified section offset in the specified section reference.
// If no relocation information is found and a non-zero ReferenceValue for the
// symbol is passed, look up that address in the info's AddrMap.
static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
DisassembleInfo *info, uint64_t &n_value,
uint64_t ReferenceValue = 0) {
n_value = 0;
if (!info->verbose)
return nullptr;
// See if there is an external relocation entry at the sect_offset.
bool reloc_found = false;
DataRefImpl Rel;
MachO::any_relocation_info RE;
bool isExtern = false;
SymbolRef Symbol;
for (const RelocationRef &Reloc : S.relocations()) {
uint64_t RelocOffset = Reloc.getOffset();
if (RelocOffset == sect_offset) {
Rel = Reloc.getRawDataRefImpl();
RE = info->O->getRelocation(Rel);
if (info->O->isRelocationScattered(RE))
continue;
isExtern = info->O->getPlainRelocationExternal(RE);
if (isExtern) {
symbol_iterator RelocSym = Reloc.getSymbol();
Symbol = *RelocSym;
}
reloc_found = true;
break;
}
}
// If there is an external relocation entry for a symbol in this section
// at this section_offset then use that symbol's value for the n_value
// and return its name.
const char *SymbolName = nullptr;
if (reloc_found && isExtern) {
n_value = Symbol.getValue();
ErrorOr<StringRef> NameOrError = Symbol.getName();
if (std::error_code EC = NameOrError.getError())
report_fatal_error(EC.message());
StringRef Name = *NameOrError;
if (!Name.empty()) {
SymbolName = Name.data();
return SymbolName;
}
}
// TODO: For fully linked images, look through the external relocation
// entries off the dynamic symtab command. For these the r_offset is from the
// start of the first writeable segment in the Mach-O file. So the offset
// to this section from that segment is passed to this routine by the caller,
// as the database_offset. Which is the difference of the section's starting
// address and the first writable segment.
//
// NOTE: need add passing the database_offset to this routine.
// We did not find an external relocation entry so look up the ReferenceValue
// as an address of a symbol and if found return that symbol's name.
SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
return SymbolName;
}
static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
DisassembleInfo *info,
uint32_t ReferenceValue) {
uint64_t n_value64;
return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
}
// These are structs in the Objective-C meta data and read to produce the
// comments for disassembly. While these are part of the ABI they are no
// public defintions. So the are here not in include/llvm/Support/MachO.h .
// The cfstring object in a 64-bit Mach-O file.
struct cfstring64_t {
uint64_t isa; // class64_t * (64-bit pointer)
uint64_t flags; // flag bits
uint64_t characters; // char * (64-bit pointer)
uint64_t length; // number of non-NULL characters in above
};
// The class object in a 64-bit Mach-O file.
struct class64_t {
uint64_t isa; // class64_t * (64-bit pointer)
uint64_t superclass; // class64_t * (64-bit pointer)
uint64_t cache; // Cache (64-bit pointer)
uint64_t vtable; // IMP * (64-bit pointer)
uint64_t data; // class_ro64_t * (64-bit pointer)
};
struct class32_t {
uint32_t isa; /* class32_t * (32-bit pointer) */
uint32_t superclass; /* class32_t * (32-bit pointer) */
uint32_t cache; /* Cache (32-bit pointer) */
uint32_t vtable; /* IMP * (32-bit pointer) */
uint32_t data; /* class_ro32_t * (32-bit pointer) */
};
struct class_ro64_t {
uint32_t flags;
uint32_t instanceStart;
uint32_t instanceSize;
uint32_t reserved;
uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
uint64_t name; // const char * (64-bit pointer)
uint64_t baseMethods; // const method_list_t * (64-bit pointer)
uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
uint64_t ivars; // const ivar_list_t * (64-bit pointer)
uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
};
struct class_ro32_t {
uint32_t flags;
uint32_t instanceStart;
uint32_t instanceSize;
uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
uint32_t name; /* const char * (32-bit pointer) */
uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
uint32_t baseProperties; /* const struct objc_property_list *
(32-bit pointer) */
};
/* Values for class_ro{64,32}_t->flags */
#define RO_META (1 << 0)
#define RO_ROOT (1 << 1)
#define RO_HAS_CXX_STRUCTORS (1 << 2)
struct method_list64_t {
uint32_t entsize;
uint32_t count;
/* struct method64_t first; These structures follow inline */
};
struct method_list32_t {
uint32_t entsize;
uint32_t count;
/* struct method32_t first; These structures follow inline */
};
struct method64_t {
uint64_t name; /* SEL (64-bit pointer) */
uint64_t types; /* const char * (64-bit pointer) */
uint64_t imp; /* IMP (64-bit pointer) */
};
struct method32_t {
uint32_t name; /* SEL (32-bit pointer) */
uint32_t types; /* const char * (32-bit pointer) */
uint32_t imp; /* IMP (32-bit pointer) */
};
struct protocol_list64_t {
uint64_t count; /* uintptr_t (a 64-bit value) */
/* struct protocol64_t * list[0]; These pointers follow inline */
};
struct protocol_list32_t {
uint32_t count; /* uintptr_t (a 32-bit value) */
/* struct protocol32_t * list[0]; These pointers follow inline */
};
struct protocol64_t {
uint64_t isa; /* id * (64-bit pointer) */
uint64_t name; /* const char * (64-bit pointer) */
uint64_t protocols; /* struct protocol_list64_t *
(64-bit pointer) */
uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
uint64_t classMethods; /* method_list_t * (64-bit pointer) */
uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
uint64_t instanceProperties; /* struct objc_property_list *
(64-bit pointer) */
};
struct protocol32_t {
uint32_t isa; /* id * (32-bit pointer) */
uint32_t name; /* const char * (32-bit pointer) */
uint32_t protocols; /* struct protocol_list_t *
(32-bit pointer) */
uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
uint32_t classMethods; /* method_list_t * (32-bit pointer) */
uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
uint32_t instanceProperties; /* struct objc_property_list *
(32-bit pointer) */
};
struct ivar_list64_t {
uint32_t entsize;
uint32_t count;
/* struct ivar64_t first; These structures follow inline */
};
struct ivar_list32_t {
uint32_t entsize;
uint32_t count;
/* struct ivar32_t first; These structures follow inline */
};
struct ivar64_t {
uint64_t offset; /* uintptr_t * (64-bit pointer) */
uint64_t name; /* const char * (64-bit pointer) */
uint64_t type; /* const char * (64-bit pointer) */
uint32_t alignment;
uint32_t size;
};
struct ivar32_t {
uint32_t offset; /* uintptr_t * (32-bit pointer) */
uint32_t name; /* const char * (32-bit pointer) */
uint32_t type; /* const char * (32-bit pointer) */
uint32_t alignment;
uint32_t size;
};
struct objc_property_list64 {
uint32_t entsize;
uint32_t count;
/* struct objc_property64 first; These structures follow inline */
};
struct objc_property_list32 {
uint32_t entsize;
uint32_t count;
/* struct objc_property32 first; These structures follow inline */
};
struct objc_property64 {
uint64_t name; /* const char * (64-bit pointer) */
uint64_t attributes; /* const char * (64-bit pointer) */
};
struct objc_property32 {
uint32_t name; /* const char * (32-bit pointer) */
uint32_t attributes; /* const char * (32-bit pointer) */
};
struct category64_t {
uint64_t name; /* const char * (64-bit pointer) */
uint64_t cls; /* struct class_t * (64-bit pointer) */
uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
uint64_t instanceProperties; /* struct objc_property_list *
(64-bit pointer) */
};
struct category32_t {
uint32_t name; /* const char * (32-bit pointer) */
uint32_t cls; /* struct class_t * (32-bit pointer) */
uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
uint32_t instanceProperties; /* struct objc_property_list *
(32-bit pointer) */
};
struct objc_image_info64 {
uint32_t version;
uint32_t flags;
};
struct objc_image_info32 {
uint32_t version;
uint32_t flags;
};
struct imageInfo_t {
uint32_t version;
uint32_t flags;
};
/* masks for objc_image_info.flags */
#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
struct message_ref64 {
uint64_t imp; /* IMP (64-bit pointer) */
uint64_t sel; /* SEL (64-bit pointer) */
};
struct message_ref32 {
uint32_t imp; /* IMP (32-bit pointer) */
uint32_t sel; /* SEL (32-bit pointer) */
};
// Objective-C 1 (32-bit only) meta data structs.
struct objc_module_t {
uint32_t version;
uint32_t size;
uint32_t name; /* char * (32-bit pointer) */
uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
};
struct objc_symtab_t {
uint32_t sel_ref_cnt;
uint32_t refs; /* SEL * (32-bit pointer) */
uint16_t cls_def_cnt;
uint16_t cat_def_cnt;
// uint32_t defs[1]; /* void * (32-bit pointer) variable size */
};
struct objc_class_t {
uint32_t isa; /* struct objc_class * (32-bit pointer) */
uint32_t super_class; /* struct objc_class * (32-bit pointer) */
uint32_t name; /* const char * (32-bit pointer) */
int32_t version;
int32_t info;
int32_t instance_size;
uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
uint32_t cache; /* struct objc_cache * (32-bit pointer) */
uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
};
#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
// class is not a metaclass
#define CLS_CLASS 0x1
// class is a metaclass
#define CLS_META 0x2
struct objc_category_t {
uint32_t category_name; /* char * (32-bit pointer) */
uint32_t class_name; /* char * (32-bit pointer) */
uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
};
struct objc_ivar_t {
uint32_t ivar_name; /* char * (32-bit pointer) */
uint32_t ivar_type; /* char * (32-bit pointer) */
int32_t ivar_offset;
};
struct objc_ivar_list_t {
int32_t ivar_count;
// struct objc_ivar_t ivar_list[1]; /* variable length structure */
};
struct objc_method_list_t {
uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
int32_t method_count;
// struct objc_method_t method_list[1]; /* variable length structure */
};
struct objc_method_t {
uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
uint32_t method_types; /* char * (32-bit pointer) */
uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
(32-bit pointer) */
};
struct objc_protocol_list_t {
uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
int32_t count;
// uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
// (32-bit pointer) */
};
struct objc_protocol_t {
uint32_t isa; /* struct objc_class * (32-bit pointer) */
uint32_t protocol_name; /* char * (32-bit pointer) */
uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
uint32_t instance_methods; /* struct objc_method_description_list *
(32-bit pointer) */
uint32_t class_methods; /* struct objc_method_description_list *
(32-bit pointer) */
};
struct objc_method_description_list_t {
int32_t count;
// struct objc_method_description_t list[1];
};
struct objc_method_description_t {
uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
uint32_t types; /* char * (32-bit pointer) */
};
inline void swapStruct(struct cfstring64_t &cfs) {
sys::swapByteOrder(cfs.isa);
sys::swapByteOrder(cfs.flags);
sys::swapByteOrder(cfs.characters);
sys::swapByteOrder(cfs.length);
}
inline void swapStruct(struct class64_t &c) {
sys::swapByteOrder(c.isa);
sys::swapByteOrder(c.superclass);
sys::swapByteOrder(c.cache);
sys::swapByteOrder(c.vtable);
sys::swapByteOrder(c.data);
}
inline void swapStruct(struct class32_t &c) {
sys::swapByteOrder(c.isa);
sys::swapByteOrder(c.superclass);
sys::swapByteOrder(c.cache);
sys::swapByteOrder(c.vtable);
sys::swapByteOrder(c.data);
}
inline void swapStruct(struct class_ro64_t &cro) {
sys::swapByteOrder(cro.flags);
sys::swapByteOrder(cro.instanceStart);
sys::swapByteOrder(cro.instanceSize);
sys::swapByteOrder(cro.reserved);
sys::swapByteOrder(cro.ivarLayout);
sys::swapByteOrder(cro.name);
sys::swapByteOrder(cro.baseMethods);
sys::swapByteOrder(cro.baseProtocols);
sys::swapByteOrder(cro.ivars);
sys::swapByteOrder(cro.weakIvarLayout);
sys::swapByteOrder(cro.baseProperties);
}
inline void swapStruct(struct class_ro32_t &cro) {
sys::swapByteOrder(cro.flags);
sys::swapByteOrder(cro.instanceStart);
sys::swapByteOrder(cro.instanceSize);
sys::swapByteOrder(cro.ivarLayout);
sys::swapByteOrder(cro.name);
sys::swapByteOrder(cro.baseMethods);
sys::swapByteOrder(cro.baseProtocols);
sys::swapByteOrder(cro.ivars);
sys::swapByteOrder(cro.weakIvarLayout);
sys::swapByteOrder(cro.baseProperties);
}
inline void swapStruct(struct method_list64_t &ml) {
sys::swapByteOrder(ml.entsize);
sys::swapByteOrder(ml.count);
}
inline void swapStruct(struct method_list32_t &ml) {
sys::swapByteOrder(ml.entsize);
sys::swapByteOrder(ml.count);
}
inline void swapStruct(struct method64_t &m) {
sys::swapByteOrder(m.name);
sys::swapByteOrder(m.types);
sys::swapByteOrder(m.imp);
}
inline void swapStruct(struct method32_t &m) {
sys::swapByteOrder(m.name);
sys::swapByteOrder(m.types);
sys::swapByteOrder(m.imp);
}
inline void swapStruct(struct protocol_list64_t &pl) {
sys::swapByteOrder(pl.count);
}
inline void swapStruct(struct protocol_list32_t &pl) {
sys::swapByteOrder(pl.count);
}
inline void swapStruct(struct protocol64_t &p) {
sys::swapByteOrder(p.isa);
sys::swapByteOrder(p.name);
sys::swapByteOrder(p.protocols);
sys::swapByteOrder(p.instanceMethods);
sys::swapByteOrder(p.classMethods);
sys::swapByteOrder(p.optionalInstanceMethods);
sys::swapByteOrder(p.optionalClassMethods);
sys::swapByteOrder(p.instanceProperties);
}
inline void swapStruct(struct protocol32_t &p) {
sys::swapByteOrder(p.isa);
sys::swapByteOrder(p.name);
sys::swapByteOrder(p.protocols);
sys::swapByteOrder(p.instanceMethods);
sys::swapByteOrder(p.classMethods);
sys::swapByteOrder(p.optionalInstanceMethods);
sys::swapByteOrder(p.optionalClassMethods);
sys::swapByteOrder(p.instanceProperties);
}
inline void swapStruct(struct ivar_list64_t &il) {
sys::swapByteOrder(il.entsize);
sys::swapByteOrder(il.count);
}
inline void swapStruct(struct ivar_list32_t &il) {
sys::swapByteOrder(il.entsize);
sys::swapByteOrder(il.count);
}
inline void swapStruct(struct ivar64_t &i) {
sys::swapByteOrder(i.offset);
sys::swapByteOrder(i.name);
sys::swapByteOrder(i.type);
sys::swapByteOrder(i.alignment);
sys::swapByteOrder(i.size);
}
inline void swapStruct(struct ivar32_t &i) {
sys::swapByteOrder(i.offset);
sys::swapByteOrder(i.name);
sys::swapByteOrder(i.type);
sys::swapByteOrder(i.alignment);
sys::swapByteOrder(i.size);
}
inline void swapStruct(struct objc_property_list64 &pl) {
sys::swapByteOrder(pl.entsize);
sys::swapByteOrder(pl.count);
}
inline void swapStruct(struct objc_property_list32 &pl) {
sys::swapByteOrder(pl.entsize);
sys::swapByteOrder(pl.count);
}
inline void swapStruct(struct objc_property64 &op) {
sys::swapByteOrder(op.name);
sys::swapByteOrder(op.attributes);
}
inline void swapStruct(struct objc_property32 &op) {
sys::swapByteOrder(op.name);
sys::swapByteOrder(op.attributes);
}
inline void swapStruct(struct category64_t &c) {
sys::swapByteOrder(c.name);
sys::swapByteOrder(c.cls);
sys::swapByteOrder(c.instanceMethods);
sys::swapByteOrder(c.classMethods);
sys::swapByteOrder(c.protocols);
sys::swapByteOrder(c.instanceProperties);
}
inline void swapStruct(struct category32_t &c) {
sys::swapByteOrder(c.name);
sys::swapByteOrder(c.cls);
sys::swapByteOrder(c.instanceMethods);
sys::swapByteOrder(c.classMethods);
sys::swapByteOrder(c.protocols);
sys::swapByteOrder(c.instanceProperties);
}
inline void swapStruct(struct objc_image_info64 &o) {
sys::swapByteOrder(o.version);
sys::swapByteOrder(o.flags);
}
inline void swapStruct(struct objc_image_info32 &o) {
sys::swapByteOrder(o.version);
sys::swapByteOrder(o.flags);
}
inline void swapStruct(struct imageInfo_t &o) {
sys::swapByteOrder(o.version);
sys::swapByteOrder(o.flags);
}
inline void swapStruct(struct message_ref64 &mr) {
sys::swapByteOrder(mr.imp);
sys::swapByteOrder(mr.sel);
}
inline void swapStruct(struct message_ref32 &mr) {
sys::swapByteOrder(mr.imp);
sys::swapByteOrder(mr.sel);
}
inline void swapStruct(struct objc_module_t &module) {
sys::swapByteOrder(module.version);
sys::swapByteOrder(module.size);
sys::swapByteOrder(module.name);
sys::swapByteOrder(module.symtab);
}
inline void swapStruct(struct objc_symtab_t &symtab) {
sys::swapByteOrder(symtab.sel_ref_cnt);
sys::swapByteOrder(symtab.refs);
sys::swapByteOrder(symtab.cls_def_cnt);
sys::swapByteOrder(symtab.cat_def_cnt);
}
inline void swapStruct(struct objc_class_t &objc_class) {
sys::swapByteOrder(objc_class.isa);
sys::swapByteOrder(objc_class.super_class);
sys::swapByteOrder(objc_class.name);
sys::swapByteOrder(objc_class.version);
sys::swapByteOrder(objc_class.info);
sys::swapByteOrder(objc_class.instance_size);
sys::swapByteOrder(objc_class.ivars);
sys::swapByteOrder(objc_class.methodLists);
sys::swapByteOrder(objc_class.cache);
sys::swapByteOrder(objc_class.protocols);
}
inline void swapStruct(struct objc_category_t &objc_category) {
sys::swapByteOrder(objc_category.category_name);
sys::swapByteOrder(objc_category.class_name);
sys::swapByteOrder(objc_category.instance_methods);
sys::swapByteOrder(objc_category.class_methods);
sys::swapByteOrder(objc_category.protocols);
}
inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
sys::swapByteOrder(objc_ivar_list.ivar_count);
}
inline void swapStruct(struct objc_ivar_t &objc_ivar) {
sys::swapByteOrder(objc_ivar.ivar_name);
sys::swapByteOrder(objc_ivar.ivar_type);
sys::swapByteOrder(objc_ivar.ivar_offset);
}
inline void swapStruct(struct objc_method_list_t &method_list) {
sys::swapByteOrder(method_list.obsolete);
sys::swapByteOrder(method_list.method_count);
}
inline void swapStruct(struct objc_method_t &method) {
sys::swapByteOrder(method.method_name);
sys::swapByteOrder(method.method_types);
sys::swapByteOrder(method.method_imp);
}
inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
sys::swapByteOrder(protocol_list.next);
sys::swapByteOrder(protocol_list.count);
}
inline void swapStruct(struct objc_protocol_t &protocol) {
sys::swapByteOrder(protocol.isa);
sys::swapByteOrder(protocol.protocol_name);
sys::swapByteOrder(protocol.protocol_list);
sys::swapByteOrder(protocol.instance_methods);
sys::swapByteOrder(protocol.class_methods);
}
inline void swapStruct(struct objc_method_description_list_t &mdl) {
sys::swapByteOrder(mdl.count);
}
inline void swapStruct(struct objc_method_description_t &md) {
sys::swapByteOrder(md.name);
sys::swapByteOrder(md.types);
}
static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
struct DisassembleInfo *info);
// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
// to an Objective-C class and returns the class name. It is also passed the
// address of the pointer, so when the pointer is zero as it can be in an .o
// file, that is used to look for an external relocation entry with a symbol
// name.
static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
uint64_t ReferenceValue,
struct DisassembleInfo *info) {
const char *r;
uint32_t offset, left;
SectionRef S;
// The pointer_value can be 0 in an object file and have a relocation
// entry for the class symbol at the ReferenceValue (the address of the
// pointer).
if (pointer_value == 0) {
r = get_pointer_64(ReferenceValue, offset, left, S, info);
if (r == nullptr || left < sizeof(uint64_t))
return nullptr;
uint64_t n_value;
const char *symbol_name = get_symbol_64(offset, S, info, n_value);
if (symbol_name == nullptr)
return nullptr;
const char *class_name = strrchr(symbol_name, '$');
if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
return class_name + 2;
else
return nullptr;
}
// The case were the pointer_value is non-zero and points to a class defined
// in this Mach-O file.
r = get_pointer_64(pointer_value, offset, left, S, info);
if (r == nullptr || left < sizeof(struct class64_t))
return nullptr;
struct class64_t c;
memcpy(&c, r, sizeof(struct class64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(c);
if (c.data == 0)
return nullptr;
r = get_pointer_64(c.data, offset, left, S, info);
if (r == nullptr || left < sizeof(struct class_ro64_t))
return nullptr;
struct class_ro64_t cro;
memcpy(&cro, r, sizeof(struct class_ro64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(cro);
if (cro.name == 0)
return nullptr;
const char *name = get_pointer_64(cro.name, offset, left, S, info);
return name;
}
// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
// pointer to a cfstring and returns its name or nullptr.
static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
struct DisassembleInfo *info) {
const char *r, *name;
uint32_t offset, left;
SectionRef S;
struct cfstring64_t cfs;
uint64_t cfs_characters;
r = get_pointer_64(ReferenceValue, offset, left, S, info);
if (r == nullptr || left < sizeof(struct cfstring64_t))
return nullptr;
memcpy(&cfs, r, sizeof(struct cfstring64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(cfs);
if (cfs.characters == 0) {
uint64_t n_value;
const char *symbol_name = get_symbol_64(
offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
if (symbol_name == nullptr)
return nullptr;
cfs_characters = n_value;
} else
cfs_characters = cfs.characters;
name = get_pointer_64(cfs_characters, offset, left, S, info);
return name;
}
// get_objc2_64bit_selref() is used for disassembly and is passed a the address
// of a pointer to an Objective-C selector reference when the pointer value is
// zero as in a .o file and is likely to have a external relocation entry with
// who's symbol's n_value is the real pointer to the selector name. If that is
// the case the real pointer to the selector name is returned else 0 is
// returned
static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
struct DisassembleInfo *info) {
uint32_t offset, left;
SectionRef S;
const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
if (r == nullptr || left < sizeof(uint64_t))
return 0;
uint64_t n_value;
const char *symbol_name = get_symbol_64(offset, S, info, n_value);
if (symbol_name == nullptr)
return 0;
return n_value;
}
static const SectionRef get_section(MachOObjectFile *O, const char *segname,
const char *sectname) {
for (const SectionRef &Section : O->sections()) {
StringRef SectName;
Section.getName(SectName);
DataRefImpl Ref = Section.getRawDataRefImpl();
StringRef SegName = O->getSectionFinalSegmentName(Ref);
if (SegName == segname && SectName == sectname)
return Section;
}
return SectionRef();
}
static void
walk_pointer_list_64(const char *listname, const SectionRef S,
MachOObjectFile *O, struct DisassembleInfo *info,
void (*func)(uint64_t, struct DisassembleInfo *info)) {
if (S == SectionRef())
return;
StringRef SectName;
S.getName(SectName);
DataRefImpl Ref = S.getRawDataRefImpl();
StringRef SegName = O->getSectionFinalSegmentName(Ref);
outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
StringRef BytesStr;
S.getContents(BytesStr);
const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
uint32_t left = S.getSize() - i;
uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
uint64_t p = 0;
memcpy(&p, Contents + i, size);
if (i + sizeof(uint64_t) > S.getSize())
outs() << listname << " list pointer extends past end of (" << SegName
<< "," << SectName << ") section\n";
outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(p);
uint64_t n_value = 0;
const char *name = get_symbol_64(i, S, info, n_value, p);
if (name == nullptr)
name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
if (n_value != 0) {
outs() << format("0x%" PRIx64, n_value);
if (p != 0)
outs() << " + " << format("0x%" PRIx64, p);
} else
outs() << format("0x%" PRIx64, p);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
p += n_value;
if (func)
func(p, info);
}
}
static void
walk_pointer_list_32(const char *listname, const SectionRef S,
MachOObjectFile *O, struct DisassembleInfo *info,
void (*func)(uint32_t, struct DisassembleInfo *info)) {
if (S == SectionRef())
return;
StringRef SectName;
S.getName(SectName);
DataRefImpl Ref = S.getRawDataRefImpl();
StringRef SegName = O->getSectionFinalSegmentName(Ref);
outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
StringRef BytesStr;
S.getContents(BytesStr);
const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
uint32_t left = S.getSize() - i;
uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
uint32_t p = 0;
memcpy(&p, Contents + i, size);
if (i + sizeof(uint32_t) > S.getSize())
outs() << listname << " list pointer extends past end of (" << SegName
<< "," << SectName << ") section\n";
uint32_t Address = S.getAddress() + i;
outs() << format("%08" PRIx32, Address) << " ";
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(p);
outs() << format("0x%" PRIx32, p);
const char *name = get_symbol_32(i, S, info, p);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
if (func)
func(p, info);
}
}
static void print_layout_map(const char *layout_map, uint32_t left) {
if (layout_map == nullptr)
return;
outs() << " layout map: ";
do {
outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
left--;
layout_map++;
} while (*layout_map != '\0' && left != 0);
outs() << "\n";
}
static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
uint32_t offset, left;
SectionRef S;
const char *layout_map;
if (p == 0)
return;
layout_map = get_pointer_64(p, offset, left, S, info);
print_layout_map(layout_map, left);
}
static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
uint32_t offset, left;
SectionRef S;
const char *layout_map;
if (p == 0)
return;
layout_map = get_pointer_32(p, offset, left, S, info);
print_layout_map(layout_map, left);
}
static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
const char *indent) {
struct method_list64_t ml;
struct method64_t m;
const char *r;
uint32_t offset, xoffset, left, i;
SectionRef S, xS;
const char *name, *sym_name;
uint64_t n_value;
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&ml, '\0', sizeof(struct method_list64_t));
if (left < sizeof(struct method_list64_t)) {
memcpy(&ml, r, left);
outs() << " (method_list_t entends past the end of the section)\n";
} else
memcpy(&ml, r, sizeof(struct method_list64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(ml);
outs() << indent << "\t\t entsize " << ml.entsize << "\n";
outs() << indent << "\t\t count " << ml.count << "\n";
p += sizeof(struct method_list64_t);
offset += sizeof(struct method_list64_t);
for (i = 0; i < ml.count; i++) {
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&m, '\0', sizeof(struct method64_t));
if (left < sizeof(struct method64_t)) {
memcpy(&m, r, left);
outs() << indent << " (method_t extends past the end of the section)\n";
} else
memcpy(&m, r, sizeof(struct method64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(m);
outs() << indent << "\t\t name ";
sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
info, n_value, m.name);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (m.name != 0)
outs() << " + " << format("0x%" PRIx64, m.name);
} else
outs() << format("0x%" PRIx64, m.name);
name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << indent << "\t\t types ";
sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
info, n_value, m.types);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (m.types != 0)
outs() << " + " << format("0x%" PRIx64, m.types);
} else
outs() << format("0x%" PRIx64, m.types);
name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << indent << "\t\t imp ";
name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
n_value, m.imp);
if (info->verbose && name == nullptr) {
if (n_value != 0) {
outs() << format("0x%" PRIx64, n_value) << " ";
if (m.imp != 0)
outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
} else
outs() << format("0x%" PRIx64, m.imp) << " ";
}
if (name != nullptr)
outs() << name;
outs() << "\n";
p += sizeof(struct method64_t);
offset += sizeof(struct method64_t);
}
}
static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
const char *indent) {
struct method_list32_t ml;
struct method32_t m;
const char *r, *name;
uint32_t offset, xoffset, left, i;
SectionRef S, xS;
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&ml, '\0', sizeof(struct method_list32_t));
if (left < sizeof(struct method_list32_t)) {
memcpy(&ml, r, left);
outs() << " (method_list_t entends past the end of the section)\n";
} else
memcpy(&ml, r, sizeof(struct method_list32_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(ml);
outs() << indent << "\t\t entsize " << ml.entsize << "\n";
outs() << indent << "\t\t count " << ml.count << "\n";
p += sizeof(struct method_list32_t);
offset += sizeof(struct method_list32_t);
for (i = 0; i < ml.count; i++) {
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&m, '\0', sizeof(struct method32_t));
if (left < sizeof(struct method32_t)) {
memcpy(&ml, r, left);
outs() << indent << " (method_t entends past the end of the section)\n";
} else
memcpy(&m, r, sizeof(struct method32_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(m);
outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
name = get_pointer_32(m.name, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
name = get_pointer_32(m.types, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
m.imp);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
p += sizeof(struct method32_t);
offset += sizeof(struct method32_t);
}
}
static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
uint32_t offset, left, xleft;
SectionRef S;
struct objc_method_list_t method_list;
struct objc_method_t method;
const char *r, *methods, *name, *SymbolName;
int32_t i;
r = get_pointer_32(p, offset, left, S, info, true);
if (r == nullptr)
return true;
outs() << "\n";
if (left > sizeof(struct objc_method_list_t)) {
memcpy(&method_list, r, sizeof(struct objc_method_list_t));
} else {
outs() << "\t\t objc_method_list extends past end of the section\n";
memset(&method_list, '\0', sizeof(struct objc_method_list_t));
memcpy(&method_list, r, left);
}
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(method_list);
outs() << "\t\t obsolete "
<< format("0x%08" PRIx32, method_list.obsolete) << "\n";
outs() << "\t\t method_count " << method_list.method_count << "\n";
methods = r + sizeof(struct objc_method_list_t);
for (i = 0; i < method_list.method_count; i++) {
if ((i + 1) * sizeof(struct objc_method_t) > left) {
outs() << "\t\t remaining method's extend past the of the section\n";
break;
}
memcpy(&method, methods + i * sizeof(struct objc_method_t),
sizeof(struct objc_method_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(method);
outs() << "\t\t method_name "
<< format("0x%08" PRIx32, method.method_name);
if (info->verbose) {
name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
if (name != nullptr)
outs() << format(" %.*s", xleft, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
outs() << "\t\t method_types "
<< format("0x%08" PRIx32, method.method_types);
if (info->verbose) {
name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
if (name != nullptr)
outs() << format(" %.*s", xleft, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
outs() << "\t\t method_imp "
<< format("0x%08" PRIx32, method.method_imp) << " ";
if (info->verbose) {
SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
if (SymbolName != nullptr)
outs() << SymbolName;
}
outs() << "\n";
}
return false;
}
static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
struct protocol_list64_t pl;
uint64_t q, n_value;
struct protocol64_t pc;
const char *r;
uint32_t offset, xoffset, left, i;
SectionRef S, xS;
const char *name, *sym_name;
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&pl, '\0', sizeof(struct protocol_list64_t));
if (left < sizeof(struct protocol_list64_t)) {
memcpy(&pl, r, left);
outs() << " (protocol_list_t entends past the end of the section)\n";
} else
memcpy(&pl, r, sizeof(struct protocol_list64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(pl);
outs() << " count " << pl.count << "\n";
p += sizeof(struct protocol_list64_t);
offset += sizeof(struct protocol_list64_t);
for (i = 0; i < pl.count; i++) {
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr)
return;
q = 0;
if (left < sizeof(uint64_t)) {
memcpy(&q, r, left);
outs() << " (protocol_t * entends past the end of the section)\n";
} else
memcpy(&q, r, sizeof(uint64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(q);
outs() << "\t\t list[" << i << "] ";
sym_name = get_symbol_64(offset, S, info, n_value, q);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (q != 0)
outs() << " + " << format("0x%" PRIx64, q);
} else
outs() << format("0x%" PRIx64, q);
outs() << " (struct protocol_t *)\n";
r = get_pointer_64(q + n_value, offset, left, S, info);
if (r == nullptr)
return;
memset(&pc, '\0', sizeof(struct protocol64_t));
if (left < sizeof(struct protocol64_t)) {
memcpy(&pc, r, left);
outs() << " (protocol_t entends past the end of the section)\n";
} else
memcpy(&pc, r, sizeof(struct protocol64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(pc);
outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
outs() << "\t\t\t name ";
sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
info, n_value, pc.name);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (pc.name != 0)
outs() << " + " << format("0x%" PRIx64, pc.name);
} else
outs() << format("0x%" PRIx64, pc.name);
name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
outs() << "\t\t instanceMethods ";
sym_name =
get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
S, info, n_value, pc.instanceMethods);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (pc.instanceMethods != 0)
outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
} else
outs() << format("0x%" PRIx64, pc.instanceMethods);
outs() << " (struct method_list_t *)\n";
if (pc.instanceMethods + n_value != 0)
print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
outs() << "\t\t classMethods ";
sym_name =
get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
info, n_value, pc.classMethods);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (pc.classMethods != 0)
outs() << " + " << format("0x%" PRIx64, pc.classMethods);
} else
outs() << format("0x%" PRIx64, pc.classMethods);
outs() << " (struct method_list_t *)\n";
if (pc.classMethods + n_value != 0)
print_method_list64_t(pc.classMethods + n_value, info, "\t");
outs() << "\t optionalInstanceMethods "
<< format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
outs() << "\t optionalClassMethods "
<< format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
outs() << "\t instanceProperties "
<< format("0x%" PRIx64, pc.instanceProperties) << "\n";
p += sizeof(uint64_t);
offset += sizeof(uint64_t);
}
}
static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
struct protocol_list32_t pl;
uint32_t q;
struct protocol32_t pc;
const char *r;
uint32_t offset, xoffset, left, i;
SectionRef S, xS;
const char *name;
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&pl, '\0', sizeof(struct protocol_list32_t));
if (left < sizeof(struct protocol_list32_t)) {
memcpy(&pl, r, left);
outs() << " (protocol_list_t entends past the end of the section)\n";
} else
memcpy(&pl, r, sizeof(struct protocol_list32_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(pl);
outs() << " count " << pl.count << "\n";
p += sizeof(struct protocol_list32_t);
offset += sizeof(struct protocol_list32_t);
for (i = 0; i < pl.count; i++) {
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
q = 0;
if (left < sizeof(uint32_t)) {
memcpy(&q, r, left);
outs() << " (protocol_t * entends past the end of the section)\n";
} else
memcpy(&q, r, sizeof(uint32_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(q);
outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
<< " (struct protocol_t *)\n";
r = get_pointer_32(q, offset, left, S, info);
if (r == nullptr)
return;
memset(&pc, '\0', sizeof(struct protocol32_t));
if (left < sizeof(struct protocol32_t)) {
memcpy(&pc, r, left);
outs() << " (protocol_t entends past the end of the section)\n";
} else
memcpy(&pc, r, sizeof(struct protocol32_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(pc);
outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
name = get_pointer_32(pc.name, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
outs() << "\t\t instanceMethods "
<< format("0x%" PRIx32, pc.instanceMethods)
<< " (struct method_list_t *)\n";
if (pc.instanceMethods != 0)
print_method_list32_t(pc.instanceMethods, info, "\t");
outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
<< " (struct method_list_t *)\n";
if (pc.classMethods != 0)
print_method_list32_t(pc.classMethods, info, "\t");
outs() << "\t optionalInstanceMethods "
<< format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
outs() << "\t optionalClassMethods "
<< format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
outs() << "\t instanceProperties "
<< format("0x%" PRIx32, pc.instanceProperties) << "\n";
p += sizeof(uint32_t);
offset += sizeof(uint32_t);
}
}
static void print_indent(uint32_t indent) {
for (uint32_t i = 0; i < indent;) {
if (indent - i >= 8) {
outs() << "\t";
i += 8;
} else {
for (uint32_t j = i; j < indent; j++)
outs() << " ";
return;
}
}
}
static bool print_method_description_list(uint32_t p, uint32_t indent,
struct DisassembleInfo *info) {
uint32_t offset, left, xleft;
SectionRef S;
struct objc_method_description_list_t mdl;
struct objc_method_description_t md;
const char *r, *list, *name;
int32_t i;
r = get_pointer_32(p, offset, left, S, info, true);
if (r == nullptr)
return true;
outs() << "\n";
if (left > sizeof(struct objc_method_description_list_t)) {
memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
} else {
print_indent(indent);
outs() << " objc_method_description_list extends past end of the section\n";
memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
memcpy(&mdl, r, left);
}
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(mdl);
print_indent(indent);
outs() << " count " << mdl.count << "\n";
list = r + sizeof(struct objc_method_description_list_t);
for (i = 0; i < mdl.count; i++) {
if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
print_indent(indent);
outs() << " remaining list entries extend past the of the section\n";
break;
}
print_indent(indent);
outs() << " list[" << i << "]\n";
memcpy(&md, list + i * sizeof(struct objc_method_description_t),
sizeof(struct objc_method_description_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(md);
print_indent(indent);
outs() << " name " << format("0x%08" PRIx32, md.name);
if (info->verbose) {
name = get_pointer_32(md.name, offset, xleft, S, info, true);
if (name != nullptr)
outs() << format(" %.*s", xleft, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
print_indent(indent);
outs() << " types " << format("0x%08" PRIx32, md.types);
if (info->verbose) {
name = get_pointer_32(md.types, offset, xleft, S, info, true);
if (name != nullptr)
outs() << format(" %.*s", xleft, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
}
return false;
}
static bool print_protocol_list(uint32_t p, uint32_t indent,
struct DisassembleInfo *info);
static bool print_protocol(uint32_t p, uint32_t indent,
struct DisassembleInfo *info) {
uint32_t offset, left;
SectionRef S;
struct objc_protocol_t protocol;
const char *r, *name;
r = get_pointer_32(p, offset, left, S, info, true);
if (r == nullptr)
return true;
outs() << "\n";
if (left >= sizeof(struct objc_protocol_t)) {
memcpy(&protocol, r, sizeof(struct objc_protocol_t));
} else {
print_indent(indent);
outs() << " Protocol extends past end of the section\n";
memset(&protocol, '\0', sizeof(struct objc_protocol_t));
memcpy(&protocol, r, left);
}
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(protocol);
print_indent(indent);
outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
<< "\n";
print_indent(indent);
outs() << " protocol_name "
<< format("0x%08" PRIx32, protocol.protocol_name);
if (info->verbose) {
name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
if (name != nullptr)
outs() << format(" %.*s", left, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
print_indent(indent);
outs() << " protocol_list "
<< format("0x%08" PRIx32, protocol.protocol_list);
if (print_protocol_list(protocol.protocol_list, indent + 4, info))
outs() << " (not in an __OBJC section)\n";
print_indent(indent);
outs() << " instance_methods "
<< format("0x%08" PRIx32, protocol.instance_methods);
if (print_method_description_list(protocol.instance_methods, indent, info))
outs() << " (not in an __OBJC section)\n";
print_indent(indent);
outs() << " class_methods "
<< format("0x%08" PRIx32, protocol.class_methods);
if (print_method_description_list(protocol.class_methods, indent, info))
outs() << " (not in an __OBJC section)\n";
return false;
}
static bool print_protocol_list(uint32_t p, uint32_t indent,
struct DisassembleInfo *info) {
uint32_t offset, left, l;
SectionRef S;
struct objc_protocol_list_t protocol_list;
const char *r, *list;
int32_t i;
r = get_pointer_32(p, offset, left, S, info, true);
if (r == nullptr)
return true;
outs() << "\n";
if (left > sizeof(struct objc_protocol_list_t)) {
memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
} else {
outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
memcpy(&protocol_list, r, left);
}
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(protocol_list);
print_indent(indent);
outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
<< "\n";
print_indent(indent);
outs() << " count " << protocol_list.count << "\n";
list = r + sizeof(struct objc_protocol_list_t);
for (i = 0; i < protocol_list.count; i++) {
if ((i + 1) * sizeof(uint32_t) > left) {
outs() << "\t\t remaining list entries extend past the of the section\n";
break;
}
memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(l);
print_indent(indent);
outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
if (print_protocol(l, indent, info))
outs() << "(not in an __OBJC section)\n";
}
return false;
}
static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
struct ivar_list64_t il;
struct ivar64_t i;
const char *r;
uint32_t offset, xoffset, left, j;
SectionRef S, xS;
const char *name, *sym_name, *ivar_offset_p;
uint64_t ivar_offset, n_value;
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&il, '\0', sizeof(struct ivar_list64_t));
if (left < sizeof(struct ivar_list64_t)) {
memcpy(&il, r, left);
outs() << " (ivar_list_t entends past the end of the section)\n";
} else
memcpy(&il, r, sizeof(struct ivar_list64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(il);
outs() << " entsize " << il.entsize << "\n";
outs() << " count " << il.count << "\n";
p += sizeof(struct ivar_list64_t);
offset += sizeof(struct ivar_list64_t);
for (j = 0; j < il.count; j++) {
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&i, '\0', sizeof(struct ivar64_t));
if (left < sizeof(struct ivar64_t)) {
memcpy(&i, r, left);
outs() << " (ivar_t entends past the end of the section)\n";
} else
memcpy(&i, r, sizeof(struct ivar64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(i);
outs() << "\t\t\t offset ";
sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
info, n_value, i.offset);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (i.offset != 0)
outs() << " + " << format("0x%" PRIx64, i.offset);
} else
outs() << format("0x%" PRIx64, i.offset);
ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(ivar_offset);
outs() << " " << ivar_offset << "\n";
} else
outs() << "\n";
outs() << "\t\t\t name ";
sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
n_value, i.name);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (i.name != 0)
outs() << " + " << format("0x%" PRIx64, i.name);
} else
outs() << format("0x%" PRIx64, i.name);
name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << "\t\t\t type ";
sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
n_value, i.name);
name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (i.type != 0)
outs() << " + " << format("0x%" PRIx64, i.type);
} else
outs() << format("0x%" PRIx64, i.type);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << "\t\t\talignment " << i.alignment << "\n";
outs() << "\t\t\t size " << i.size << "\n";
p += sizeof(struct ivar64_t);
offset += sizeof(struct ivar64_t);
}
}
static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
struct ivar_list32_t il;
struct ivar32_t i;
const char *r;
uint32_t offset, xoffset, left, j;
SectionRef S, xS;
const char *name, *ivar_offset_p;
uint32_t ivar_offset;
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&il, '\0', sizeof(struct ivar_list32_t));
if (left < sizeof(struct ivar_list32_t)) {
memcpy(&il, r, left);
outs() << " (ivar_list_t entends past the end of the section)\n";
} else
memcpy(&il, r, sizeof(struct ivar_list32_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(il);
outs() << " entsize " << il.entsize << "\n";
outs() << " count " << il.count << "\n";
p += sizeof(struct ivar_list32_t);
offset += sizeof(struct ivar_list32_t);
for (j = 0; j < il.count; j++) {
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&i, '\0', sizeof(struct ivar32_t));
if (left < sizeof(struct ivar32_t)) {
memcpy(&i, r, left);
outs() << " (ivar_t entends past the end of the section)\n";
} else
memcpy(&i, r, sizeof(struct ivar32_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(i);
outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(ivar_offset);
outs() << " " << ivar_offset << "\n";
} else
outs() << "\n";
outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
name = get_pointer_32(i.name, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
name = get_pointer_32(i.type, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << "\t\t\talignment " << i.alignment << "\n";
outs() << "\t\t\t size " << i.size << "\n";
p += sizeof(struct ivar32_t);
offset += sizeof(struct ivar32_t);
}
}
static void print_objc_property_list64(uint64_t p,
struct DisassembleInfo *info) {
struct objc_property_list64 opl;
struct objc_property64 op;
const char *r;
uint32_t offset, xoffset, left, j;
SectionRef S, xS;
const char *name, *sym_name;
uint64_t n_value;
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&opl, '\0', sizeof(struct objc_property_list64));
if (left < sizeof(struct objc_property_list64)) {
memcpy(&opl, r, left);
outs() << " (objc_property_list entends past the end of the section)\n";
} else
memcpy(&opl, r, sizeof(struct objc_property_list64));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(opl);
outs() << " entsize " << opl.entsize << "\n";
outs() << " count " << opl.count << "\n";
p += sizeof(struct objc_property_list64);
offset += sizeof(struct objc_property_list64);
for (j = 0; j < opl.count; j++) {
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&op, '\0', sizeof(struct objc_property64));
if (left < sizeof(struct objc_property64)) {
memcpy(&op, r, left);
outs() << " (objc_property entends past the end of the section)\n";
} else
memcpy(&op, r, sizeof(struct objc_property64));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(op);
outs() << "\t\t\t name ";
sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
info, n_value, op.name);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (op.name != 0)
outs() << " + " << format("0x%" PRIx64, op.name);
} else
outs() << format("0x%" PRIx64, op.name);
name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << "\t\t\tattributes ";
sym_name =
get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
info, n_value, op.attributes);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (op.attributes != 0)
outs() << " + " << format("0x%" PRIx64, op.attributes);
} else
outs() << format("0x%" PRIx64, op.attributes);
name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
p += sizeof(struct objc_property64);
offset += sizeof(struct objc_property64);
}
}
static void print_objc_property_list32(uint32_t p,
struct DisassembleInfo *info) {
struct objc_property_list32 opl;
struct objc_property32 op;
const char *r;
uint32_t offset, xoffset, left, j;
SectionRef S, xS;
const char *name;
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&opl, '\0', sizeof(struct objc_property_list32));
if (left < sizeof(struct objc_property_list32)) {
memcpy(&opl, r, left);
outs() << " (objc_property_list entends past the end of the section)\n";
} else
memcpy(&opl, r, sizeof(struct objc_property_list32));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(opl);
outs() << " entsize " << opl.entsize << "\n";
outs() << " count " << opl.count << "\n";
p += sizeof(struct objc_property_list32);
offset += sizeof(struct objc_property_list32);
for (j = 0; j < opl.count; j++) {
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&op, '\0', sizeof(struct objc_property32));
if (left < sizeof(struct objc_property32)) {
memcpy(&op, r, left);
outs() << " (objc_property entends past the end of the section)\n";
} else
memcpy(&op, r, sizeof(struct objc_property32));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(op);
outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
name = get_pointer_32(op.name, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
name = get_pointer_32(op.attributes, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
p += sizeof(struct objc_property32);
offset += sizeof(struct objc_property32);
}
}
static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
bool &is_meta_class) {
struct class_ro64_t cro;
const char *r;
uint32_t offset, xoffset, left;
SectionRef S, xS;
const char *name, *sym_name;
uint64_t n_value;
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr || left < sizeof(struct class_ro64_t))
return false;
memset(&cro, '\0', sizeof(struct class_ro64_t));
if (left < sizeof(struct class_ro64_t)) {
memcpy(&cro, r, left);
outs() << " (class_ro_t entends past the end of the section)\n";
} else
memcpy(&cro, r, sizeof(struct class_ro64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(cro);
outs() << " flags " << format("0x%" PRIx32, cro.flags);
if (cro.flags & RO_META)
outs() << " RO_META";
if (cro.flags & RO_ROOT)
outs() << " RO_ROOT";
if (cro.flags & RO_HAS_CXX_STRUCTORS)
outs() << " RO_HAS_CXX_STRUCTORS";
outs() << "\n";
outs() << " instanceStart " << cro.instanceStart << "\n";
outs() << " instanceSize " << cro.instanceSize << "\n";
outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
<< "\n";
outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
<< "\n";
print_layout_map64(cro.ivarLayout, info);
outs() << " name ";
sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
info, n_value, cro.name);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (cro.name != 0)
outs() << " + " << format("0x%" PRIx64, cro.name);
} else
outs() << format("0x%" PRIx64, cro.name);
name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << " baseMethods ";
sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
S, info, n_value, cro.baseMethods);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (cro.baseMethods != 0)
outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
} else
outs() << format("0x%" PRIx64, cro.baseMethods);
outs() << " (struct method_list_t *)\n";
if (cro.baseMethods + n_value != 0)
print_method_list64_t(cro.baseMethods + n_value, info, "");
outs() << " baseProtocols ";
sym_name =
get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
info, n_value, cro.baseProtocols);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (cro.baseProtocols != 0)
outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
} else
outs() << format("0x%" PRIx64, cro.baseProtocols);
outs() << "\n";
if (cro.baseProtocols + n_value != 0)
print_protocol_list64_t(cro.baseProtocols + n_value, info);
outs() << " ivars ";
sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
info, n_value, cro.ivars);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (cro.ivars != 0)
outs() << " + " << format("0x%" PRIx64, cro.ivars);
} else
outs() << format("0x%" PRIx64, cro.ivars);
outs() << "\n";
if (cro.ivars + n_value != 0)
print_ivar_list64_t(cro.ivars + n_value, info);
outs() << " weakIvarLayout ";
sym_name =
get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
info, n_value, cro.weakIvarLayout);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (cro.weakIvarLayout != 0)
outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
} else
outs() << format("0x%" PRIx64, cro.weakIvarLayout);
outs() << "\n";
print_layout_map64(cro.weakIvarLayout + n_value, info);
outs() << " baseProperties ";
sym_name =
get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
info, n_value, cro.baseProperties);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (cro.baseProperties != 0)
outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
} else
outs() << format("0x%" PRIx64, cro.baseProperties);
outs() << "\n";
if (cro.baseProperties + n_value != 0)
print_objc_property_list64(cro.baseProperties + n_value, info);
is_meta_class = (cro.flags & RO_META) != 0;
return true;
}
static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
bool &is_meta_class) {
struct class_ro32_t cro;
const char *r;
uint32_t offset, xoffset, left;
SectionRef S, xS;
const char *name;
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return false;
memset(&cro, '\0', sizeof(struct class_ro32_t));
if (left < sizeof(struct class_ro32_t)) {
memcpy(&cro, r, left);
outs() << " (class_ro_t entends past the end of the section)\n";
} else
memcpy(&cro, r, sizeof(struct class_ro32_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(cro);
outs() << " flags " << format("0x%" PRIx32, cro.flags);
if (cro.flags & RO_META)
outs() << " RO_META";
if (cro.flags & RO_ROOT)
outs() << " RO_ROOT";
if (cro.flags & RO_HAS_CXX_STRUCTORS)
outs() << " RO_HAS_CXX_STRUCTORS";
outs() << "\n";
outs() << " instanceStart " << cro.instanceStart << "\n";
outs() << " instanceSize " << cro.instanceSize << "\n";
outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
<< "\n";
print_layout_map32(cro.ivarLayout, info);
outs() << " name " << format("0x%" PRIx32, cro.name);
name = get_pointer_32(cro.name, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << " baseMethods "
<< format("0x%" PRIx32, cro.baseMethods)
<< " (struct method_list_t *)\n";
if (cro.baseMethods != 0)
print_method_list32_t(cro.baseMethods, info, "");
outs() << " baseProtocols "
<< format("0x%" PRIx32, cro.baseProtocols) << "\n";
if (cro.baseProtocols != 0)
print_protocol_list32_t(cro.baseProtocols, info);
outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
<< "\n";
if (cro.ivars != 0)
print_ivar_list32_t(cro.ivars, info);
outs() << " weakIvarLayout "
<< format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
print_layout_map32(cro.weakIvarLayout, info);
outs() << " baseProperties "
<< format("0x%" PRIx32, cro.baseProperties) << "\n";
if (cro.baseProperties != 0)
print_objc_property_list32(cro.baseProperties, info);
is_meta_class = (cro.flags & RO_META) != 0;
return true;
}
static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
struct class64_t c;
const char *r;
uint32_t offset, left;
SectionRef S;
const char *name;
uint64_t isa_n_value, n_value;
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr || left < sizeof(struct class64_t))
return;
memset(&c, '\0', sizeof(struct class64_t));
if (left < sizeof(struct class64_t)) {
memcpy(&c, r, left);
outs() << " (class_t entends past the end of the section)\n";
} else
memcpy(&c, r, sizeof(struct class64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(c);
outs() << " isa " << format("0x%" PRIx64, c.isa);
name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
isa_n_value, c.isa);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
outs() << " superclass " << format("0x%" PRIx64, c.superclass);
name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
n_value, c.superclass);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
outs() << " cache " << format("0x%" PRIx64, c.cache);
name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
n_value, c.cache);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
outs() << " vtable " << format("0x%" PRIx64, c.vtable);
name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
n_value, c.vtable);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
n_value, c.data);
outs() << " data ";
if (n_value != 0) {
if (info->verbose && name != nullptr)
outs() << name;
else
outs() << format("0x%" PRIx64, n_value);
if (c.data != 0)
outs() << " + " << format("0x%" PRIx64, c.data);
} else
outs() << format("0x%" PRIx64, c.data);
outs() << " (struct class_ro_t *)";
// This is a Swift class if some of the low bits of the pointer are set.
if ((c.data + n_value) & 0x7)
outs() << " Swift class";
outs() << "\n";
bool is_meta_class;
if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
return;
if (!is_meta_class &&
c.isa + isa_n_value != p &&
c.isa + isa_n_value != 0 &&
info->depth < 100) {
info->depth++;
outs() << "Meta Class\n";
print_class64_t(c.isa + isa_n_value, info);
}
}
static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
struct class32_t c;
const char *r;
uint32_t offset, left;
SectionRef S;
const char *name;
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&c, '\0', sizeof(struct class32_t));
if (left < sizeof(struct class32_t)) {
memcpy(&c, r, left);
outs() << " (class_t entends past the end of the section)\n";
} else
memcpy(&c, r, sizeof(struct class32_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(c);
outs() << " isa " << format("0x%" PRIx32, c.isa);
name =
get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
outs() << " superclass " << format("0x%" PRIx32, c.superclass);
name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
c.superclass);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
outs() << " cache " << format("0x%" PRIx32, c.cache);
name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
c.cache);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
outs() << " vtable " << format("0x%" PRIx32, c.vtable);
name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
c.vtable);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
name =
get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
outs() << " data " << format("0x%" PRIx32, c.data)
<< " (struct class_ro_t *)";
// This is a Swift class if some of the low bits of the pointer are set.
if (c.data & 0x3)
outs() << " Swift class";
outs() << "\n";
bool is_meta_class;
if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
return;
if (!is_meta_class) {
outs() << "Meta Class\n";
print_class32_t(c.isa, info);
}
}
static void print_objc_class_t(struct objc_class_t *objc_class,
struct DisassembleInfo *info) {
uint32_t offset, left, xleft;
const char *name, *p, *ivar_list;
SectionRef S;
int32_t i;
struct objc_ivar_list_t objc_ivar_list;
struct objc_ivar_t ivar;
outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
if (name != nullptr)
outs() << format(" %.*s", left, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
outs() << "\t super_class "
<< format("0x%08" PRIx32, objc_class->super_class);
if (info->verbose) {
name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
if (name != nullptr)
outs() << format(" %.*s", left, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
if (info->verbose) {
name = get_pointer_32(objc_class->name, offset, left, S, info, true);
if (name != nullptr)
outs() << format(" %.*s", left, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
<< "\n";
outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
if (info->verbose) {
if (CLS_GETINFO(objc_class, CLS_CLASS))
outs() << " CLS_CLASS";
else if (CLS_GETINFO(objc_class, CLS_META))
outs() << " CLS_META";
}
outs() << "\n";
outs() << "\t instance_size "
<< format("0x%08" PRIx32, objc_class->instance_size) << "\n";
p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
if (p != nullptr) {
if (left > sizeof(struct objc_ivar_list_t)) {
outs() << "\n";
memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
} else {
outs() << " (entends past the end of the section)\n";
memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
memcpy(&objc_ivar_list, p, left);
}
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(objc_ivar_list);
outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
ivar_list = p + sizeof(struct objc_ivar_list_t);
for (i = 0; i < objc_ivar_list.ivar_count; i++) {
if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
outs() << "\t\t remaining ivar's extend past the of the section\n";
break;
}
memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
sizeof(struct objc_ivar_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(ivar);
outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
if (info->verbose) {
name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
if (name != nullptr)
outs() << format(" %.*s", xleft, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
if (info->verbose) {
name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
if (name != nullptr)
outs() << format(" %.*s", xleft, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
outs() << "\t\t ivar_offset "
<< format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
}
} else {
outs() << " (not in an __OBJC section)\n";
}
outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
if (print_method_list(objc_class->methodLists, info))
outs() << " (not in an __OBJC section)\n";
outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
<< "\n";
outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
if (print_protocol_list(objc_class->protocols, 16, info))
outs() << " (not in an __OBJC section)\n";
}
static void print_objc_objc_category_t(struct objc_category_t *objc_category,
struct DisassembleInfo *info) {
uint32_t offset, left;
const char *name;
SectionRef S;
outs() << "\t category name "
<< format("0x%08" PRIx32, objc_category->category_name);
if (info->verbose) {
name = get_pointer_32(objc_category->category_name, offset, left, S, info,
true);
if (name != nullptr)
outs() << format(" %.*s", left, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
outs() << "\t\t class name "
<< format("0x%08" PRIx32, objc_category->class_name);
if (info->verbose) {
name =
get_pointer_32(objc_category->class_name, offset, left, S, info, true);
if (name != nullptr)
outs() << format(" %.*s", left, name);
else
outs() << " (not in an __OBJC section)";
}
outs() << "\n";
outs() << "\t instance methods "
<< format("0x%08" PRIx32, objc_category->instance_methods);
if (print_method_list(objc_category->instance_methods, info))
outs() << " (not in an __OBJC section)\n";
outs() << "\t class methods "
<< format("0x%08" PRIx32, objc_category->class_methods);
if (print_method_list(objc_category->class_methods, info))
outs() << " (not in an __OBJC section)\n";
}
static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
struct category64_t c;
const char *r;
uint32_t offset, xoffset, left;
SectionRef S, xS;
const char *name, *sym_name;
uint64_t n_value;
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&c, '\0', sizeof(struct category64_t));
if (left < sizeof(struct category64_t)) {
memcpy(&c, r, left);
outs() << " (category_t entends past the end of the section)\n";
} else
memcpy(&c, r, sizeof(struct category64_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(c);
outs() << " name ";
sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
info, n_value, c.name);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (c.name != 0)
outs() << " + " << format("0x%" PRIx64, c.name);
} else
outs() << format("0x%" PRIx64, c.name);
name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
outs() << " cls ";
sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
n_value, c.cls);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (c.cls != 0)
outs() << " + " << format("0x%" PRIx64, c.cls);
} else
outs() << format("0x%" PRIx64, c.cls);
outs() << "\n";
if (c.cls + n_value != 0)
print_class64_t(c.cls + n_value, info);
outs() << " instanceMethods ";
sym_name =
get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
info, n_value, c.instanceMethods);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (c.instanceMethods != 0)
outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
} else
outs() << format("0x%" PRIx64, c.instanceMethods);
outs() << "\n";
if (c.instanceMethods + n_value != 0)
print_method_list64_t(c.instanceMethods + n_value, info, "");
outs() << " classMethods ";
sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
S, info, n_value, c.classMethods);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (c.classMethods != 0)
outs() << " + " << format("0x%" PRIx64, c.classMethods);
} else
outs() << format("0x%" PRIx64, c.classMethods);
outs() << "\n";
if (c.classMethods + n_value != 0)
print_method_list64_t(c.classMethods + n_value, info, "");
outs() << " protocols ";
sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
info, n_value, c.protocols);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (c.protocols != 0)
outs() << " + " << format("0x%" PRIx64, c.protocols);
} else
outs() << format("0x%" PRIx64, c.protocols);
outs() << "\n";
if (c.protocols + n_value != 0)
print_protocol_list64_t(c.protocols + n_value, info);
outs() << "instanceProperties ";
sym_name =
get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
S, info, n_value, c.instanceProperties);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (c.instanceProperties != 0)
outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
} else
outs() << format("0x%" PRIx64, c.instanceProperties);
outs() << "\n";
if (c.instanceProperties + n_value != 0)
print_objc_property_list64(c.instanceProperties + n_value, info);
}
static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
struct category32_t c;
const char *r;
uint32_t offset, left;
SectionRef S, xS;
const char *name;
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&c, '\0', sizeof(struct category32_t));
if (left < sizeof(struct category32_t)) {
memcpy(&c, r, left);
outs() << " (category_t entends past the end of the section)\n";
} else
memcpy(&c, r, sizeof(struct category32_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(c);
outs() << " name " << format("0x%" PRIx32, c.name);
name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
c.name);
if (name)
outs() << " " << name;
outs() << "\n";
outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
if (c.cls != 0)
print_class32_t(c.cls, info);
outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
<< "\n";
if (c.instanceMethods != 0)
print_method_list32_t(c.instanceMethods, info, "");
outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
<< "\n";
if (c.classMethods != 0)
print_method_list32_t(c.classMethods, info, "");
outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
if (c.protocols != 0)
print_protocol_list32_t(c.protocols, info);
outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
<< "\n";
if (c.instanceProperties != 0)
print_objc_property_list32(c.instanceProperties, info);
}
static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
uint32_t i, left, offset, xoffset;
uint64_t p, n_value;
struct message_ref64 mr;
const char *name, *sym_name;
const char *r;
SectionRef xS;
if (S == SectionRef())
return;
StringRef SectName;
S.getName(SectName);
DataRefImpl Ref = S.getRawDataRefImpl();
StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
offset = 0;
for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
p = S.getAddress() + i;
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&mr, '\0', sizeof(struct message_ref64));
if (left < sizeof(struct message_ref64)) {
memcpy(&mr, r, left);
outs() << " (message_ref entends past the end of the section)\n";
} else
memcpy(&mr, r, sizeof(struct message_ref64));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(mr);
outs() << " imp ";
name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
n_value, mr.imp);
if (n_value != 0) {
outs() << format("0x%" PRIx64, n_value) << " ";
if (mr.imp != 0)
outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
} else
outs() << format("0x%" PRIx64, mr.imp) << " ";
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
outs() << " sel ";
sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
info, n_value, mr.sel);
if (n_value != 0) {
if (info->verbose && sym_name != nullptr)
outs() << sym_name;
else
outs() << format("0x%" PRIx64, n_value);
if (mr.sel != 0)
outs() << " + " << format("0x%" PRIx64, mr.sel);
} else
outs() << format("0x%" PRIx64, mr.sel);
name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
if (name != nullptr)
outs() << format(" %.*s", left, name);
outs() << "\n";
offset += sizeof(struct message_ref64);
}
}
static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
uint32_t i, left, offset, xoffset, p;
struct message_ref32 mr;
const char *name, *r;
SectionRef xS;
if (S == SectionRef())
return;
StringRef SectName;
S.getName(SectName);
DataRefImpl Ref = S.getRawDataRefImpl();
StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
offset = 0;
for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
p = S.getAddress() + i;
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&mr, '\0', sizeof(struct message_ref32));
if (left < sizeof(struct message_ref32)) {
memcpy(&mr, r, left);
outs() << " (message_ref entends past the end of the section)\n";
} else
memcpy(&mr, r, sizeof(struct message_ref32));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(mr);
outs() << " imp " << format("0x%" PRIx32, mr.imp);
name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
mr.imp);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
outs() << " sel " << format("0x%" PRIx32, mr.sel);
name = get_pointer_32(mr.sel, xoffset, left, xS, info);
if (name != nullptr)
outs() << " " << name;
outs() << "\n";
offset += sizeof(struct message_ref32);
}
}
static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
uint32_t left, offset, swift_version;
uint64_t p;
struct objc_image_info64 o;
const char *r;
if (S == SectionRef())
return;
StringRef SectName;
S.getName(SectName);
DataRefImpl Ref = S.getRawDataRefImpl();
StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
p = S.getAddress();
r = get_pointer_64(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&o, '\0', sizeof(struct objc_image_info64));
if (left < sizeof(struct objc_image_info64)) {
memcpy(&o, r, left);
outs() << " (objc_image_info entends past the end of the section)\n";
} else
memcpy(&o, r, sizeof(struct objc_image_info64));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(o);
outs() << " version " << o.version << "\n";
outs() << " flags " << format("0x%" PRIx32, o.flags);
if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
outs() << " OBJC_IMAGE_IS_REPLACEMENT";
if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
outs() << " OBJC_IMAGE_SUPPORTS_GC";
swift_version = (o.flags >> 8) & 0xff;
if (swift_version != 0) {
if (swift_version == 1)
outs() << " Swift 1.0";
else if (swift_version == 2)
outs() << " Swift 1.1";
else
outs() << " unknown future Swift version (" << swift_version << ")";
}
outs() << "\n";
}
static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
uint32_t left, offset, swift_version, p;
struct objc_image_info32 o;
const char *r;
StringRef SectName;
S.getName(SectName);
DataRefImpl Ref = S.getRawDataRefImpl();
StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
p = S.getAddress();
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&o, '\0', sizeof(struct objc_image_info32));
if (left < sizeof(struct objc_image_info32)) {
memcpy(&o, r, left);
outs() << " (objc_image_info entends past the end of the section)\n";
} else
memcpy(&o, r, sizeof(struct objc_image_info32));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(o);
outs() << " version " << o.version << "\n";
outs() << " flags " << format("0x%" PRIx32, o.flags);
if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
outs() << " OBJC_IMAGE_IS_REPLACEMENT";
if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
outs() << " OBJC_IMAGE_SUPPORTS_GC";
swift_version = (o.flags >> 8) & 0xff;
if (swift_version != 0) {
if (swift_version == 1)
outs() << " Swift 1.0";
else if (swift_version == 2)
outs() << " Swift 1.1";
else
outs() << " unknown future Swift version (" << swift_version << ")";
}
outs() << "\n";
}
static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
uint32_t left, offset, p;
struct imageInfo_t o;
const char *r;
StringRef SectName;
S.getName(SectName);
DataRefImpl Ref = S.getRawDataRefImpl();
StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
p = S.getAddress();
r = get_pointer_32(p, offset, left, S, info);
if (r == nullptr)
return;
memset(&o, '\0', sizeof(struct imageInfo_t));
if (left < sizeof(struct imageInfo_t)) {
memcpy(&o, r, left);
outs() << " (imageInfo entends past the end of the section)\n";
} else
memcpy(&o, r, sizeof(struct imageInfo_t));
if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(o);
outs() << " version " << o.version << "\n";
outs() << " flags " << format("0x%" PRIx32, o.flags);
if (o.flags & 0x1)
outs() << " F&C";
if (o.flags & 0x2)
outs() << " GC";
if (o.flags & 0x4)
outs() << " GC-only";
else
outs() << " RR";
outs() << "\n";
}
static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
SymbolAddressMap AddrMap;
if (verbose)
CreateSymbolAddressMap(O, &AddrMap);
std::vector<SectionRef> Sections;
for (const SectionRef &Section : O->sections()) {
StringRef SectName;
Section.getName(SectName);
Sections.push_back(Section);
}
struct DisassembleInfo info;
// Set up the block of info used by the Symbolizer call backs.
info.verbose = verbose;
info.O = O;
info.AddrMap = &AddrMap;
info.Sections = &Sections;
info.class_name = nullptr;
info.selector_name = nullptr;
info.method = nullptr;
info.demangled_name = nullptr;
info.bindtable = nullptr;
info.adrp_addr = 0;
info.adrp_inst = 0;
info.depth = 0;
SectionRef CL = get_section(O, "__OBJC2", "__class_list");
if (CL == SectionRef())
CL = get_section(O, "__DATA", "__objc_classlist");
info.S = CL;
walk_pointer_list_64("class", CL, O, &info, print_class64_t);
SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
if (CR == SectionRef())
CR = get_section(O, "__DATA", "__objc_classrefs");
info.S = CR;
walk_pointer_list_64("class refs", CR, O, &info, nullptr);
SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
if (SR == SectionRef())
SR = get_section(O, "__DATA", "__objc_superrefs");
info.S = SR;
walk_pointer_list_64("super refs", SR, O, &info, nullptr);
SectionRef CA = get_section(O, "__OBJC2", "__category_list");
if (CA == SectionRef())
CA = get_section(O, "__DATA", "__objc_catlist");
info.S = CA;
walk_pointer_list_64("category", CA, O, &info, print_category64_t);
SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
if (PL == SectionRef())
PL = get_section(O, "__DATA", "__objc_protolist");
info.S = PL;
walk_pointer_list_64("protocol", PL, O, &info, nullptr);
SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
if (MR == SectionRef())
MR = get_section(O, "__DATA", "__objc_msgrefs");
info.S = MR;
print_message_refs64(MR, &info);
SectionRef II = get_section(O, "__OBJC2", "__image_info");
if (II == SectionRef())
II = get_section(O, "__DATA", "__objc_imageinfo");
info.S = II;
print_image_info64(II, &info);
if (info.bindtable != nullptr)
delete info.bindtable;
}
static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
SymbolAddressMap AddrMap;
if (verbose)
CreateSymbolAddressMap(O, &AddrMap);
std::vector<SectionRef> Sections;
for (const SectionRef &Section : O->sections()) {
StringRef SectName;
Section.getName(SectName);
Sections.push_back(Section);
}
struct DisassembleInfo info;
// Set up the block of info used by the Symbolizer call backs.
info.verbose = verbose;
info.O = O;
info.AddrMap = &AddrMap;
info.Sections = &Sections;
info.class_name = nullptr;
info.selector_name = nullptr;
info.method = nullptr;
info.demangled_name = nullptr;
info.bindtable = nullptr;
info.adrp_addr = 0;
info.adrp_inst = 0;
const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
if (CL != SectionRef()) {
info.S = CL;
walk_pointer_list_32("class", CL, O, &info, print_class32_t);
} else {
const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
info.S = CL;
walk_pointer_list_32("class", CL, O, &info, print_class32_t);
}
const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
if (CR != SectionRef()) {
info.S = CR;
walk_pointer_list_32("class refs", CR, O, &info, nullptr);
} else {
const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
info.S = CR;
walk_pointer_list_32("class refs", CR, O, &info, nullptr);
}
const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
if (SR != SectionRef()) {
info.S = SR;
walk_pointer_list_32("super refs", SR, O, &info, nullptr);
} else {
const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
info.S = SR;
walk_pointer_list_32("super refs", SR, O, &info, nullptr);
}
const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
if (CA != SectionRef()) {
info.S = CA;
walk_pointer_list_32("category", CA, O, &info, print_category32_t);
} else {
const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
info.S = CA;
walk_pointer_list_32("category", CA, O, &info, print_category32_t);
}
const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
if (PL != SectionRef()) {
info.S = PL;
walk_pointer_list_32("protocol", PL, O, &info, nullptr);
} else {
const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
info.S = PL;
walk_pointer_list_32("protocol", PL, O, &info, nullptr);
}
const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
if (MR != SectionRef()) {
info.S = MR;
print_message_refs32(MR, &info);
} else {
const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
info.S = MR;
print_message_refs32(MR, &info);
}
const SectionRef II = get_section(O, "__OBJC2", "__image_info");
if (II != SectionRef()) {
info.S = II;
print_image_info32(II, &info);
} else {
const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
info.S = II;
print_image_info32(II, &info);
}
}
static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
uint32_t i, j, p, offset, xoffset, left, defs_left, def;
const char *r, *name, *defs;
struct objc_module_t module;
SectionRef S, xS;
struct objc_symtab_t symtab;
struct objc_class_t objc_class;
struct objc_category_t objc_category;
outs() << "Objective-C segment\n";
S = get_section(O, "__OBJC", "__module_info");
if (S == SectionRef())
return false;
SymbolAddressMap AddrMap;
if (verbose)
CreateSymbolAddressMap(O, &AddrMap);
std::vector<SectionRef> Sections;
for (const SectionRef &Section : O->sections()) {
StringRef SectName;
Section.getName(SectName);
Sections.push_back(Section);
}
struct DisassembleInfo info;
// Set up the block of info used by the Symbolizer call backs.
info.verbose = verbose;
info.O = O;
info.AddrMap = &AddrMap;
info.Sections = &Sections;
info.class_name = nullptr;
info.selector_name = nullptr;
info.method = nullptr;
info.demangled_name = nullptr;
info.bindtable = nullptr;
info.adrp_addr = 0;
info.adrp_inst = 0;
for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
p = S.getAddress() + i;
r = get_pointer_32(p, offset, left, S, &info, true);
if (r == nullptr)
return true;
memset(&module, '\0', sizeof(struct objc_module_t));
if (left < sizeof(struct objc_module_t)) {
memcpy(&module, r, left);
outs() << " (module extends past end of __module_info section)\n";
} else
memcpy(&module, r, sizeof(struct objc_module_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(module);
outs() << "Module " << format("0x%" PRIx32, p) << "\n";
outs() << " version " << module.version << "\n";
outs() << " size " << module.size << "\n";
outs() << " name ";
name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
if (name != nullptr)
outs() << format("%.*s", left, name);
else
outs() << format("0x%08" PRIx32, module.name)
<< "(not in an __OBJC section)";
outs() << "\n";
r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
if (module.symtab == 0 || r == nullptr) {
outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
<< " (not in an __OBJC section)\n";
continue;
}
outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
memset(&symtab, '\0', sizeof(struct objc_symtab_t));
defs_left = 0;
defs = nullptr;
if (left < sizeof(struct objc_symtab_t)) {
memcpy(&symtab, r, left);
outs() << "\tsymtab extends past end of an __OBJC section)\n";
} else {
memcpy(&symtab, r, sizeof(struct objc_symtab_t));
if (left > sizeof(struct objc_symtab_t)) {
defs_left = left - sizeof(struct objc_symtab_t);
defs = r + sizeof(struct objc_symtab_t);
}
}
if (O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(symtab);
outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
if (r == nullptr)
outs() << " (not in an __OBJC section)";
outs() << "\n";
outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
if (symtab.cls_def_cnt > 0)
outs() << "\tClass Definitions\n";
for (j = 0; j < symtab.cls_def_cnt; j++) {
if ((j + 1) * sizeof(uint32_t) > defs_left) {
outs() << "\t(remaining class defs entries entends past the end of the "
<< "section)\n";
break;
}
memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(def);
r = get_pointer_32(def, xoffset, left, xS, &info, true);
outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
if (r != nullptr) {
if (left > sizeof(struct objc_class_t)) {
outs() << "\n";
memcpy(&objc_class, r, sizeof(struct objc_class_t));
} else {
outs() << " (entends past the end of the section)\n";
memset(&objc_class, '\0', sizeof(struct objc_class_t));
memcpy(&objc_class, r, left);
}
if (O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(objc_class);
print_objc_class_t(&objc_class, &info);
} else {
outs() << "(not in an __OBJC section)\n";
}
if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
outs() << "\tMeta Class";
r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
if (r != nullptr) {
if (left > sizeof(struct objc_class_t)) {
outs() << "\n";
memcpy(&objc_class, r, sizeof(struct objc_class_t));
} else {
outs() << " (entends past the end of the section)\n";
memset(&objc_class, '\0', sizeof(struct objc_class_t));
memcpy(&objc_class, r, left);
}
if (O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(objc_class);
print_objc_class_t(&objc_class, &info);
} else {
outs() << "(not in an __OBJC section)\n";
}
}
}
if (symtab.cat_def_cnt > 0)
outs() << "\tCategory Definitions\n";
for (j = 0; j < symtab.cat_def_cnt; j++) {
if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
outs() << "\t(remaining category defs entries entends past the end of "
<< "the section)\n";
break;
}
memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(def);
r = get_pointer_32(def, xoffset, left, xS, &info, true);
outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
<< format("0x%08" PRIx32, def);
if (r != nullptr) {
if (left > sizeof(struct objc_category_t)) {
outs() << "\n";
memcpy(&objc_category, r, sizeof(struct objc_category_t));
} else {
outs() << " (entends past the end of the section)\n";
memset(&objc_category, '\0', sizeof(struct objc_category_t));
memcpy(&objc_category, r, left);
}
if (O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(objc_category);
print_objc_objc_category_t(&objc_category, &info);
} else {
outs() << "(not in an __OBJC section)\n";
}
}
}
const SectionRef II = get_section(O, "__OBJC", "__image_info");
if (II != SectionRef())
print_image_info(II, &info);
return true;
}
static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
uint32_t size, uint32_t addr) {
SymbolAddressMap AddrMap;
CreateSymbolAddressMap(O, &AddrMap);
std::vector<SectionRef> Sections;
for (const SectionRef &Section : O->sections()) {
StringRef SectName;
Section.getName(SectName);
Sections.push_back(Section);
}
struct DisassembleInfo info;
// Set up the block of info used by the Symbolizer call backs.
info.verbose = true;
info.O = O;
info.AddrMap = &AddrMap;
info.Sections = &Sections;
info.class_name = nullptr;
info.selector_name = nullptr;
info.method = nullptr;
info.demangled_name = nullptr;
info.bindtable = nullptr;
info.adrp_addr = 0;
info.adrp_inst = 0;
const char *p;
struct objc_protocol_t protocol;
uint32_t left, paddr;
for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
memset(&protocol, '\0', sizeof(struct objc_protocol_t));
left = size - (p - sect);
if (left < sizeof(struct objc_protocol_t)) {
outs() << "Protocol extends past end of __protocol section\n";
memcpy(&protocol, p, left);
} else
memcpy(&protocol, p, sizeof(struct objc_protocol_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
swapStruct(protocol);
paddr = addr + (p - sect);
outs() << "Protocol " << format("0x%" PRIx32, paddr);
if (print_protocol(paddr, 0, &info))
outs() << "(not in an __OBJC section)\n";
}
}
static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
if (O->is64Bit())
printObjc2_64bit_MetaData(O, verbose);
else {
MachO::mach_header H;
H = O->getHeader();
if (H.cputype == MachO::CPU_TYPE_ARM)
printObjc2_32bit_MetaData(O, verbose);
else {
// This is the 32-bit non-arm cputype case. Which is normally
// the first Objective-C ABI. But it may be the case of a
// binary for the iOS simulator which is the second Objective-C
// ABI. In that case printObjc1_32bit_MetaData() will determine that
// and return false.
if (!printObjc1_32bit_MetaData(O, verbose))
printObjc2_32bit_MetaData(O, verbose);
}
}
}
// GuessLiteralPointer returns a string which for the item in the Mach-O file
// for the address passed in as ReferenceValue for printing as a comment with
// the instruction and also returns the corresponding type of that item
// indirectly through ReferenceType.
//
// If ReferenceValue is an address of literal cstring then a pointer to the
// cstring is returned and ReferenceType is set to
// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
//
// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
// Class ref that name is returned and the ReferenceType is set accordingly.
//
// Lastly, literals which are Symbol address in a literal pool are looked for
// and if found the symbol name is returned and ReferenceType is set to
// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
//
// If there is no item in the Mach-O file for the address passed in as
// ReferenceValue nullptr is returned and ReferenceType is unchanged.
static const char *GuessLiteralPointer(uint64_t ReferenceValue,
uint64_t ReferencePC,
uint64_t *ReferenceType,
struct DisassembleInfo *info) {
// First see if there is an external relocation entry at the ReferencePC.
if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
uint64_t sect_addr = info->S.getAddress();
uint64_t sect_offset = ReferencePC - sect_addr;
bool reloc_found = false;
DataRefImpl Rel;
MachO::any_relocation_info RE;
bool isExtern = false;
SymbolRef Symbol;
for (const RelocationRef &Reloc : info->S.relocations()) {
uint64_t RelocOffset = Reloc.getOffset();
if (RelocOffset == sect_offset) {
Rel = Reloc.getRawDataRefImpl();
RE = info->O->getRelocation(Rel);
if (info->O->isRelocationScattered(RE))
continue;
isExtern = info->O->getPlainRelocationExternal(RE);
if (isExtern) {
symbol_iterator RelocSym = Reloc.getSymbol();
Symbol = *RelocSym;
}
reloc_found = true;
break;
}
}
// If there is an external relocation entry for a symbol in a section
// then used that symbol's value for the value of the reference.
if (reloc_found && isExtern) {
if (info->O->getAnyRelocationPCRel(RE)) {
unsigned Type = info->O->getAnyRelocationType(RE);
if (Type == MachO::X86_64_RELOC_SIGNED) {
ReferenceValue = Symbol.getValue();
}
}
}
}
// Look for literals such as Objective-C CFStrings refs, Selector refs,
// Message refs and Class refs.
bool classref, selref, msgref, cfstring;
uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
selref, msgref, cfstring);
if (classref && pointer_value == 0) {
// Note the ReferenceValue is a pointer into the __objc_classrefs section.
// And the pointer_value in that section is typically zero as it will be
// set by dyld as part of the "bind information".
const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
if (name != nullptr) {
*ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
const char *class_name = strrchr(name, '$');
if (class_name != nullptr && class_name[1] == '_' &&
class_name[2] != '\0') {
info->class_name = class_name + 2;
return name;
}
}
}
if (classref) {
*ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
const char *name =
get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
if (name != nullptr)
info->class_name = name;
else
name = "bad class ref";
return name;
}
if (cfstring) {
*ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
return name;
}
if (selref && pointer_value == 0)
pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
if (pointer_value != 0)
ReferenceValue = pointer_value;
const char *name = GuessCstringPointer(ReferenceValue, info);
if (name) {
if (pointer_value != 0 && selref) {
*ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
info->selector_name = name;
} else if (pointer_value != 0 && msgref) {
info->class_name = nullptr;
*ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
info->selector_name = name;
} else
*ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
return name;
}
// Lastly look for an indirect symbol with this ReferenceValue which is in
// a literal pool. If found return that symbol name.
name = GuessIndirectSymbol(ReferenceValue, info);
if (name) {
*ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
return name;
}
return nullptr;
}
// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
// the Symbolizer. It looks up the ReferenceValue using the info passed via the
// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
// is created and returns the symbol name that matches the ReferenceValue or
// nullptr if none. The ReferenceType is passed in for the IN type of
// reference the instruction is making from the values in defined in the header
// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
// Out type and the ReferenceName will also be set which is added as a comment
// to the disassembled instruction.
//
#if HAVE_CXXABI_H
// If the symbol name is a C++ mangled name then the demangled name is
// returned through ReferenceName and ReferenceType is set to
// LLVMDisassembler_ReferenceType_DeMangled_Name .
#endif
//
// When this is called to get a symbol name for a branch target then the
// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
// SymbolValue will be looked for in the indirect symbol table to determine if
// it is an address for a symbol stub. If so then the symbol name for that
// stub is returned indirectly through ReferenceName and then ReferenceType is
// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
//
// When this is called with an value loaded via a PC relative load then
// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
// SymbolValue is checked to be an address of literal pointer, symbol pointer,
// or an Objective-C meta data reference. If so the output ReferenceType is
// set to correspond to that as well as setting the ReferenceName.
static const char *SymbolizerSymbolLookUp(void *DisInfo,
uint64_t ReferenceValue,
uint64_t *ReferenceType,
uint64_t ReferencePC,
const char **ReferenceName) {
struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
// If no verbose symbolic information is wanted then just return nullptr.
if (!info->verbose) {
*ReferenceName = nullptr;
*ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
return nullptr;
}
const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
*ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
if (*ReferenceName != nullptr) {
method_reference(info, ReferenceType, ReferenceName);
if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
*ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
} else
#if HAVE_CXXABI_H
if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
if (info->demangled_name != nullptr)
free(info->demangled_name);
int status;
info->demangled_name =
abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
if (info->demangled_name != nullptr) {
*ReferenceName = info->demangled_name;
*ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
} else
*ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
} else
#endif
*ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
} else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
*ReferenceName =
GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
if (*ReferenceName)
method_reference(info, ReferenceType, ReferenceName);
else
*ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
// If this is arm64 and the reference is an adrp instruction save the
// instruction, passed in ReferenceValue and the address of the instruction
// for use later if we see and add immediate instruction.
} else if (info->O->getArch() == Triple::aarch64 &&
*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
info->adrp_inst = ReferenceValue;
info->adrp_addr = ReferencePC;
SymbolName = nullptr;
*ReferenceName = nullptr;
*ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
// If this is arm64 and reference is an add immediate instruction and we
// have
// seen an adrp instruction just before it and the adrp's Xd register
// matches
// this add's Xn register reconstruct the value being referenced and look to
// see if it is a literal pointer. Note the add immediate instruction is
// passed in ReferenceValue.
} else if (info->O->getArch() == Triple::aarch64 &&
*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
ReferencePC - 4 == info->adrp_addr &&
(info->adrp_inst & 0x9f000000) == 0x90000000 &&
(info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
uint32_t addxri_inst;
uint64_t adrp_imm, addxri_imm;
adrp_imm =
((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
if (info->adrp_inst & 0x0200000)
adrp_imm |= 0xfffffffffc000000LL;
addxri_inst = ReferenceValue;
addxri_imm = (addxri_inst >> 10) & 0xfff;
if (((addxri_inst >> 22) & 0x3) == 1)
addxri_imm <<= 12;
ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
(adrp_imm << 12) + addxri_imm;
*ReferenceName =
GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
if (*ReferenceName == nullptr)
*ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
// If this is arm64 and the reference is a load register instruction and we
// have seen an adrp instruction just before it and the adrp's Xd register
// matches this add's Xn register reconstruct the value being referenced and
// look to see if it is a literal pointer. Note the load register
// instruction is passed in ReferenceValue.
} else if (info->O->getArch() == Triple::aarch64 &&
*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
ReferencePC - 4 == info->adrp_addr &&
(info->adrp_inst & 0x9f000000) == 0x90000000 &&
(info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
uint32_t ldrxui_inst;
uint64_t adrp_imm, ldrxui_imm;
adrp_imm =
((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
if (info->adrp_inst & 0x0200000)
adrp_imm |= 0xfffffffffc000000LL;
ldrxui_inst = ReferenceValue;
ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
(adrp_imm << 12) + (ldrxui_imm << 3);
*ReferenceName =
GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
if (*ReferenceName == nullptr)
*ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
}
// If this arm64 and is an load register (PC-relative) instruction the
// ReferenceValue is the PC plus the immediate value.
else if (info->O->getArch() == Triple::aarch64 &&
(*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
*ReferenceName =
GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
if (*ReferenceName == nullptr)
*ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
}
#if HAVE_CXXABI_H
else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
if (info->demangled_name != nullptr)
free(info->demangled_name);
int status;
info->demangled_name =
abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
if (info->demangled_name != nullptr) {
*ReferenceName = info->demangled_name;
*ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
}
}
#endif
else {
*ReferenceName = nullptr;
*ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
}
return SymbolName;
}
/// \brief Emits the comments that are stored in the CommentStream.
/// Each comment in the CommentStream must end with a newline.
static void emitComments(raw_svector_ostream &CommentStream,
SmallString<128> &CommentsToEmit,
formatted_raw_ostream &FormattedOS,
const MCAsmInfo &MAI) {
// Flush the stream before taking its content.
StringRef Comments = CommentsToEmit.str();
// Get the default information for printing a comment.
const char *CommentBegin = MAI.getCommentString();
unsigned CommentColumn = MAI.getCommentColumn();
bool IsFirst = true;
while (!Comments.empty()) {
if (!IsFirst)
FormattedOS << '\n';
// Emit a line of comments.
FormattedOS.PadToColumn(CommentColumn);
size_t Position = Comments.find('\n');
FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
// Move after the newline character.
Comments = Comments.substr(Position + 1);
IsFirst = false;
}
FormattedOS.flush();
// Tell the comment stream that the vector changed underneath it.
CommentsToEmit.clear();
}
static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
StringRef DisSegName, StringRef DisSectName) {
const char *McpuDefault = nullptr;
const Target *ThumbTarget = nullptr;
const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
if (!TheTarget) {
// GetTarget prints out stuff.
return;
}
if (MCPU.empty() && McpuDefault)
MCPU = McpuDefault;
std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
if (ThumbTarget)
ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
if (MAttrs.size()) {
SubtargetFeatures Features;
for (unsigned i = 0; i != MAttrs.size(); ++i)
Features.AddFeature(MAttrs[i]);
FeaturesStr = Features.getString();
}
// Set up disassembler.
std::unique_ptr<const MCRegisterInfo> MRI(
TheTarget->createMCRegInfo(TripleName));
std::unique_ptr<const MCAsmInfo> AsmInfo(
TheTarget->createMCAsmInfo(*MRI, TripleName));
std::unique_ptr<const MCSubtargetInfo> STI(
TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
std::unique_ptr<MCDisassembler> DisAsm(
TheTarget->createMCDisassembler(*STI, Ctx));
std::unique_ptr<MCSymbolizer> Symbolizer;
struct DisassembleInfo SymbolizerInfo;
std::unique_ptr<MCRelocationInfo> RelInfo(
TheTarget->createMCRelocationInfo(TripleName, Ctx));
if (RelInfo) {
Symbolizer.reset(TheTarget->createMCSymbolizer(
TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
&SymbolizerInfo, &Ctx, std::move(RelInfo)));
DisAsm->setSymbolizer(std::move(Symbolizer));
}
int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
// Set the display preference for hex vs. decimal immediates.
IP->setPrintImmHex(PrintImmHex);
// Comment stream and backing vector.
SmallString<128> CommentsToEmit;
raw_svector_ostream CommentStream(CommentsToEmit);
// FIXME: Setting the CommentStream in the InstPrinter is problematic in that
// if it is done then arm64 comments for string literals don't get printed
// and some constant get printed instead and not setting it causes intel
// (32-bit and 64-bit) comments printed with different spacing before the
// comment causing different diffs with the 'C' disassembler library API.
// IP->setCommentStream(CommentStream);
if (!AsmInfo || !STI || !DisAsm || !IP) {
errs() << "error: couldn't initialize disassembler for target "
<< TripleName << '\n';
return;
}
// Set up thumb disassembler.
std::unique_ptr<const MCRegisterInfo> ThumbMRI;
std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
std::unique_ptr<MCDisassembler> ThumbDisAsm;
std::unique_ptr<MCInstPrinter> ThumbIP;
std::unique_ptr<MCContext> ThumbCtx;
std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
struct DisassembleInfo ThumbSymbolizerInfo;
std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
if (ThumbTarget) {
ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
ThumbAsmInfo.reset(
ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
ThumbSTI.reset(
ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
MCContext *PtrThumbCtx = ThumbCtx.get();
ThumbRelInfo.reset(
ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
if (ThumbRelInfo) {
ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
&ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
}
int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
*ThumbInstrInfo, *ThumbMRI));
// Set the display preference for hex vs. decimal immediates.
ThumbIP->setPrintImmHex(PrintImmHex);
}
if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
errs() << "error: couldn't initialize disassembler for target "
<< ThumbTripleName << '\n';
return;
}
MachO::mach_header Header = MachOOF->getHeader();
// FIXME: Using the -cfg command line option, this code used to be able to
// annotate relocations with the referenced symbol's name, and if this was
// inside a __[cf]string section, the data it points to. This is now replaced
// by the upcoming MCSymbolizer, which needs the appropriate setup done above.
std::vector<SectionRef> Sections;
std::vector<SymbolRef> Symbols;
SmallVector<uint64_t, 8> FoundFns;
uint64_t BaseSegmentAddress;
getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
BaseSegmentAddress);
// Sort the symbols by address, just in case they didn't come in that way.
std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
// Build a data in code table that is sorted on by the address of each entry.
uint64_t BaseAddress = 0;
if (Header.filetype == MachO::MH_OBJECT)
BaseAddress = Sections[0].getAddress();
else
BaseAddress = BaseSegmentAddress;
DiceTable Dices;
for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
DI != DE; ++DI) {
uint32_t Offset;
DI->getOffset(Offset);
Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
}
array_pod_sort(Dices.begin(), Dices.end());
#ifndef NDEBUG
raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
#else
raw_ostream &DebugOut = nulls();
#endif
std::unique_ptr<DIContext> diContext;
ObjectFile *DbgObj = MachOOF;
// Try to find debug info and set up the DIContext for it.
if (UseDbg) {
// A separate DSym file path was specified, parse it as a macho file,
// get the sections and supply it to the section name parsing machinery.
if (!DSYMFile.empty()) {
ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
MemoryBuffer::getFileOrSTDIN(DSYMFile);
if (std::error_code EC = BufOrErr.getError()) {
errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
return;
}
DbgObj =
ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
.get()
.release();
}
// Setup the DIContext
diContext.reset(new DWARFContextInMemory(*DbgObj));
}
if (FilterSections.size() == 0)
outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
StringRef SectName;
if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
continue;
DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
if (SegmentName != DisSegName)
continue;
StringRef BytesStr;
Sections[SectIdx].getContents(BytesStr);
ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
BytesStr.size());
uint64_t SectAddress = Sections[SectIdx].getAddress();
bool symbolTableWorked = false;
// Create a map of symbol addresses to symbol names for use by
// the SymbolizerSymbolLookUp() routine.
SymbolAddressMap AddrMap;
bool DisSymNameFound = false;
for (const SymbolRef &Symbol : MachOOF->symbols()) {
SymbolRef::Type ST = Symbol.getType();
if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
ST == SymbolRef::ST_Other) {
uint64_t Address = Symbol.getValue();
ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
if (std::error_code EC = SymNameOrErr.getError())
report_fatal_error(EC.message());
StringRef SymName = *SymNameOrErr;
AddrMap[Address] = SymName;
if (!DisSymName.empty() && DisSymName == SymName)
DisSymNameFound = true;
}
}
if (!DisSymName.empty() && !DisSymNameFound) {
outs() << "Can't find -dis-symname: " << DisSymName << "\n";
return;
}
// Set up the block of info used by the Symbolizer call backs.
SymbolizerInfo.verbose = !NoSymbolicOperands;
SymbolizerInfo.O = MachOOF;
SymbolizerInfo.S = Sections[SectIdx];
SymbolizerInfo.AddrMap = &AddrMap;
SymbolizerInfo.Sections = &Sections;
SymbolizerInfo.class_name = nullptr;
SymbolizerInfo.selector_name = nullptr;
SymbolizerInfo.method = nullptr;
SymbolizerInfo.demangled_name = nullptr;
SymbolizerInfo.bindtable = nullptr;
SymbolizerInfo.adrp_addr = 0;
SymbolizerInfo.adrp_inst = 0;
// Same for the ThumbSymbolizer
ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
ThumbSymbolizerInfo.O = MachOOF;
ThumbSymbolizerInfo.S = Sections[SectIdx];
ThumbSymbolizerInfo.AddrMap = &AddrMap;
ThumbSymbolizerInfo.Sections = &Sections;
ThumbSymbolizerInfo.class_name = nullptr;
ThumbSymbolizerInfo.selector_name = nullptr;
ThumbSymbolizerInfo.method = nullptr;
ThumbSymbolizerInfo.demangled_name = nullptr;
ThumbSymbolizerInfo.bindtable = nullptr;
ThumbSymbolizerInfo.adrp_addr = 0;
ThumbSymbolizerInfo.adrp_inst = 0;
// Disassemble symbol by symbol.
for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
if (std::error_code EC = SymNameOrErr.getError())
report_fatal_error(EC.message());
StringRef SymName = *SymNameOrErr;
SymbolRef::Type ST = Symbols[SymIdx].getType();
if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
continue;
// Make sure the symbol is defined in this section.
bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
if (!containsSym)
continue;
// If we are only disassembling one symbol see if this is that symbol.
if (!DisSymName.empty() && DisSymName != SymName)
continue;
// Start at the address of the symbol relative to the section's address.
uint64_t Start = Symbols[SymIdx].getValue();
uint64_t SectionAddress = Sections[SectIdx].getAddress();
Start -= SectionAddress;
// Stop disassembling either at the beginning of the next symbol or at
// the end of the section.
bool containsNextSym = false;
uint64_t NextSym = 0;
uint64_t NextSymIdx = SymIdx + 1;
while (Symbols.size() > NextSymIdx) {
SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
if (NextSymType == SymbolRef::ST_Function) {
containsNextSym =
Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
NextSym = Symbols[NextSymIdx].getValue();
NextSym -= SectionAddress;
break;
}
++NextSymIdx;
}
uint64_t SectSize = Sections[SectIdx].getSize();
uint64_t End = containsNextSym ? NextSym : SectSize;
uint64_t Size;
symbolTableWorked = true;
DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
bool isThumb =
(MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
outs() << SymName << ":\n";
DILineInfo lastLine;
for (uint64_t Index = Start; Index < End; Index += Size) {
MCInst Inst;
uint64_t PC = SectAddress + Index;
if (!NoLeadingAddr) {
if (FullLeadingAddr) {
if (MachOOF->is64Bit())
outs() << format("%016" PRIx64, PC);
else
outs() << format("%08" PRIx64, PC);
} else {
outs() << format("%8" PRIx64 ":", PC);
}
}
if (!NoShowRawInsn)
outs() << "\t";
// Check the data in code table here to see if this is data not an
// instruction to be disassembled.
DiceTable Dice;
Dice.push_back(std::make_pair(PC, DiceRef()));
dice_table_iterator DTI =
std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
compareDiceTableEntries);
if (DTI != Dices.end()) {
uint16_t Length;
DTI->second.getLength(Length);
uint16_t Kind;
DTI->second.getKind(Kind);
Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
(PC == (DTI->first + Length - 1)) && (Length & 1))
Size++;
continue;
}
SmallVector<char, 64> AnnotationsBytes;
raw_svector_ostream Annotations(AnnotationsBytes);
bool gotInst;
if (isThumb)
gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
PC, DebugOut, Annotations);
else
gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
DebugOut, Annotations);
if (gotInst) {
if (!NoShowRawInsn) {
dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
}
formatted_raw_ostream FormattedOS(outs());
StringRef AnnotationsStr = Annotations.str();
if (isThumb)
ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
else
IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
// Print debug info.
if (diContext) {
DILineInfo dli = diContext->getLineInfoForAddress(PC);
// Print valid line info if it changed.
if (dli != lastLine && dli.Line != 0)
outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
<< dli.Column;
lastLine = dli;
}
outs() << "\n";
} else {
unsigned int Arch = MachOOF->getArch();
if (Arch == Triple::x86_64 || Arch == Triple::x86) {
outs() << format("\t.byte 0x%02x #bad opcode\n",
*(Bytes.data() + Index) & 0xff);
Size = 1; // skip exactly one illegible byte and move on.
} else if (Arch == Triple::aarch64) {
uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
(*(Bytes.data() + Index + 1) & 0xff) << 8 |
(*(Bytes.data() + Index + 2) & 0xff) << 16 |
(*(Bytes.data() + Index + 3) & 0xff) << 24;
outs() << format("\t.long\t0x%08x\n", opcode);
Size = 4;
} else {
errs() << "llvm-objdump: warning: invalid instruction encoding\n";
if (Size == 0)
Size = 1; // skip illegible bytes
}
}
}
}
if (!symbolTableWorked) {
// Reading the symbol table didn't work, disassemble the whole section.
uint64_t SectAddress = Sections[SectIdx].getAddress();
uint64_t SectSize = Sections[SectIdx].getSize();
uint64_t InstSize;
for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
MCInst Inst;
uint64_t PC = SectAddress + Index;
if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
DebugOut, nulls())) {
if (!NoLeadingAddr) {
if (FullLeadingAddr) {
if (MachOOF->is64Bit())
outs() << format("%016" PRIx64, PC);
else
outs() << format("%08" PRIx64, PC);
} else {
outs() << format("%8" PRIx64 ":", PC);
}
}
if (!NoShowRawInsn) {
outs() << "\t";
dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
}
IP->printInst(&Inst, outs(), "", *STI);
outs() << "\n";
} else {
unsigned int Arch = MachOOF->getArch();
if (Arch == Triple::x86_64 || Arch == Triple::x86) {
outs() << format("\t.byte 0x%02x #bad opcode\n",
*(Bytes.data() + Index) & 0xff);
InstSize = 1; // skip exactly one illegible byte and move on.
} else {
errs() << "llvm-objdump: warning: invalid instruction encoding\n";
if (InstSize == 0)
InstSize = 1; // skip illegible bytes
}
}
}
}
// The TripleName's need to be reset if we are called again for a different
// archtecture.
TripleName = "";
ThumbTripleName = "";
if (SymbolizerInfo.method != nullptr)
free(SymbolizerInfo.method);
if (SymbolizerInfo.demangled_name != nullptr)
free(SymbolizerInfo.demangled_name);
if (SymbolizerInfo.bindtable != nullptr)
delete SymbolizerInfo.bindtable;
if (ThumbSymbolizerInfo.method != nullptr)
free(ThumbSymbolizerInfo.method);
if (ThumbSymbolizerInfo.demangled_name != nullptr)
free(ThumbSymbolizerInfo.demangled_name);
if (ThumbSymbolizerInfo.bindtable != nullptr)
delete ThumbSymbolizerInfo.bindtable;
}
}
//===----------------------------------------------------------------------===//
// __compact_unwind section dumping
//===----------------------------------------------------------------------===//
namespace {
template <typename T> static uint64_t readNext(const char *&Buf) {
using llvm::support::little;
using llvm::support::unaligned;
uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
Buf += sizeof(T);
return Val;
}
struct CompactUnwindEntry {
uint32_t OffsetInSection;
uint64_t FunctionAddr;
uint32_t Length;
uint32_t CompactEncoding;
uint64_t PersonalityAddr;
uint64_t LSDAAddr;
RelocationRef FunctionReloc;
RelocationRef PersonalityReloc;
RelocationRef LSDAReloc;
CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
: OffsetInSection(Offset) {
if (Is64)
read<uint64_t>(Contents.data() + Offset);
else
read<uint32_t>(Contents.data() + Offset);
}
private:
template <typename UIntPtr> void read(const char *Buf) {
FunctionAddr = readNext<UIntPtr>(Buf);
Length = readNext<uint32_t>(Buf);
CompactEncoding = readNext<uint32_t>(Buf);
PersonalityAddr = readNext<UIntPtr>(Buf);
LSDAAddr = readNext<UIntPtr>(Buf);
}
};
}
/// Given a relocation from __compact_unwind, consisting of the RelocationRef
/// and data being relocated, determine the best base Name and Addend to use for
/// display purposes.
///
/// 1. An Extern relocation will directly reference a symbol (and the data is
/// then already an addend), so use that.
/// 2. Otherwise the data is an offset in the object file's layout; try to find
// a symbol before it in the same section, and use the offset from there.
/// 3. Finally, if all that fails, fall back to an offset from the start of the
/// referenced section.
static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
std::map<uint64_t, SymbolRef> &Symbols,
const RelocationRef &Reloc, uint64_t Addr,
StringRef &Name, uint64_t &Addend) {
if (Reloc.getSymbol() != Obj->symbol_end()) {
ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
if (std::error_code EC = NameOrErr.getError())
report_fatal_error(EC.message());
Name = *NameOrErr;
Addend = Addr;
return;
}
auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
uint64_t SectionAddr = RelocSection.getAddress();
auto Sym = Symbols.upper_bound(Addr);
if (Sym == Symbols.begin()) {
// The first symbol in the object is after this reference, the best we can
// do is section-relative notation.
RelocSection.getName(Name);
Addend = Addr - SectionAddr;
return;
}
// Go back one so that SymbolAddress <= Addr.
--Sym;
section_iterator SymSection = *Sym->second.getSection();
if (RelocSection == *SymSection) {
// There's a valid symbol in the same section before this reference.
ErrorOr<StringRef> NameOrErr = Sym->second.getName();
if (std::error_code EC = NameOrErr.getError())
report_fatal_error(EC.message());
Name = *NameOrErr;
Addend = Addr - Sym->first;
return;
}
// There is a symbol before this reference, but it's in a different
// section. Probably not helpful to mention it, so use the section name.
RelocSection.getName(Name);
Addend = Addr - SectionAddr;
}
static void printUnwindRelocDest(const MachOObjectFile *Obj,
std::map<uint64_t, SymbolRef> &Symbols,
const RelocationRef &Reloc, uint64_t Addr) {
StringRef Name;
uint64_t Addend;
if (!Reloc.getObject())
return;
findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
outs() << Name;
if (Addend)
outs() << " + " << format("0x%" PRIx64, Addend);
}
static void
printMachOCompactUnwindSection(const MachOObjectFile *Obj,
std::map<uint64_t, SymbolRef> &Symbols,
const SectionRef &CompactUnwind) {
assert(Obj->isLittleEndian() &&
"There should not be a big-endian .o with __compact_unwind");
bool Is64 = Obj->is64Bit();
uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
StringRef Contents;
CompactUnwind.getContents(Contents);
SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
// First populate the initial raw offsets, encodings and so on from the entry.
for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
CompactUnwinds.push_back(Entry);
}
// Next we need to look at the relocations to find out what objects are
// actually being referred to.
for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
uint64_t RelocAddress = Reloc.getOffset();
uint32_t EntryIdx = RelocAddress / EntrySize;
uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
if (OffsetInEntry == 0)
Entry.FunctionReloc = Reloc;
else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
Entry.PersonalityReloc = Reloc;
else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
Entry.LSDAReloc = Reloc;
else
llvm_unreachable("Unexpected relocation in __compact_unwind section");
}
// Finally, we're ready to print the data we've gathered.
outs() << "Contents of __compact_unwind section:\n";
for (auto &Entry : CompactUnwinds) {
outs() << " Entry at offset "
<< format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
// 1. Start of the region this entry applies to.
outs() << " start: " << format("0x%" PRIx64,
Entry.FunctionAddr) << ' ';
printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
outs() << '\n';
// 2. Length of the region this entry applies to.
outs() << " length: " << format("0x%" PRIx32, Entry.Length)
<< '\n';
// 3. The 32-bit compact encoding.
outs() << " compact encoding: "
<< format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
// 4. The personality function, if present.
if (Entry.PersonalityReloc.getObject()) {
outs() << " personality function: "
<< format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
Entry.PersonalityAddr);
outs() << '\n';
}
// 5. This entry's language-specific data area.
if (Entry.LSDAReloc.getObject()) {
outs() << " LSDA: " << format("0x%" PRIx64,
Entry.LSDAAddr) << ' ';
printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
outs() << '\n';
}
}
}
//===----------------------------------------------------------------------===//
// __unwind_info section dumping
//===----------------------------------------------------------------------===//
static void printRegularSecondLevelUnwindPage(const char *PageStart) {
const char *Pos = PageStart;
uint32_t Kind = readNext<uint32_t>(Pos);
(void)Kind;
assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
uint16_t EntriesStart = readNext<uint16_t>(Pos);
uint16_t NumEntries = readNext<uint16_t>(Pos);
Pos = PageStart + EntriesStart;
for (unsigned i = 0; i < NumEntries; ++i) {
uint32_t FunctionOffset = readNext<uint32_t>(Pos);
uint32_t Encoding = readNext<uint32_t>(Pos);
outs() << " [" << i << "]: "
<< "function offset=" << format("0x%08" PRIx32, FunctionOffset)
<< ", "
<< "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
}
}
static void printCompressedSecondLevelUnwindPage(
const char *PageStart, uint32_t FunctionBase,
const SmallVectorImpl<uint32_t> &CommonEncodings) {
const char *Pos = PageStart;
uint32_t Kind = readNext<uint32_t>(Pos);
(void)Kind;
assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
uint16_t EntriesStart = readNext<uint16_t>(Pos);
uint16_t NumEntries = readNext<uint16_t>(Pos);
uint16_t EncodingsStart = readNext<uint16_t>(Pos);
readNext<uint16_t>(Pos);
const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
PageStart + EncodingsStart);
Pos = PageStart + EntriesStart;
for (unsigned i = 0; i < NumEntries; ++i) {
uint32_t Entry = readNext<uint32_t>(Pos);
uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
uint32_t EncodingIdx = Entry >> 24;
uint32_t Encoding;
if (EncodingIdx < CommonEncodings.size())
Encoding = CommonEncodings[EncodingIdx];
else
Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
outs() << " [" << i << "]: "
<< "function offset=" << format("0x%08" PRIx32, FunctionOffset)
<< ", "
<< "encoding[" << EncodingIdx
<< "]=" << format("0x%08" PRIx32, Encoding) << '\n';
}
}
static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
std::map<uint64_t, SymbolRef> &Symbols,
const SectionRef &UnwindInfo) {
assert(Obj->isLittleEndian() &&
"There should not be a big-endian .o with __unwind_info");
outs() << "Contents of __unwind_info section:\n";
StringRef Contents;
UnwindInfo.getContents(Contents);
const char *Pos = Contents.data();
//===----------------------------------
// Section header
//===----------------------------------
uint32_t Version = readNext<uint32_t>(Pos);
outs() << " Version: "
<< format("0x%" PRIx32, Version) << '\n';
assert(Version == 1 && "only understand version 1");
uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
outs() << " Common encodings array section offset: "
<< format("0x%" PRIx32, CommonEncodingsStart) << '\n';
uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
outs() << " Number of common encodings in array: "
<< format("0x%" PRIx32, NumCommonEncodings) << '\n';
uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
outs() << " Personality function array section offset: "
<< format("0x%" PRIx32, PersonalitiesStart) << '\n';
uint32_t NumPersonalities = readNext<uint32_t>(Pos);
outs() << " Number of personality functions in array: "
<< format("0x%" PRIx32, NumPersonalities) << '\n';
uint32_t IndicesStart = readNext<uint32_t>(Pos);
outs() << " Index array section offset: "
<< format("0x%" PRIx32, IndicesStart) << '\n';
uint32_t NumIndices = readNext<uint32_t>(Pos);
outs() << " Number of indices in array: "
<< format("0x%" PRIx32, NumIndices) << '\n';
//===----------------------------------
// A shared list of common encodings
//===----------------------------------
// These occupy indices in the range [0, N] whenever an encoding is referenced
// from a compressed 2nd level index table. In practice the linker only
// creates ~128 of these, so that indices are available to embed encodings in
// the 2nd level index.
SmallVector<uint32_t, 64> CommonEncodings;
outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Pos = Contents.data() + CommonEncodingsStart;
for (unsigned i = 0; i < NumCommonEncodings; ++i) {
uint32_t Encoding = readNext<uint32_t>(Pos);
CommonEncodings.push_back(Encoding);
outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
<< '\n';
}
//===----------------------------------
// Personality functions used in this executable
//===----------------------------------
// There should be only a handful of these (one per source language,
// roughly). Particularly since they only get 2 bits in the compact encoding.
outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Pos = Contents.data() + PersonalitiesStart;
for (unsigned i = 0; i < NumPersonalities; ++i) {
uint32_t PersonalityFn = readNext<uint32_t>(Pos);
outs() << " personality[" << i + 1
<< "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
}
//===----------------------------------
// The level 1 index entries
//===----------------------------------
// These specify an approximate place to start searching for the more detailed
// information, sorted by PC.
struct IndexEntry {
uint32_t FunctionOffset;
uint32_t SecondLevelPageStart;
uint32_t LSDAStart;
};
SmallVector<IndexEntry, 4> IndexEntries;
outs() << " Top level indices: (count = " << NumIndices << ")\n";
Pos = Contents.data() + IndicesStart;
for (unsigned i = 0; i < NumIndices; ++i) {
IndexEntry Entry;
Entry.FunctionOffset = readNext<uint32_t>(Pos);
Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
Entry.LSDAStart = readNext<uint32_t>(Pos);
IndexEntries.push_back(Entry);
outs() << " [" << i << "]: "
<< "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
<< ", "
<< "2nd level page offset="
<< format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
<< "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
}
//===----------------------------------
// Next come the LSDA tables
//===----------------------------------
// The LSDA layout is rather implicit: it's a contiguous array of entries from
// the first top-level index's LSDAOffset to the last (sentinel).
outs() << " LSDA descriptors:\n";
Pos = Contents.data() + IndexEntries[0].LSDAStart;
int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
(2 * sizeof(uint32_t));
for (int i = 0; i < NumLSDAs; ++i) {
uint32_t FunctionOffset = readNext<uint32_t>(Pos);
uint32_t LSDAOffset = readNext<uint32_t>(Pos);
outs() << " [" << i << "]: "
<< "function offset=" << format("0x%08" PRIx32, FunctionOffset)
<< ", "
<< "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
}
//===----------------------------------
// Finally, the 2nd level indices
//===----------------------------------
// Generally these are 4K in size, and have 2 possible forms:
// + Regular stores up to 511 entries with disparate encodings
// + Compressed stores up to 1021 entries if few enough compact encoding
// values are used.
outs() << " Second level indices:\n";
for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
// The final sentinel top-level index has no associated 2nd level page
if (IndexEntries[i].SecondLevelPageStart == 0)
break;
outs() << " Second level index[" << i << "]: "
<< "offset in section="
<< format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
<< ", "
<< "base function offset="
<< format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
if (Kind == 2)
printRegularSecondLevelUnwindPage(Pos);
else if (Kind == 3)
printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
CommonEncodings);
else
llvm_unreachable("Do not know how to print this kind of 2nd level page");
}
}
static unsigned getSizeForEncoding(bool is64Bit,
unsigned symbolEncoding) {
unsigned format = symbolEncoding & 0x0f;
switch (format) {
default: llvm_unreachable("Unknown Encoding");
case dwarf::DW_EH_PE_absptr:
case dwarf::DW_EH_PE_signed:
return is64Bit ? 8 : 4;
case dwarf::DW_EH_PE_udata2:
case dwarf::DW_EH_PE_sdata2:
return 2;
case dwarf::DW_EH_PE_udata4:
case dwarf::DW_EH_PE_sdata4:
return 4;
case dwarf::DW_EH_PE_udata8:
case dwarf::DW_EH_PE_sdata8:
return 8;
}
}
static uint64_t readPointer(const char *&Pos, bool is64Bit, unsigned Encoding) {
switch (getSizeForEncoding(is64Bit, Encoding)) {
case 2:
return readNext<uint16_t>(Pos);
break;
case 4:
return readNext<uint32_t>(Pos);
break;
case 8:
return readNext<uint64_t>(Pos);
break;
default:
llvm_unreachable("Illegal data size");
}
}
static void printMachOEHFrameSection(const MachOObjectFile *Obj,
std::map<uint64_t, SymbolRef> &Symbols,
const SectionRef &EHFrame) {
if (!Obj->isLittleEndian()) {
outs() << "warning: cannot handle big endian __eh_frame section\n";
return;
}
bool is64Bit = Obj->is64Bit();
outs() << "Contents of __eh_frame section:\n";
StringRef Contents;
EHFrame.getContents(Contents);
/// A few fields of the CIE are used when decoding the FDE's. This struct
/// will cache those fields we need so that we don't have to decode it
/// repeatedly for each FDE that references it.
struct DecodedCIE {
Optional<uint32_t> FDEPointerEncoding;
Optional<uint32_t> LSDAPointerEncoding;
bool hasAugmentationLength;
};
// Map from the start offset of the CIE to the cached data for that CIE.
DenseMap<uint64_t, DecodedCIE> CachedCIEs;
for (const char *Pos = Contents.data(), *End = Contents.end(); Pos != End; ) {
const char *EntryStartPos = Pos;
uint64_t Length = readNext<uint32_t>(Pos);
if (Length == 0xffffffff)
Length = readNext<uint64_t>(Pos);
// Save the Pos so that we can check the length we encoded against what we
// end up decoding.
const char *PosAfterLength = Pos;
const char *EntryEndPos = PosAfterLength + Length;
assert(EntryEndPos <= End &&
"__eh_frame entry length exceeds section size");
uint32_t ID = readNext<uint32_t>(Pos);
if (ID == 0) {
// This is a CIE.
uint32_t Version = readNext<uint8_t>(Pos);
// Parse a null terminated augmentation string
SmallString<8> AugmentationString;
for (uint8_t Char = readNext<uint8_t>(Pos); Char;
Char = readNext<uint8_t>(Pos))
AugmentationString.push_back(Char);
// Optionally parse the EH data if the augmentation string says it's there.
Optional<uint64_t> EHData;
if (StringRef(AugmentationString).count("eh"))
EHData = is64Bit ? readNext<uint64_t>(Pos) : readNext<uint32_t>(Pos);
unsigned ULEBByteCount;
uint64_t CodeAlignmentFactor = decodeULEB128((const uint8_t *)Pos,
&ULEBByteCount);
Pos += ULEBByteCount;
int64_t DataAlignmentFactor = decodeSLEB128((const uint8_t *)Pos,
&ULEBByteCount);
Pos += ULEBByteCount;
uint32_t ReturnAddressRegister = readNext<uint8_t>(Pos);
Optional<uint64_t> AugmentationLength;
Optional<uint32_t> LSDAPointerEncoding;
Optional<uint32_t> PersonalityEncoding;
Optional<uint64_t> Personality;
Optional<uint32_t> FDEPointerEncoding;
if (!AugmentationString.empty() && AugmentationString.front() == 'z') {
AugmentationLength = decodeULEB128((const uint8_t *)Pos,
&ULEBByteCount);
Pos += ULEBByteCount;
// Walk the augmentation string to get all the augmentation data.
for (unsigned i = 1, e = AugmentationString.size(); i != e; ++i) {
char Char = AugmentationString[i];
switch (Char) {
case 'e':
assert((i + 1) != e && AugmentationString[i + 1] == 'h' &&
"Expected 'eh' in augmentation string");
break;
case 'L':
assert(!LSDAPointerEncoding && "Duplicate LSDA encoding");
LSDAPointerEncoding = readNext<uint8_t>(Pos);
break;
case 'P': {
assert(!Personality && "Duplicate personality");
PersonalityEncoding = readNext<uint8_t>(Pos);
Personality = readPointer(Pos, is64Bit, *PersonalityEncoding);
break;
}
case 'R':
assert(!FDEPointerEncoding && "Duplicate FDE encoding");
FDEPointerEncoding = readNext<uint8_t>(Pos);
break;
case 'z':
llvm_unreachable("'z' must be first in the augmentation string");
}
}
}
outs() << "CIE:\n";
outs() << " Length: " << Length << "\n";
outs() << " CIE ID: " << ID << "\n";
outs() << " Version: " << Version << "\n";
outs() << " Augmentation String: " << AugmentationString << "\n";
if (EHData)
outs() << " EHData: " << *EHData << "\n";
outs() << " Code Alignment Factor: " << CodeAlignmentFactor << "\n";
outs() << " Data Alignment Factor: " << DataAlignmentFactor << "\n";
outs() << " Return Address Register: " << ReturnAddressRegister << "\n";
if (AugmentationLength) {
outs() << " Augmentation Data Length: " << *AugmentationLength << "\n";
if (LSDAPointerEncoding) {
outs() << " FDE LSDA Pointer Encoding: "
<< *LSDAPointerEncoding << "\n";
}
if (Personality) {
outs() << " Personality Encoding: " << *PersonalityEncoding << "\n";
outs() << " Personality: " << *Personality << "\n";
}
if (FDEPointerEncoding) {
outs() << " FDE Address Pointer Encoding: "
<< *FDEPointerEncoding << "\n";
}
}
// FIXME: Handle instructions.
// For now just emit some bytes
outs() << " Instructions:\n ";
dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
outs());
outs() << "\n";
Pos = EntryEndPos;
// Cache this entry.
uint64_t Offset = EntryStartPos - Contents.data();
CachedCIEs[Offset] = { FDEPointerEncoding, LSDAPointerEncoding,
AugmentationLength.hasValue() };
continue;
}
// This is an FDE.
// The CIE pointer for an FDE is the same location as the ID which we
// already read.
uint32_t CIEPointer = ID;
const char *CIEStart = PosAfterLength - CIEPointer;
assert(CIEStart >= Contents.data() &&
"FDE points to CIE before the __eh_frame start");
uint64_t CIEOffset = CIEStart - Contents.data();
auto CIEIt = CachedCIEs.find(CIEOffset);
if (CIEIt == CachedCIEs.end())
llvm_unreachable("Couldn't find CIE at offset in to __eh_frame section");
const DecodedCIE &CIE = CIEIt->getSecond();
assert(CIE.FDEPointerEncoding &&
"FDE references CIE which did not set pointer encoding");
uint64_t PCPointerSize = getSizeForEncoding(is64Bit,
*CIE.FDEPointerEncoding);
uint64_t PCBegin = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
uint64_t PCRange = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
Optional<uint64_t> AugmentationLength;
uint32_t LSDAPointerSize;
Optional<uint64_t> LSDAPointer;
if (CIE.hasAugmentationLength) {
unsigned ULEBByteCount;
AugmentationLength = decodeULEB128((const uint8_t *)Pos,
&ULEBByteCount);
Pos += ULEBByteCount;
// Decode the LSDA if the CIE augmentation string said we should.
if (CIE.LSDAPointerEncoding) {
LSDAPointerSize = getSizeForEncoding(is64Bit, *CIE.LSDAPointerEncoding);
LSDAPointer = readPointer(Pos, is64Bit, *CIE.LSDAPointerEncoding);
}
}
outs() << "FDE:\n";
outs() << " Length: " << Length << "\n";
outs() << " CIE Offset: " << CIEOffset << "\n";
if (PCPointerSize == 8) {
outs() << format(" PC Begin: %016" PRIx64, PCBegin) << "\n";
outs() << format(" PC Range: %016" PRIx64, PCRange) << "\n";
} else {
outs() << format(" PC Begin: %08" PRIx64, PCBegin) << "\n";
outs() << format(" PC Range: %08" PRIx64, PCRange) << "\n";
}
if (AugmentationLength) {
outs() << " Augmentation Data Length: " << *AugmentationLength << "\n";
if (LSDAPointer) {
if (LSDAPointerSize == 8)
outs() << format(" LSDA Pointer: %016\n" PRIx64, *LSDAPointer);
else
outs() << format(" LSDA Pointer: %08\n" PRIx64, *LSDAPointer);
}
}
// FIXME: Handle instructions.
// For now just emit some bytes
outs() << " Instructions:\n ";
dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
outs());
outs() << "\n";
Pos = EntryEndPos;
}
}
void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
std::map<uint64_t, SymbolRef> Symbols;
for (const SymbolRef &SymRef : Obj->symbols()) {
// Discard any undefined or absolute symbols. They're not going to take part
// in the convenience lookup for unwind info and just take up resources.
section_iterator Section = *SymRef.getSection();
if (Section == Obj->section_end())
continue;
uint64_t Addr = SymRef.getValue();
Symbols.insert(std::make_pair(Addr, SymRef));
}
for (const SectionRef &Section : Obj->sections()) {
StringRef SectName;
Section.getName(SectName);
if (SectName == "__compact_unwind")
printMachOCompactUnwindSection(Obj, Symbols, Section);
else if (SectName == "__unwind_info")
printMachOUnwindInfoSection(Obj, Symbols, Section);
else if (SectName == "__eh_frame")
printMachOEHFrameSection(Obj, Symbols, Section);
}
}
static void PrintMachHeader(uint32_t magic, uint32_t cputype,
uint32_t cpusubtype, uint32_t filetype,
uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
bool verbose) {
outs() << "Mach header\n";
outs() << " magic cputype cpusubtype caps filetype ncmds "
"sizeofcmds flags\n";
if (verbose) {
if (magic == MachO::MH_MAGIC)
outs() << " MH_MAGIC";
else if (magic == MachO::MH_MAGIC_64)
outs() << "MH_MAGIC_64";
else
outs() << format(" 0x%08" PRIx32, magic);
switch (cputype) {
case MachO::CPU_TYPE_I386:
outs() << " I386";
switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
case MachO::CPU_SUBTYPE_I386_ALL:
outs() << " ALL";
break;
default:
outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
break;
}
break;
case MachO::CPU_TYPE_X86_64:
outs() << " X86_64";
switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
case MachO::CPU_SUBTYPE_X86_64_ALL:
outs() << " ALL";
break;
case MachO::CPU_SUBTYPE_X86_64_H:
outs() << " Haswell";
break;
default:
outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
break;
}
break;
case MachO::CPU_TYPE_ARM:
outs() << " ARM";
switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
case MachO::CPU_SUBTYPE_ARM_ALL:
outs() << " ALL";
break;
case MachO::CPU_SUBTYPE_ARM_V4T:
outs() << " V4T";
break;
case MachO::CPU_SUBTYPE_ARM_V5TEJ:
outs() << " V5TEJ";
break;
case MachO::CPU_SUBTYPE_ARM_XSCALE:
outs() << " XSCALE";
break;
case MachO::CPU_SUBTYPE_ARM_V6:
outs() << " V6";
break;
case MachO::CPU_SUBTYPE_ARM_V6M:
outs() << " V6M";
break;
case MachO::CPU_SUBTYPE_ARM_V7:
outs() << " V7";
break;
case MachO::CPU_SUBTYPE_ARM_V7EM:
outs() << " V7EM";
break;
case MachO::CPU_SUBTYPE_ARM_V7K:
outs() << " V7K";
break;
case MachO::CPU_SUBTYPE_ARM_V7M:
outs() << " V7M";
break;
case MachO::CPU_SUBTYPE_ARM_V7S:
outs() << " V7S";
break;
default:
outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
break;
}
break;
case MachO::CPU_TYPE_ARM64:
outs() << " ARM64";
switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
case MachO::CPU_SUBTYPE_ARM64_ALL:
outs() << " ALL";
break;
default:
outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
break;
}
break;
case MachO::CPU_TYPE_POWERPC:
outs() << " PPC";
switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
case MachO::CPU_SUBTYPE_POWERPC_ALL:
outs() << " ALL";
break;
default:
outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
break;
}
break;
case MachO::CPU_TYPE_POWERPC64:
outs() << " PPC64";
switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
case MachO::CPU_SUBTYPE_POWERPC_ALL:
outs() << " ALL";
break;
default:
outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
break;
}
break;
}
if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
outs() << " LIB64";
} else {
outs() << format(" 0x%02" PRIx32,
(cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
}
switch (filetype) {
case MachO::MH_OBJECT:
outs() << " OBJECT";
break;
case MachO::MH_EXECUTE:
outs() << " EXECUTE";
break;
case MachO::MH_FVMLIB:
outs() << " FVMLIB";
break;
case MachO::MH_CORE:
outs() << " CORE";
break;
case MachO::MH_PRELOAD:
outs() << " PRELOAD";
break;
case MachO::MH_DYLIB:
outs() << " DYLIB";
break;
case MachO::MH_DYLIB_STUB:
outs() << " DYLIB_STUB";
break;
case MachO::MH_DYLINKER:
outs() << " DYLINKER";
break;
case MachO::MH_BUNDLE:
outs() << " BUNDLE";
break;
case MachO::MH_DSYM:
outs() << " DSYM";
break;
case MachO::MH_KEXT_BUNDLE:
outs() << " KEXTBUNDLE";
break;
default:
outs() << format(" %10u", filetype);
break;
}
outs() << format(" %5u", ncmds);
outs() << format(" %10u", sizeofcmds);
uint32_t f = flags;
if (f & MachO::MH_NOUNDEFS) {
outs() << " NOUNDEFS";
f &= ~MachO::MH_NOUNDEFS;
}
if (f & MachO::MH_INCRLINK) {
outs() << " INCRLINK";
f &= ~MachO::MH_INCRLINK;
}
if (f & MachO::MH_DYLDLINK) {
outs() << " DYLDLINK";
f &= ~MachO::MH_DYLDLINK;
}
if (f & MachO::MH_BINDATLOAD) {
outs() << " BINDATLOAD";
f &= ~MachO::MH_BINDATLOAD;
}
if (f & MachO::MH_PREBOUND) {
outs() << " PREBOUND";
f &= ~MachO::MH_PREBOUND;
}
if (f & MachO::MH_SPLIT_SEGS) {
outs() << " SPLIT_SEGS";
f &= ~MachO::MH_SPLIT_SEGS;
}
if (f & MachO::MH_LAZY_INIT) {
outs() << " LAZY_INIT";
f &= ~MachO::MH_LAZY_INIT;
}
if (f & MachO::MH_TWOLEVEL) {
outs() << " TWOLEVEL";
f &= ~MachO::MH_TWOLEVEL;
}
if (f & MachO::MH_FORCE_FLAT) {
outs() << " FORCE_FLAT";
f &= ~MachO::MH_FORCE_FLAT;
}
if (f & MachO::MH_NOMULTIDEFS) {
outs() << " NOMULTIDEFS";
f &= ~MachO::MH_NOMULTIDEFS;
}
if (f & MachO::MH_NOFIXPREBINDING) {
outs() << " NOFIXPREBINDING";
f &= ~MachO::MH_NOFIXPREBINDING;
}
if (f & MachO::MH_PREBINDABLE) {
outs() << " PREBINDABLE";
f &= ~MachO::MH_PREBINDABLE;
}
if (f & MachO::MH_ALLMODSBOUND) {
outs() << " ALLMODSBOUND";
f &= ~MachO::MH_ALLMODSBOUND;
}
if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
outs() << " SUBSECTIONS_VIA_SYMBOLS";
f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
}
if (f & MachO::MH_CANONICAL) {
outs() << " CANONICAL";
f &= ~MachO::MH_CANONICAL;
}
if (f & MachO::MH_WEAK_DEFINES) {
outs() << " WEAK_DEFINES";
f &= ~MachO::MH_WEAK_DEFINES;
}
if (f & MachO::MH_BINDS_TO_WEAK) {
outs() << " BINDS_TO_WEAK";
f &= ~MachO::MH_BINDS_TO_WEAK;
}
if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
outs() << " ALLOW_STACK_EXECUTION";
f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
}
if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
outs() << " DEAD_STRIPPABLE_DYLIB";
f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
}
if (f & MachO::MH_PIE) {
outs() << " PIE";
f &= ~MachO::MH_PIE;
}
if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
outs() << " NO_REEXPORTED_DYLIBS";
f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
}
if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
outs() << " MH_HAS_TLV_DESCRIPTORS";
f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
}
if (f & MachO::MH_NO_HEAP_EXECUTION) {
outs() << " MH_NO_HEAP_EXECUTION";
f &= ~MachO::MH_NO_HEAP_EXECUTION;
}
if (f & MachO::MH_APP_EXTENSION_SAFE) {
outs() << " APP_EXTENSION_SAFE";
f &= ~MachO::MH_APP_EXTENSION_SAFE;
}
if (f != 0 || flags == 0)
outs() << format(" 0x%08" PRIx32, f);
} else {
outs() << format(" 0x%08" PRIx32, magic);
outs() << format(" %7d", cputype);
outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
outs() << format(" 0x%02" PRIx32,
(cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
outs() << format(" %10u", filetype);
outs() << format(" %5u", ncmds);
outs() << format(" %10u", sizeofcmds);
outs() << format(" 0x%08" PRIx32, flags);
}
outs() << "\n";
}
static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
StringRef SegName, uint64_t vmaddr,
uint64_t vmsize, uint64_t fileoff,
uint64_t filesize, uint32_t maxprot,
uint32_t initprot, uint32_t nsects,
uint32_t flags, uint32_t object_size,
bool verbose) {
uint64_t expected_cmdsize;
if (cmd == MachO::LC_SEGMENT) {
outs() << " cmd LC_SEGMENT\n";
expected_cmdsize = nsects;
expected_cmdsize *= sizeof(struct MachO::section);
expected_cmdsize += sizeof(struct MachO::segment_command);
} else {
outs() << " cmd LC_SEGMENT_64\n";
expected_cmdsize = nsects;
expected_cmdsize *= sizeof(struct MachO::section_64);
expected_cmdsize += sizeof(struct MachO::segment_command_64);
}
outs() << " cmdsize " << cmdsize;
if (cmdsize != expected_cmdsize)
outs() << " Inconsistent size\n";
else
outs() << "\n";
outs() << " segname " << SegName << "\n";
if (cmd == MachO::LC_SEGMENT_64) {
outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
} else {
outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
}
outs() << " fileoff " << fileoff;
if (fileoff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " filesize " << filesize;
if (fileoff + filesize > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
if (verbose) {
if ((maxprot &
~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
MachO::VM_PROT_EXECUTE)) != 0)
outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
else {
outs() << " maxprot ";
outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
}
if ((initprot &
~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
MachO::VM_PROT_EXECUTE)) != 0)
outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
else {
outs() << " initprot ";
outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
}
} else {
outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
}
outs() << " nsects " << nsects << "\n";
if (verbose) {
outs() << " flags";
if (flags == 0)
outs() << " (none)\n";
else {
if (flags & MachO::SG_HIGHVM) {
outs() << " HIGHVM";
flags &= ~MachO::SG_HIGHVM;
}
if (flags & MachO::SG_FVMLIB) {
outs() << " FVMLIB";
flags &= ~MachO::SG_FVMLIB;
}
if (flags & MachO::SG_NORELOC) {
outs() << " NORELOC";
flags &= ~MachO::SG_NORELOC;
}
if (flags & MachO::SG_PROTECTED_VERSION_1) {
outs() << " PROTECTED_VERSION_1";
flags &= ~MachO::SG_PROTECTED_VERSION_1;
}
if (flags)
outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
else
outs() << "\n";
}
} else {
outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
}
}
static void PrintSection(const char *sectname, const char *segname,
uint64_t addr, uint64_t size, uint32_t offset,
uint32_t align, uint32_t reloff, uint32_t nreloc,
uint32_t flags, uint32_t reserved1, uint32_t reserved2,
uint32_t cmd, const char *sg_segname,
uint32_t filetype, uint32_t object_size,
bool verbose) {
outs() << "Section\n";
outs() << " sectname " << format("%.16s\n", sectname);
outs() << " segname " << format("%.16s", segname);
if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
outs() << " (does not match segment)\n";
else
outs() << "\n";
if (cmd == MachO::LC_SEGMENT_64) {
outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
outs() << " size " << format("0x%016" PRIx64, size);
} else {
outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
outs() << " size " << format("0x%08" PRIx64, size);
}
if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " offset " << offset;
if (offset > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
uint32_t align_shifted = 1 << align;
outs() << " align 2^" << align << " (" << align_shifted << ")\n";
outs() << " reloff " << reloff;
if (reloff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " nreloc " << nreloc;
if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
uint32_t section_type = flags & MachO::SECTION_TYPE;
if (verbose) {
outs() << " type";
if (section_type == MachO::S_REGULAR)
outs() << " S_REGULAR\n";
else if (section_type == MachO::S_ZEROFILL)
outs() << " S_ZEROFILL\n";
else if (section_type == MachO::S_CSTRING_LITERALS)
outs() << " S_CSTRING_LITERALS\n";
else if (section_type == MachO::S_4BYTE_LITERALS)
outs() << " S_4BYTE_LITERALS\n";
else if (section_type == MachO::S_8BYTE_LITERALS)
outs() << " S_8BYTE_LITERALS\n";
else if (section_type == MachO::S_16BYTE_LITERALS)
outs() << " S_16BYTE_LITERALS\n";
else if (section_type == MachO::S_LITERAL_POINTERS)
outs() << " S_LITERAL_POINTERS\n";
else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
outs() << " S_LAZY_SYMBOL_POINTERS\n";
else if (section_type == MachO::S_SYMBOL_STUBS)
outs() << " S_SYMBOL_STUBS\n";
else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
outs() << " S_MOD_INIT_FUNC_POINTERS\n";
else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
outs() << " S_MOD_TERM_FUNC_POINTERS\n";
else if (section_type == MachO::S_COALESCED)
outs() << " S_COALESCED\n";
else if (section_type == MachO::S_INTERPOSING)
outs() << " S_INTERPOSING\n";
else if (section_type == MachO::S_DTRACE_DOF)
outs() << " S_DTRACE_DOF\n";
else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
outs() << " S_THREAD_LOCAL_REGULAR\n";
else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
outs() << " S_THREAD_LOCAL_ZEROFILL\n";
else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
outs() << " S_THREAD_LOCAL_VARIABLES\n";
else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
else
outs() << format("0x%08" PRIx32, section_type) << "\n";
outs() << "attributes";
uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
outs() << " PURE_INSTRUCTIONS";
if (section_attributes & MachO::S_ATTR_NO_TOC)
outs() << " NO_TOC";
if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
outs() << " STRIP_STATIC_SYMS";
if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
outs() << " NO_DEAD_STRIP";
if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
outs() << " LIVE_SUPPORT";
if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
outs() << " SELF_MODIFYING_CODE";
if (section_attributes & MachO::S_ATTR_DEBUG)
outs() << " DEBUG";
if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
outs() << " SOME_INSTRUCTIONS";
if (section_attributes & MachO::S_ATTR_EXT_RELOC)
outs() << " EXT_RELOC";
if (section_attributes & MachO::S_ATTR_LOC_RELOC)
outs() << " LOC_RELOC";
if (section_attributes == 0)
outs() << " (none)";
outs() << "\n";
} else
outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
outs() << " reserved1 " << reserved1;
if (section_type == MachO::S_SYMBOL_STUBS ||
section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
outs() << " (index into indirect symbol table)\n";
else
outs() << "\n";
outs() << " reserved2 " << reserved2;
if (section_type == MachO::S_SYMBOL_STUBS)
outs() << " (size of stubs)\n";
else
outs() << "\n";
}
static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
uint32_t object_size) {
outs() << " cmd LC_SYMTAB\n";
outs() << " cmdsize " << st.cmdsize;
if (st.cmdsize != sizeof(struct MachO::symtab_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " symoff " << st.symoff;
if (st.symoff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " nsyms " << st.nsyms;
uint64_t big_size;
if (Is64Bit) {
big_size = st.nsyms;
big_size *= sizeof(struct MachO::nlist_64);
big_size += st.symoff;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
} else {
big_size = st.nsyms;
big_size *= sizeof(struct MachO::nlist);
big_size += st.symoff;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
}
outs() << " stroff " << st.stroff;
if (st.stroff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " strsize " << st.strsize;
big_size = st.stroff;
big_size += st.strsize;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
}
static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
uint32_t nsyms, uint32_t object_size,
bool Is64Bit) {
outs() << " cmd LC_DYSYMTAB\n";
outs() << " cmdsize " << dyst.cmdsize;
if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " ilocalsym " << dyst.ilocalsym;
if (dyst.ilocalsym > nsyms)
outs() << " (greater than the number of symbols)\n";
else
outs() << "\n";
outs() << " nlocalsym " << dyst.nlocalsym;
uint64_t big_size;
big_size = dyst.ilocalsym;
big_size += dyst.nlocalsym;
if (big_size > nsyms)
outs() << " (past the end of the symbol table)\n";
else
outs() << "\n";
outs() << " iextdefsym " << dyst.iextdefsym;
if (dyst.iextdefsym > nsyms)
outs() << " (greater than the number of symbols)\n";
else
outs() << "\n";
outs() << " nextdefsym " << dyst.nextdefsym;
big_size = dyst.iextdefsym;
big_size += dyst.nextdefsym;
if (big_size > nsyms)
outs() << " (past the end of the symbol table)\n";
else
outs() << "\n";
outs() << " iundefsym " << dyst.iundefsym;
if (dyst.iundefsym > nsyms)
outs() << " (greater than the number of symbols)\n";
else
outs() << "\n";
outs() << " nundefsym " << dyst.nundefsym;
big_size = dyst.iundefsym;
big_size += dyst.nundefsym;
if (big_size > nsyms)
outs() << " (past the end of the symbol table)\n";
else
outs() << "\n";
outs() << " tocoff " << dyst.tocoff;
if (dyst.tocoff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " ntoc " << dyst.ntoc;
big_size = dyst.ntoc;
big_size *= sizeof(struct MachO::dylib_table_of_contents);
big_size += dyst.tocoff;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " modtaboff " << dyst.modtaboff;
if (dyst.modtaboff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " nmodtab " << dyst.nmodtab;
uint64_t modtabend;
if (Is64Bit) {
modtabend = dyst.nmodtab;
modtabend *= sizeof(struct MachO::dylib_module_64);
modtabend += dyst.modtaboff;
} else {
modtabend = dyst.nmodtab;
modtabend *= sizeof(struct MachO::dylib_module);
modtabend += dyst.modtaboff;
}
if (modtabend > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " extrefsymoff " << dyst.extrefsymoff;
if (dyst.extrefsymoff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " nextrefsyms " << dyst.nextrefsyms;
big_size = dyst.nextrefsyms;
big_size *= sizeof(struct MachO::dylib_reference);
big_size += dyst.extrefsymoff;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " indirectsymoff " << dyst.indirectsymoff;
if (dyst.indirectsymoff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " nindirectsyms " << dyst.nindirectsyms;
big_size = dyst.nindirectsyms;
big_size *= sizeof(uint32_t);
big_size += dyst.indirectsymoff;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " extreloff " << dyst.extreloff;
if (dyst.extreloff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " nextrel " << dyst.nextrel;
big_size = dyst.nextrel;
big_size *= sizeof(struct MachO::relocation_info);
big_size += dyst.extreloff;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " locreloff " << dyst.locreloff;
if (dyst.locreloff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " nlocrel " << dyst.nlocrel;
big_size = dyst.nlocrel;
big_size *= sizeof(struct MachO::relocation_info);
big_size += dyst.locreloff;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
}
static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
uint32_t object_size) {
if (dc.cmd == MachO::LC_DYLD_INFO)
outs() << " cmd LC_DYLD_INFO\n";
else
outs() << " cmd LC_DYLD_INFO_ONLY\n";
outs() << " cmdsize " << dc.cmdsize;
if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " rebase_off " << dc.rebase_off;
if (dc.rebase_off > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " rebase_size " << dc.rebase_size;
uint64_t big_size;
big_size = dc.rebase_off;
big_size += dc.rebase_size;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " bind_off " << dc.bind_off;
if (dc.bind_off > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " bind_size " << dc.bind_size;
big_size = dc.bind_off;
big_size += dc.bind_size;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " weak_bind_off " << dc.weak_bind_off;
if (dc.weak_bind_off > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " weak_bind_size " << dc.weak_bind_size;
big_size = dc.weak_bind_off;
big_size += dc.weak_bind_size;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " lazy_bind_off " << dc.lazy_bind_off;
if (dc.lazy_bind_off > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " lazy_bind_size " << dc.lazy_bind_size;
big_size = dc.lazy_bind_off;
big_size += dc.lazy_bind_size;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " export_off " << dc.export_off;
if (dc.export_off > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " export_size " << dc.export_size;
big_size = dc.export_off;
big_size += dc.export_size;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
}
static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
const char *Ptr) {
if (dyld.cmd == MachO::LC_ID_DYLINKER)
outs() << " cmd LC_ID_DYLINKER\n";
else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
outs() << " cmd LC_LOAD_DYLINKER\n";
else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
outs() << " cmd LC_DYLD_ENVIRONMENT\n";
else
outs() << " cmd ?(" << dyld.cmd << ")\n";
outs() << " cmdsize " << dyld.cmdsize;
if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
if (dyld.name >= dyld.cmdsize)
outs() << " name ?(bad offset " << dyld.name << ")\n";
else {
const char *P = (const char *)(Ptr) + dyld.name;
outs() << " name " << P << " (offset " << dyld.name << ")\n";
}
}
static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
outs() << " cmd LC_UUID\n";
outs() << " cmdsize " << uuid.cmdsize;
if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " uuid ";
for (int i = 0; i < 16; ++i) {
outs() << format("%02" PRIX32, uuid.uuid[i]);
if (i == 3 || i == 5 || i == 7 || i == 9)
outs() << "-";
}
outs() << "\n";
}
static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
outs() << " cmd LC_RPATH\n";
outs() << " cmdsize " << rpath.cmdsize;
if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
if (rpath.path >= rpath.cmdsize)
outs() << " path ?(bad offset " << rpath.path << ")\n";
else {
const char *P = (const char *)(Ptr) + rpath.path;
outs() << " path " << P << " (offset " << rpath.path << ")\n";
}
}
static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
StringRef LoadCmdName;
switch (vd.cmd) {
case MachO::LC_VERSION_MIN_MACOSX:
LoadCmdName = "LC_VERSION_MIN_MACOSX";
break;
case MachO::LC_VERSION_MIN_IPHONEOS:
LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
break;
case MachO::LC_VERSION_MIN_TVOS:
LoadCmdName = "LC_VERSION_MIN_TVOS";
break;
case MachO::LC_VERSION_MIN_WATCHOS:
LoadCmdName = "LC_VERSION_MIN_WATCHOS";
break;
default:
llvm_unreachable("Unknown version min load command");
}
outs() << " cmd " << LoadCmdName << '\n';
outs() << " cmdsize " << vd.cmdsize;
if (vd.cmdsize != sizeof(struct MachO::version_min_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " version "
<< MachOObjectFile::getVersionMinMajor(vd, false) << "."
<< MachOObjectFile::getVersionMinMinor(vd, false);
uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
if (Update != 0)
outs() << "." << Update;
outs() << "\n";
if (vd.sdk == 0)
outs() << " sdk n/a";
else {
outs() << " sdk "
<< MachOObjectFile::getVersionMinMajor(vd, true) << "."
<< MachOObjectFile::getVersionMinMinor(vd, true);
}
Update = MachOObjectFile::getVersionMinUpdate(vd, true);
if (Update != 0)
outs() << "." << Update;
outs() << "\n";
}
static void PrintSourceVersionCommand(MachO::source_version_command sd) {
outs() << " cmd LC_SOURCE_VERSION\n";
outs() << " cmdsize " << sd.cmdsize;
if (sd.cmdsize != sizeof(struct MachO::source_version_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
uint64_t a = (sd.version >> 40) & 0xffffff;
uint64_t b = (sd.version >> 30) & 0x3ff;
uint64_t c = (sd.version >> 20) & 0x3ff;
uint64_t d = (sd.version >> 10) & 0x3ff;
uint64_t e = sd.version & 0x3ff;
outs() << " version " << a << "." << b;
if (e != 0)
outs() << "." << c << "." << d << "." << e;
else if (d != 0)
outs() << "." << c << "." << d;
else if (c != 0)
outs() << "." << c;
outs() << "\n";
}
static void PrintEntryPointCommand(MachO::entry_point_command ep) {
outs() << " cmd LC_MAIN\n";
outs() << " cmdsize " << ep.cmdsize;
if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " entryoff " << ep.entryoff << "\n";
outs() << " stacksize " << ep.stacksize << "\n";
}
static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
uint32_t object_size) {
outs() << " cmd LC_ENCRYPTION_INFO\n";
outs() << " cmdsize " << ec.cmdsize;
if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " cryptoff " << ec.cryptoff;
if (ec.cryptoff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " cryptsize " << ec.cryptsize;
if (ec.cryptsize > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " cryptid " << ec.cryptid << "\n";
}
static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
uint32_t object_size) {
outs() << " cmd LC_ENCRYPTION_INFO_64\n";
outs() << " cmdsize " << ec.cmdsize;
if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " cryptoff " << ec.cryptoff;
if (ec.cryptoff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " cryptsize " << ec.cryptsize;
if (ec.cryptsize > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " cryptid " << ec.cryptid << "\n";
outs() << " pad " << ec.pad << "\n";
}
static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
const char *Ptr) {
outs() << " cmd LC_LINKER_OPTION\n";
outs() << " cmdsize " << lo.cmdsize;
if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " count " << lo.count << "\n";
const char *string = Ptr + sizeof(struct MachO::linker_option_command);
uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
uint32_t i = 0;
while (left > 0) {
while (*string == '\0' && left > 0) {
string++;
left--;
}
if (left > 0) {
i++;
outs() << " string #" << i << " " << format("%.*s\n", left, string);
uint32_t NullPos = StringRef(string, left).find('\0');
uint32_t len = std::min(NullPos, left) + 1;
string += len;
left -= len;
}
}
if (lo.count != i)
outs() << " count " << lo.count << " does not match number of strings "
<< i << "\n";
}
static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
const char *Ptr) {
outs() << " cmd LC_SUB_FRAMEWORK\n";
outs() << " cmdsize " << sub.cmdsize;
if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
if (sub.umbrella < sub.cmdsize) {
const char *P = Ptr + sub.umbrella;
outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
} else {
outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
}
}
static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
const char *Ptr) {
outs() << " cmd LC_SUB_UMBRELLA\n";
outs() << " cmdsize " << sub.cmdsize;
if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
if (sub.sub_umbrella < sub.cmdsize) {
const char *P = Ptr + sub.sub_umbrella;
outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
} else {
outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
}
}
static void PrintSubLibraryCommand(MachO::sub_library_command sub,
const char *Ptr) {
outs() << " cmd LC_SUB_LIBRARY\n";
outs() << " cmdsize " << sub.cmdsize;
if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
if (sub.sub_library < sub.cmdsize) {
const char *P = Ptr + sub.sub_library;
outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
} else {
outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
}
}
static void PrintSubClientCommand(MachO::sub_client_command sub,
const char *Ptr) {
outs() << " cmd LC_SUB_CLIENT\n";
outs() << " cmdsize " << sub.cmdsize;
if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
if (sub.client < sub.cmdsize) {
const char *P = Ptr + sub.client;
outs() << " client " << P << " (offset " << sub.client << ")\n";
} else {
outs() << " client ?(bad offset " << sub.client << ")\n";
}
}
static void PrintRoutinesCommand(MachO::routines_command r) {
outs() << " cmd LC_ROUTINES\n";
outs() << " cmdsize " << r.cmdsize;
if (r.cmdsize != sizeof(struct MachO::routines_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
outs() << " init_module " << r.init_module << "\n";
outs() << " reserved1 " << r.reserved1 << "\n";
outs() << " reserved2 " << r.reserved2 << "\n";
outs() << " reserved3 " << r.reserved3 << "\n";
outs() << " reserved4 " << r.reserved4 << "\n";
outs() << " reserved5 " << r.reserved5 << "\n";
outs() << " reserved6 " << r.reserved6 << "\n";
}
static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
outs() << " cmd LC_ROUTINES_64\n";
outs() << " cmdsize " << r.cmdsize;
if (r.cmdsize != sizeof(struct MachO::routines_command_64))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
outs() << " init_module " << r.init_module << "\n";
outs() << " reserved1 " << r.reserved1 << "\n";
outs() << " reserved2 " << r.reserved2 << "\n";
outs() << " reserved3 " << r.reserved3 << "\n";
outs() << " reserved4 " << r.reserved4 << "\n";
outs() << " reserved5 " << r.reserved5 << "\n";
outs() << " reserved6 " << r.reserved6 << "\n";
}
static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
}
static void Print_mmst_reg(MachO::mmst_reg_t &r) {
uint32_t f;
outs() << "\t mmst_reg ";
for (f = 0; f < 10; f++)
outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
outs() << "\n";
outs() << "\t mmst_rsrv ";
for (f = 0; f < 6; f++)
outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
outs() << "\n";
}
static void Print_xmm_reg(MachO::xmm_reg_t &r) {
uint32_t f;
outs() << "\t xmm_reg ";
for (f = 0; f < 16; f++)
outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
outs() << "\n";
}
static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
outs() << " denorm " << fpu.fpu_fcw.denorm;
outs() << " zdiv " << fpu.fpu_fcw.zdiv;
outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
outs() << " undfl " << fpu.fpu_fcw.undfl;
outs() << " precis " << fpu.fpu_fcw.precis << "\n";
outs() << "\t\t pc ";
if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
outs() << "FP_PREC_24B ";
else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
outs() << "FP_PREC_53B ";
else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
outs() << "FP_PREC_64B ";
else
outs() << fpu.fpu_fcw.pc << " ";
outs() << "rc ";
if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
outs() << "FP_RND_NEAR ";
else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
outs() << "FP_RND_DOWN ";
else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
outs() << "FP_RND_UP ";
else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
outs() << "FP_CHOP ";
outs() << "\n";
outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
outs() << " denorm " << fpu.fpu_fsw.denorm;
outs() << " zdiv " << fpu.fpu_fsw.zdiv;
outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
outs() << " undfl " << fpu.fpu_fsw.undfl;
outs() << " precis " << fpu.fpu_fsw.precis;
outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
outs() << " c0 " << fpu.fpu_fsw.c0;
outs() << " c1 " << fpu.fpu_fsw.c1;
outs() << " c2 " << fpu.fpu_fsw.c2;
outs() << " tos " << fpu.fpu_fsw.tos;
outs() << " c3 " << fpu.fpu_fsw.c3;
outs() << " busy " << fpu.fpu_fsw.busy << "\n";
outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
outs() << "\n";
outs() << "\t fpu_stmm0:\n";
Print_mmst_reg(fpu.fpu_stmm0);
outs() << "\t fpu_stmm1:\n";
Print_mmst_reg(fpu.fpu_stmm1);
outs() << "\t fpu_stmm2:\n";
Print_mmst_reg(fpu.fpu_stmm2);
outs() << "\t fpu_stmm3:\n";
Print_mmst_reg(fpu.fpu_stmm3);
outs() << "\t fpu_stmm4:\n";
Print_mmst_reg(fpu.fpu_stmm4);
outs() << "\t fpu_stmm5:\n";
Print_mmst_reg(fpu.fpu_stmm5);
outs() << "\t fpu_stmm6:\n";
Print_mmst_reg(fpu.fpu_stmm6);
outs() << "\t fpu_stmm7:\n";
Print_mmst_reg(fpu.fpu_stmm7);
outs() << "\t fpu_xmm0:\n";
Print_xmm_reg(fpu.fpu_xmm0);
outs() << "\t fpu_xmm1:\n";
Print_xmm_reg(fpu.fpu_xmm1);
outs() << "\t fpu_xmm2:\n";
Print_xmm_reg(fpu.fpu_xmm2);
outs() << "\t fpu_xmm3:\n";
Print_xmm_reg(fpu.fpu_xmm3);
outs() << "\t fpu_xmm4:\n";
Print_xmm_reg(fpu.fpu_xmm4);
outs() << "\t fpu_xmm5:\n";
Print_xmm_reg(fpu.fpu_xmm5);
outs() << "\t fpu_xmm6:\n";
Print_xmm_reg(fpu.fpu_xmm6);
outs() << "\t fpu_xmm7:\n";
Print_xmm_reg(fpu.fpu_xmm7);
outs() << "\t fpu_xmm8:\n";
Print_xmm_reg(fpu.fpu_xmm8);
outs() << "\t fpu_xmm9:\n";
Print_xmm_reg(fpu.fpu_xmm9);
outs() << "\t fpu_xmm10:\n";
Print_xmm_reg(fpu.fpu_xmm10);
outs() << "\t fpu_xmm11:\n";
Print_xmm_reg(fpu.fpu_xmm11);
outs() << "\t fpu_xmm12:\n";
Print_xmm_reg(fpu.fpu_xmm12);
outs() << "\t fpu_xmm13:\n";
Print_xmm_reg(fpu.fpu_xmm13);
outs() << "\t fpu_xmm14:\n";
Print_xmm_reg(fpu.fpu_xmm14);
outs() << "\t fpu_xmm15:\n";
Print_xmm_reg(fpu.fpu_xmm15);
outs() << "\t fpu_rsrv4:\n";
for (uint32_t f = 0; f < 6; f++) {
outs() << "\t ";
for (uint32_t g = 0; g < 16; g++)
outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
outs() << "\n";
}
outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
outs() << "\n";
}
static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
outs() << " err " << format("0x%08" PRIx32, exc64.err);
outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
}
static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
bool isLittleEndian, uint32_t cputype) {
if (t.cmd == MachO::LC_THREAD)
outs() << " cmd LC_THREAD\n";
else if (t.cmd == MachO::LC_UNIXTHREAD)
outs() << " cmd LC_UNIXTHREAD\n";
else
outs() << " cmd " << t.cmd << " (unknown)\n";
outs() << " cmdsize " << t.cmdsize;
if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
outs() << " Incorrect size\n";
else
outs() << "\n";
const char *begin = Ptr + sizeof(struct MachO::thread_command);
const char *end = Ptr + t.cmdsize;
uint32_t flavor, count, left;
if (cputype == MachO::CPU_TYPE_X86_64) {
while (begin < end) {
if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
memcpy((char *)&flavor, begin, sizeof(uint32_t));
begin += sizeof(uint32_t);
} else {
flavor = 0;
begin = end;
}
if (isLittleEndian != sys::IsLittleEndianHost)
sys::swapByteOrder(flavor);
if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
memcpy((char *)&count, begin, sizeof(uint32_t));
begin += sizeof(uint32_t);
} else {
count = 0;
begin = end;
}
if (isLittleEndian != sys::IsLittleEndianHost)
sys::swapByteOrder(count);
if (flavor == MachO::x86_THREAD_STATE64) {
outs() << " flavor x86_THREAD_STATE64\n";
if (count == MachO::x86_THREAD_STATE64_COUNT)
outs() << " count x86_THREAD_STATE64_COUNT\n";
else
outs() << " count " << count
<< " (not x86_THREAD_STATE64_COUNT)\n";
MachO::x86_thread_state64_t cpu64;
left = end - begin;
if (left >= sizeof(MachO::x86_thread_state64_t)) {
memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
begin += sizeof(MachO::x86_thread_state64_t);
} else {
memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
memcpy(&cpu64, begin, left);
begin += left;
}
if (isLittleEndian != sys::IsLittleEndianHost)
swapStruct(cpu64);
Print_x86_thread_state64_t(cpu64);
} else if (flavor == MachO::x86_THREAD_STATE) {
outs() << " flavor x86_THREAD_STATE\n";
if (count == MachO::x86_THREAD_STATE_COUNT)
outs() << " count x86_THREAD_STATE_COUNT\n";
else
outs() << " count " << count
<< " (not x86_THREAD_STATE_COUNT)\n";
struct MachO::x86_thread_state_t ts;
left = end - begin;
if (left >= sizeof(MachO::x86_thread_state_t)) {
memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
begin += sizeof(MachO::x86_thread_state_t);
} else {
memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
memcpy(&ts, begin, left);
begin += left;
}
if (isLittleEndian != sys::IsLittleEndianHost)
swapStruct(ts);
if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
else
outs() << "tsh.count " << ts.tsh.count
<< " (not x86_THREAD_STATE64_COUNT\n";
Print_x86_thread_state64_t(ts.uts.ts64);
} else {
outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
<< ts.tsh.count << "\n";
}
} else if (flavor == MachO::x86_FLOAT_STATE) {
outs() << " flavor x86_FLOAT_STATE\n";
if (count == MachO::x86_FLOAT_STATE_COUNT)
outs() << " count x86_FLOAT_STATE_COUNT\n";
else
outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
struct MachO::x86_float_state_t fs;
left = end - begin;
if (left >= sizeof(MachO::x86_float_state_t)) {
memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
begin += sizeof(MachO::x86_float_state_t);
} else {
memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
memcpy(&fs, begin, left);
begin += left;
}
if (isLittleEndian != sys::IsLittleEndianHost)
swapStruct(fs);
if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
else
outs() << "fsh.count " << fs.fsh.count
<< " (not x86_FLOAT_STATE64_COUNT\n";
Print_x86_float_state_t(fs.ufs.fs64);
} else {
outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
<< fs.fsh.count << "\n";
}
} else if (flavor == MachO::x86_EXCEPTION_STATE) {
outs() << " flavor x86_EXCEPTION_STATE\n";
if (count == MachO::x86_EXCEPTION_STATE_COUNT)
outs() << " count x86_EXCEPTION_STATE_COUNT\n";
else
outs() << " count " << count
<< " (not x86_EXCEPTION_STATE_COUNT)\n";
struct MachO::x86_exception_state_t es;
left = end - begin;
if (left >= sizeof(MachO::x86_exception_state_t)) {
memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
begin += sizeof(MachO::x86_exception_state_t);
} else {
memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
memcpy(&es, begin, left);
begin += left;
}
if (isLittleEndian != sys::IsLittleEndianHost)
swapStruct(es);
if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
else
outs() << "\t esh.count " << es.esh.count
<< " (not x86_EXCEPTION_STATE64_COUNT\n";
Print_x86_exception_state_t(es.ues.es64);
} else {
outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
<< es.esh.count << "\n";
}
} else {
outs() << " flavor " << flavor << " (unknown)\n";
outs() << " count " << count << "\n";
outs() << " state (unknown)\n";
begin += count * sizeof(uint32_t);
}
}
} else {
while (begin < end) {
if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
memcpy((char *)&flavor, begin, sizeof(uint32_t));
begin += sizeof(uint32_t);
} else {
flavor = 0;
begin = end;
}
if (isLittleEndian != sys::IsLittleEndianHost)
sys::swapByteOrder(flavor);
if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
memcpy((char *)&count, begin, sizeof(uint32_t));
begin += sizeof(uint32_t);
} else {
count = 0;
begin = end;
}
if (isLittleEndian != sys::IsLittleEndianHost)
sys::swapByteOrder(count);
outs() << " flavor " << flavor << "\n";
outs() << " count " << count << "\n";
outs() << " state (Unknown cputype/cpusubtype)\n";
begin += count * sizeof(uint32_t);
}
}
}
static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
if (dl.cmd == MachO::LC_ID_DYLIB)
outs() << " cmd LC_ID_DYLIB\n";
else if (dl.cmd == MachO::LC_LOAD_DYLIB)
outs() << " cmd LC_LOAD_DYLIB\n";
else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
outs() << " cmd LC_REEXPORT_DYLIB\n";
else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
else
outs() << " cmd " << dl.cmd << " (unknown)\n";
outs() << " cmdsize " << dl.cmdsize;
if (dl.cmdsize < sizeof(struct MachO::dylib_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
if (dl.dylib.name < dl.cmdsize) {
const char *P = (const char *)(Ptr) + dl.dylib.name;
outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
} else {
outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
}
outs() << " time stamp " << dl.dylib.timestamp << " ";
time_t t = dl.dylib.timestamp;
outs() << ctime(&t);
outs() << " current version ";
if (dl.dylib.current_version == 0xffffffff)
outs() << "n/a\n";
else
outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
<< ((dl.dylib.current_version >> 8) & 0xff) << "."
<< (dl.dylib.current_version & 0xff) << "\n";
outs() << "compatibility version ";
if (dl.dylib.compatibility_version == 0xffffffff)
outs() << "n/a\n";
else
outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
<< ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
<< (dl.dylib.compatibility_version & 0xff) << "\n";
}
static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
uint32_t object_size) {
if (ld.cmd == MachO::LC_CODE_SIGNATURE)
outs() << " cmd LC_FUNCTION_STARTS\n";
else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
outs() << " cmd LC_FUNCTION_STARTS\n";
else if (ld.cmd == MachO::LC_DATA_IN_CODE)
outs() << " cmd LC_DATA_IN_CODE\n";
else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
else
outs() << " cmd " << ld.cmd << " (?)\n";
outs() << " cmdsize " << ld.cmdsize;
if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
outs() << " Incorrect size\n";
else
outs() << "\n";
outs() << " dataoff " << ld.dataoff;
if (ld.dataoff > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
outs() << " datasize " << ld.datasize;
uint64_t big_size = ld.dataoff;
big_size += ld.datasize;
if (big_size > object_size)
outs() << " (past end of file)\n";
else
outs() << "\n";
}
static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
uint32_t cputype, bool verbose) {
StringRef Buf = Obj->getData();
unsigned Index = 0;
for (const auto &Command : Obj->load_commands()) {
outs() << "Load command " << Index++ << "\n";
if (Command.C.cmd == MachO::LC_SEGMENT) {
MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
const char *sg_segname = SLC.segname;
PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
verbose);
for (unsigned j = 0; j < SLC.nsects; j++) {
MachO::section S = Obj->getSection(Command, j);
PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
}
} else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
const char *sg_segname = SLC_64.segname;
PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
for (unsigned j = 0; j < SLC_64.nsects; j++) {
MachO::section_64 S_64 = Obj->getSection64(Command, j);
PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
sg_segname, filetype, Buf.size(), verbose);
}
} else if (Command.C.cmd == MachO::LC_SYMTAB) {
MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
} else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
Obj->is64Bit());
} else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
} else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
Command.C.cmd == MachO::LC_ID_DYLINKER ||
Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
PrintDyldLoadCommand(Dyld, Command.Ptr);
} else if (Command.C.cmd == MachO::LC_UUID) {
MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
PrintUuidLoadCommand(Uuid);
} else if (Command.C.cmd == MachO::LC_RPATH) {
MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
PrintRpathLoadCommand(Rpath, Command.Ptr);
} else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
PrintVersionMinLoadCommand(Vd);
} else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
PrintSourceVersionCommand(Sd);
} else if (Command.C.cmd == MachO::LC_MAIN) {
MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
PrintEntryPointCommand(Ep);
} else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
MachO::encryption_info_command Ei =
Obj->getEncryptionInfoCommand(Command);
PrintEncryptionInfoCommand(Ei, Buf.size());
} else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
MachO::encryption_info_command_64 Ei =
Obj->getEncryptionInfoCommand64(Command);
PrintEncryptionInfoCommand64(Ei, Buf.size());
} else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
MachO::linker_option_command Lo =
Obj->getLinkerOptionLoadCommand(Command);
PrintLinkerOptionCommand(Lo, Command.Ptr);
} else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
PrintSubFrameworkCommand(Sf, Command.Ptr);
} else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
PrintSubUmbrellaCommand(Sf, Command.Ptr);
} else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
PrintSubLibraryCommand(Sl, Command.Ptr);
} else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
PrintSubClientCommand(Sc, Command.Ptr);
} else if (Command.C.cmd == MachO::LC_ROUTINES) {
MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
PrintRoutinesCommand(Rc);
} else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
PrintRoutinesCommand64(Rc);
} else if (Command.C.cmd == MachO::LC_THREAD ||
Command.C.cmd == MachO::LC_UNIXTHREAD) {
MachO::thread_command Tc = Obj->getThreadCommand(Command);
PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
} else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
Command.C.cmd == MachO::LC_ID_DYLIB ||
Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
PrintDylibCommand(Dl, Command.Ptr);
} else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
Command.C.cmd == MachO::LC_DATA_IN_CODE ||
Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
MachO::linkedit_data_command Ld =
Obj->getLinkeditDataLoadCommand(Command);
PrintLinkEditDataCommand(Ld, Buf.size());
} else {
outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
<< ")\n";
outs() << " cmdsize " << Command.C.cmdsize << "\n";
// TODO: get and print the raw bytes of the load command.
}
// TODO: print all the other kinds of load commands.
}
}
static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
if (Obj->is64Bit()) {
MachO::mach_header_64 H_64;
H_64 = Obj->getHeader64();
PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
} else {
MachO::mach_header H;
H = Obj->getHeader();
PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
H.sizeofcmds, H.flags, verbose);
}
}
void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
PrintMachHeader(file, !NonVerbose);
}
void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
uint32_t filetype = 0;
uint32_t cputype = 0;
if (file->is64Bit()) {
MachO::mach_header_64 H_64;
H_64 = file->getHeader64();
filetype = H_64.filetype;
cputype = H_64.cputype;
} else {
MachO::mach_header H;
H = file->getHeader();
filetype = H.filetype;
cputype = H.cputype;
}
PrintLoadCommands(file, filetype, cputype, !NonVerbose);
}
//===----------------------------------------------------------------------===//
// export trie dumping
//===----------------------------------------------------------------------===//
void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
uint64_t Flags = Entry.flags();
bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
if (ReExport)
outs() << "[re-export] ";
else
outs() << format("0x%08llX ",
Entry.address()); // FIXME:add in base address
outs() << Entry.name();
if (WeakDef || ThreadLocal || Resolver || Abs) {
bool NeedsComma = false;
outs() << " [";
if (WeakDef) {
outs() << "weak_def";
NeedsComma = true;
}
if (ThreadLocal) {
if (NeedsComma)
outs() << ", ";
outs() << "per-thread";
NeedsComma = true;
}
if (Abs) {
if (NeedsComma)
outs() << ", ";
outs() << "absolute";
NeedsComma = true;
}
if (Resolver) {
if (NeedsComma)
outs() << ", ";
outs() << format("resolver=0x%08llX", Entry.other());
NeedsComma = true;
}
outs() << "]";
}
if (ReExport) {
StringRef DylibName = "unknown";
int Ordinal = Entry.other() - 1;
Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
if (Entry.otherName().empty())
outs() << " (from " << DylibName << ")";
else
outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
}
outs() << "\n";
}
}
//===----------------------------------------------------------------------===//
// rebase table dumping
//===----------------------------------------------------------------------===//
namespace {
class SegInfo {
public:
SegInfo(const object::MachOObjectFile *Obj);
StringRef segmentName(uint32_t SegIndex);
StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
private:
struct SectionInfo {
uint64_t Address;
uint64_t Size;
StringRef SectionName;
StringRef SegmentName;
uint64_t OffsetInSegment;
uint64_t SegmentStartAddress;
uint32_t SegmentIndex;
};
const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
SmallVector<SectionInfo, 32> Sections;
};
}
SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
// Build table of sections so segIndex/offset pairs can be translated.
uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
StringRef CurSegName;
uint64_t CurSegAddress;
for (const SectionRef &Section : Obj->sections()) {
SectionInfo Info;
error(Section.getName(Info.SectionName));
Info.Address = Section.getAddress();
Info.Size = Section.getSize();
Info.SegmentName =
Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
if (!Info.SegmentName.equals(CurSegName)) {
++CurSegIndex;
CurSegName = Info.SegmentName;
CurSegAddress = Info.Address;
}
Info.SegmentIndex = CurSegIndex - 1;
Info.OffsetInSegment = Info.Address - CurSegAddress;
Info.SegmentStartAddress = CurSegAddress;
Sections.push_back(Info);
}
}
StringRef SegInfo::segmentName(uint32_t SegIndex) {
for (const SectionInfo &SI : Sections) {
if (SI.SegmentIndex == SegIndex)
return SI.SegmentName;
}
llvm_unreachable("invalid segIndex");
}
bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
uint64_t OffsetInSeg) {
for (const SectionInfo &SI : Sections) {
if (SI.SegmentIndex != SegIndex)
continue;
if (SI.OffsetInSegment > OffsetInSeg)
continue;
if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
continue;
return true;
}
return false;
}
const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
uint64_t OffsetInSeg) {
for (const SectionInfo &SI : Sections) {
if (SI.SegmentIndex != SegIndex)
continue;
if (SI.OffsetInSegment > OffsetInSeg)
continue;
if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
continue;
return SI;
}
llvm_unreachable("segIndex and offset not in any section");
}
StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
return findSection(SegIndex, OffsetInSeg).SectionName;
}
uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
return SI.SegmentStartAddress + OffsetInSeg;
}
void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
// Build table of sections so names can used in final output.
SegInfo sectionTable(Obj);
outs() << "segment section address type\n";
for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
uint32_t SegIndex = Entry.segmentIndex();
uint64_t OffsetInSeg = Entry.segmentOffset();
StringRef SegmentName = sectionTable.segmentName(SegIndex);
StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
// Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
SegmentName.str().c_str(), SectionName.str().c_str(),
Address, Entry.typeName().str().c_str());
}
}
static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
StringRef DylibName;
switch (Ordinal) {
case MachO::BIND_SPECIAL_DYLIB_SELF:
return "this-image";
case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
return "main-executable";
case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
return "flat-namespace";
default:
if (Ordinal > 0) {
std::error_code EC =
Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
if (EC)
return "<<bad library ordinal>>";
return DylibName;
}
}
return "<<unknown special ordinal>>";
}
//===----------------------------------------------------------------------===//
// bind table dumping
//===----------------------------------------------------------------------===//
void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
// Build table of sections so names can used in final output.
SegInfo sectionTable(Obj);
outs() << "segment section address type "
"addend dylib symbol\n";
for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
uint32_t SegIndex = Entry.segmentIndex();
uint64_t OffsetInSeg = Entry.segmentOffset();
StringRef SegmentName = sectionTable.segmentName(SegIndex);
StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
// Table lines look like:
// __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
StringRef Attr;
if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Attr = " (weak_import)";
outs() << left_justify(SegmentName, 8) << " "
<< left_justify(SectionName, 18) << " "
<< format_hex(Address, 10, true) << " "
<< left_justify(Entry.typeName(), 8) << " "
<< format_decimal(Entry.addend(), 8) << " "
<< left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
<< Entry.symbolName() << Attr << "\n";
}
}
//===----------------------------------------------------------------------===//
// lazy bind table dumping
//===----------------------------------------------------------------------===//
void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
// Build table of sections so names can used in final output.
SegInfo sectionTable(Obj);
outs() << "segment section address "
"dylib symbol\n";
for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
uint32_t SegIndex = Entry.segmentIndex();
uint64_t OffsetInSeg = Entry.segmentOffset();
StringRef SegmentName = sectionTable.segmentName(SegIndex);
StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
// Table lines look like:
// __DATA __got 0x00012010 libSystem ___stack_chk_guard
outs() << left_justify(SegmentName, 8) << " "
<< left_justify(SectionName, 18) << " "
<< format_hex(Address, 10, true) << " "
<< left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
<< Entry.symbolName() << "\n";
}
}
//===----------------------------------------------------------------------===//
// weak bind table dumping
//===----------------------------------------------------------------------===//
void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
// Build table of sections so names can used in final output.
SegInfo sectionTable(Obj);
outs() << "segment section address "
"type addend symbol\n";
for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
// Strong symbols don't have a location to update.
if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
outs() << " strong "
<< Entry.symbolName() << "\n";
continue;
}
uint32_t SegIndex = Entry.segmentIndex();
uint64_t OffsetInSeg = Entry.segmentOffset();
StringRef SegmentName = sectionTable.segmentName(SegIndex);
StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
// Table lines look like:
// __DATA __data 0x00001000 pointer 0 _foo
outs() << left_justify(SegmentName, 8) << " "
<< left_justify(SectionName, 18) << " "
<< format_hex(Address, 10, true) << " "
<< left_justify(Entry.typeName(), 8) << " "
<< format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
<< "\n";
}
}
// get_dyld_bind_info_symbolname() is used for disassembly and passed an
// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
// information for that address. If the address is found its binding symbol
// name is returned. If not nullptr is returned.
static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
struct DisassembleInfo *info) {
if (info->bindtable == nullptr) {
info->bindtable = new (BindTable);
SegInfo sectionTable(info->O);
for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
uint32_t SegIndex = Entry.segmentIndex();
uint64_t OffsetInSeg = Entry.segmentOffset();
if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
continue;
uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
const char *SymbolName = nullptr;
StringRef name = Entry.symbolName();
if (!name.empty())
SymbolName = name.data();
info->bindtable->push_back(std::make_pair(Address, SymbolName));
}
}
for (bind_table_iterator BI = info->bindtable->begin(),
BE = info->bindtable->end();
BI != BE; ++BI) {
uint64_t Address = BI->first;
if (ReferenceValue == Address) {
const char *SymbolName = BI->second;
return SymbolName;
}
}
return nullptr;
}
|
silverneko/HWs
|
compiler-hw-2-master/hw3/llvm-3.8.0.src/tools/llvm-objdump/MachODump.cpp
|
C++
|
mit
| 333,100
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace spec\Sylius\Bundle\PaymentBundle\Form\Type\EventListener;
use PhpSpec\ObjectBehavior;
use Sylius\Component\Payment\Calculator\FeeCalculatorInterface;
use Sylius\Component\Payment\Model\PaymentMethodInterface;
use Sylius\Component\Registry\ServiceRegistryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
/**
* @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
*/
class BuildPaymentMethodFeeCalculatorFormSubscriberSpec extends ObjectBehavior
{
function let(ServiceRegistryInterface $feeCalculatorRegistry, FormFactoryInterface $factory)
{
$this->beConstructedWith($feeCalculatorRegistry, $factory);
}
function it_is_initializable()
{
$this->shouldHaveType('Sylius\Bundle\PaymentBundle\Form\Type\EventListener\BuildPaymentMethodFeeCalculatorFormSubscriber');
}
function it_implements_event_subscriber_interface()
{
$this->shouldImplement(EventSubscriberInterface::class);
}
function it_pre_sets_data(
$factory,
$feeCalculatorRegistry,
FeeCalculatorInterface $feeCalculator,
FormEvent $event,
FormInterface $configurationForm,
FormInterface $form,
PaymentMethodInterface $paymentMethod
) {
$event->getData()->willReturn($paymentMethod)->shouldBeCalled();
$event->getForm()->willReturn($form)->shouldBeCalled();
$paymentMethod->getFeeCalculator()->willReturn('test');
$paymentMethod->getFeeCalculatorConfiguration()->willReturn(array('amount' => 100));
$feeCalculatorRegistry->get('test')->willReturn($feeCalculator)->shouldBeCalled();
$feeCalculator->getType()->willReturn('test');
$factory
->createNamed(
'feeCalculatorConfiguration',
'sylius_fee_calculator_test',
array('amount' => 100),
array('auto_initialize' => false)
)
->willReturn($configurationForm)
->shouldBeCalled()
;
$form->add($configurationForm)->shouldBeCalled();
$this->preSetData($event);
}
function it_does_not_process_if_event_has_no_data_while_pre_set(FormEvent $event)
{
$event->getData()->willReturn(null)->shouldBeCalled();
$this->preSetData($event)->shouldReturn(null);
}
function it_throws_exception_if_event_data_is_not_payment_method_object_while_pre_set(FormEvent $event)
{
$event->getData()->willReturn('badObject')->shouldBeCalled();
$this->shouldThrow(new UnexpectedTypeException('badObject', PaymentMethodInterface::class))->during('preSetData', array($event));
}
function it_is_triggered_pre_bind(
$factory,
$feeCalculatorRegistry,
FeeCalculatorInterface $feeCalculator,
FormEvent $event,
FormInterface $configurationForm,
FormInterface $form,
PaymentMethodInterface $paymentMethod
) {
$event->getData()->willReturn(array('feeCalculator' => 'test'))->shouldBeCalled();
$event->getForm()->willReturn($form)->shouldBeCalled();
$paymentMethod->getFeeCalculator()->willReturn('test');
$paymentMethod->getFeeCalculatorConfiguration()->willReturn(array());
$feeCalculatorRegistry->get('test')->willReturn($feeCalculator)->shouldBeCalled();
$feeCalculator->getType()->willReturn('test');
$factory
->createNamed(
'feeCalculatorConfiguration',
'sylius_fee_calculator_test',
array(),
array('auto_initialize' => false)
)
->willReturn($configurationForm)
->shouldBeCalled()
;
$form->add($configurationForm)->shouldBeCalled();
$this->preBind($event);
}
function it_does_not_process_if_event_data_is_empty_or_has_no_fee_calculator_field_while_pre_bind(FormEvent $event)
{
$event->getData()->willReturn(array())->shouldBeCalled();
$this->preBind($event)->shouldReturn(null);
$event->getData()->willReturn(array('badKeys' => ''))->shouldBeCalled();
$this->preBind($event)->shouldReturn(null);
}
}
|
pfwd/Sylius
|
src/Sylius/Bundle/PaymentBundle/spec/Form/Type/EventListener/BuildPaymentMethodFeeCalculatorFormSubscriberSpec.php
|
PHP
|
mit
| 4,619
|
var S_ITER$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol.iterator||'@@iterator';var S_MARK$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol["__setObjectSetter__"];function ITER$0(v,f){if(v){if(Array.isArray(v))return f?v.slice():v;var i,r;if(S_MARK$0)S_MARK$0(v);if(typeof v==='object'&&typeof (f=v[S_ITER$0])==='function'){i=f.call(v);r=[];}else if((v+'')==='[object Generator]'){i=v;r=[];};if(S_MARK$0)S_MARK$0(void 0);if(r) {while((f=i['next']()),f['done']!==true)r.push(f['value']);return r;}}throw new Error(v+' is not iterable')};var SLICE$0 = Array.prototype.slice;var $D$0;
{
var test11 = [1, 2, 3];
var test12 = SLICE$0.call(test11, 0);
test11.push(4);
console.log(test11.join("|") === "1|2|3|4", test12.join("|") === "1|2|3");
}
{
var test21 = SLICE$0.call(([1, 2, 3]), 0);
console.log(test21.join("|") === "1|2|3");
}
{
var test31;
test31 = SLICE$0.call(($D$0 = [1, 2, 3]), 0), $D$0;
console.log(test31.join("|") === "1|2|3");
{
var test321, test322, test323;
test322 = (test321 = SLICE$0.call(($D$0 = test323 = [1, 2, 3]), 0), $D$0);
test322.push(4);
console.log(test31.join("|") === "1|2|3", test322.join("|") === "1|2|3|4", test322 === test323);
}
}
{
var test41 = [1, 2, 3];
var test42;
test42 = SLICE$0.call(test41, 0), test41;
test41.push(4);
console.log(test41.join("|") === "1|2|3|4", test42.join("|") === "1|2|3");
{
var test43 = [1, 2, 3];
var test44 = ITER$0(test43 );
console.log(test44.join("|") === "1|2|3");
}
}
{
var test51 = [0, 1, 2, 3];
var test52, test53;
test53 = test51[0], test52 = SLICE$0.call(test51, 1), test51;
test51.shift();
test51.push(4);
console.log(test51.join("|") === "1|2|3|4", test52.join("|") === "1|2|3");
}
{
var test61 = [3, 2, 1], test63 = test61;
var test62 = SLICE$0.call(([test61.reverse()])[0], 0);
test61.push(4);
console.log(test61.join("|") === "1|2|3|4", test62.join("|") === "1|2|3", test63 === test61);
}
{
var test71 = [3, 2, 1];
var test72 = SLICE$0.call(([test71.reverse()])[0], 0);
console.log(test72.join("|") === "1|2|3");
{
test72 = SLICE$0.call(($D$0 = [test71.reverse()])[0], 0), $D$0;
console.log(test72.join("|") === "3|2|1");
;$D$0 = void 0}
}
|
arve0/es6-transpiler
|
tests/es6-destructuring5-out.js
|
JavaScript
|
mit
| 2,180
|
class User < ActiveRecord::Base
has_secure_password validations: false
# Scopes
#
scope :hosted, -> { where(hosted: true) }
scope :remote, -> { where(hosted: false) }
# Validations
#
validates :domain, :url,
presence: true,
uniqueness: true
validates :password,
presence: { on: :create },
confirmation: { allow_blank: true },
if: :hosted
validates :password_digest,
presence: true,
if: :hosted
before_validation do
self.display_name ||= domain
self.url ||= domain.try(:with_http)
end
# Users are either hosted or remote.
#
def remote?
!hosted?
end
# Users can have posts. Which is kind of convenient considering we're dealing
# with a distributed social _blogging_ platform.
#
concerning :Posts do
included do
has_many :posts,
foreign_key: 'domain',
primary_key: 'domain'
end
end
# Users also have timelines, which are mostly just listings of posts that
# are filled when the user is being pinged, or someone the user is subscribing
# to publishes a new post.
#
concerning :Timelines do
included do
has_many :timeline_entries,
dependent: :destroy
# `timeline_posts` returns all posts contained in the user's
# timeline, no matter its status (from friend/other, hidden/visible etc.)
# This can be used to quickly check if the user has "seen" a specific post,
# eg. to determine if another post is in reply to something the user has seen.
#
has_many :timeline_posts,
through: :timeline_entries,
source: :post
end
def add_to_timeline(post)
from_friend = (post.user == self) || friends.where(domain: post.domain).any?
TimelineEntry.transaction do
timeline_entries
.where(post_id: post.id)
.first_or_create!(from_friend: from_friend)
end
end
end
# Awww, friendship. Isn't it lovely? #pants defines a "friendship" as one user
# subscribing to another user's updates, which is different from what you may
# know from real life, but works exceedingly well in a computer context.
#
# In non-mutual friendships, if user A has user B in their friends list, A is
# a "follower" of B.
#
concerning :Friendships do
included do
has_many :friendships,
dependent: :destroy
# Please note that the following association only lists followings that are
# local to your #pants instance.
#
has_many :followings,
class_name: 'Friendship',
foreign_key: 'friend_id'
has_many :friends,
through: :friendships,
source: :friend
has_many :followers,
through: :followings,
source: :user
end
def add_friend(friend)
# Upsert friendship
friendship = friendships.where(friend_id: friend.id).first_or_initialize
if friendship.new_record?
friendship.save!
else
friendship.touch
end
if hosted?
# Make existing timeline posts visible
timeline_entries.joins(:post).where(posts: { domain: friend.domain }).update_all(from_friend: true)
end
end
# Returns a list of locally known users that have posts waiting
# in this user's incoming timeline.
#
def incoming_followers
User.where(domain: timeline_entries.from_others.includes(:post).pluck('distinct domain'))
end
end
# Send ONE ping.
#
concerning :Pings do
included do
has_many :pings,
dependent: :nullify
end
end
concerning :WebLinks do
def web_links_text
web_links.join("\n")
end
def web_links_text=(text)
self.web_links = text.split.compact.map(&:with_http)
end
end
concerning :Images do
included do
dragonfly_accessor :image
dragonfly_accessor :flair
end
def external_image_url
URI.join(url, '/user.jpg').to_s
end
def external_flair_url
URI.join(url, '/user-flair.jpg').to_s
end
def local_image
hosted? ? image : Dragonfly.app.fetch_url(external_image_url)
end
def local_flair
hosted? ? flair : Dragonfly.app.fetch_url(external_flair_url)
end
def local_thumbnail
local_image.try(:thumb, '300x300#')
end
def local_cropped_flair
local_flair.try(:thumb, '800x250#')
end
end
class << self
def [](url)
host = URI.parse(url.with_http).host
find_by(domain: host)
end
end
end
|
hmans/pants
|
app/models/user.rb
|
Ruby
|
mit
| 4,487
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper.QueryableExtensions;
using GRA.Domain.Model;
using GRA.Domain.Model.Filters;
using GRA.Domain.Repository;
using GRA.Domain.Repository.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace GRA.Data.Repository
{
public class ChallengeGroupRepository
: AuditingRepository<Model.ChallengeGroup, Domain.Model.ChallengeGroup>,
IChallengeGroupRepository
{
public ChallengeGroupRepository(ServiceFacade.Repository repositoryFacade,
ILogger<ChallengeGroupRepository> logger) : base(repositoryFacade, logger)
{
}
public override async Task<ChallengeGroup> GetByIdAsync(int id)
{
return await DbSet
.AsNoTracking()
.Where(_ => _.Id == id)
.ProjectTo<ChallengeGroup>()
.SingleOrDefaultAsync();
}
public async Task<ChallengeGroup> GetActiveByIdAsync(int id)
{
return await DbSet
.AsNoTracking()
.Where(_ => _.Id == id
&& _.ChallengeGroupChallenges.Any(c => c.Challenge.IsActive == true
&& c.Challenge.IsDeleted == false))
.ProjectTo<ChallengeGroup>()
.SingleOrDefaultAsync();
}
public async Task<ChallengeGroup> GetActiveByStubAsync(int siteId, string stub)
{
return await DbSet
.AsNoTracking()
.Where(_ => _.SiteId == siteId && _.Stub == stub
&& _.ChallengeGroupChallenges.Any(c => c.Challenge.IsActive == true
&& c.Challenge.IsDeleted == false))
.ProjectTo<ChallengeGroup>()
.SingleOrDefaultAsync();
}
public async Task<List<ChallengeGroup>> GetByChallengeId(int siteId, int challengeId)
{
return await DbSet
.AsNoTracking()
.Include(_ => _.ChallengeGroupChallenges)
.Where(_ => _.SiteId == siteId
&& _.ChallengeGroupChallenges.Select(c => c.ChallengeId).Contains(challengeId))
.ProjectTo<ChallengeGroup>()
.ToListAsync();
}
public async Task<int> CountAsync(ChallengeGroupFilter filter)
{
return await ApplyFilters(filter)
.CountAsync();
}
public async Task<IEnumerable<ChallengeGroup>> PageAsync(ChallengeGroupFilter filter)
{
return await ApplyFilters(filter)
.OrderBy(_ => _.Name)
.ApplyPagination(filter)
.ProjectTo<ChallengeGroup>()
.ToListAsync();
}
public IQueryable<Model.ChallengeGroup> ApplyFilters(ChallengeGroupFilter filter)
{
var challengeGroupList = DbSet
.AsNoTracking()
.Where(_ => _.SiteId == filter.SiteId);
if (filter.ChallengeGroupIds?.Count > 0)
{
challengeGroupList = challengeGroupList
.Where(_ => filter.ChallengeGroupIds.Contains(_.Id) == false);
}
if (filter.ActiveGroups.HasValue)
{
var inactiveChallengeIds = _context.Challenges
.AsNoTracking()
.Where(_ => _.IsActive == false || _.IsDeleted == true)
.Select(_ => _.Id);
challengeGroupList = challengeGroupList
.Where(_ =>
_.ChallengeGroupChallenges
.Where(c => inactiveChallengeIds.Contains(c.ChallengeId) == false)
.Select(c => c.ChallengeGroupId)
.Contains(_.Id) == filter.ActiveGroups.Value);
}
if (!string.IsNullOrWhiteSpace(filter.Search))
{
challengeGroupList = challengeGroupList.Where(_ => _.Name.Contains(filter.Search));
}
return challengeGroupList;
}
public async Task<ChallengeGroup> AddSaveAsync(int userId,
ChallengeGroup challengeGroup, IEnumerable<int> challengeIds)
{
var newChallengeGroup = await base.AddSaveAsync(userId, challengeGroup);
if (challengeIds.Count() > 0)
{
var time = _dateTimeProvider.Now;
var challengeGroupChallengeList = new List<Model.ChallengeGroupChallenge>();
foreach (var challengeId in challengeIds)
{
challengeGroupChallengeList.Add(new Model.ChallengeGroupChallenge()
{
ChallengeGroupId = newChallengeGroup.Id,
ChallengeId = challengeId,
CreatedAt = time,
CreatedBy = userId
});
}
await _context.ChallengeGroupChallenges.AddRangeAsync(challengeGroupChallengeList);
await _context.SaveChangesAsync();
}
return newChallengeGroup;
}
public async Task<ChallengeGroup> UpdateSaveAsync(int userId, ChallengeGroup challengeGroup,
IEnumerable<int> challengesToAdd, IEnumerable<int> challengesToRemove)
{
await base.UpdateAsync(userId, challengeGroup);
if (challengesToAdd?.Count() > 0)
{
var time = _dateTimeProvider.Now;
var challengeGroupChallengeList = new List<Model.ChallengeGroupChallenge>();
foreach (var challengeId in challengesToAdd)
{
challengeGroupChallengeList.Add(new Model.ChallengeGroupChallenge()
{
ChallengeGroupId = challengeGroup.Id,
ChallengeId = challengeId,
CreatedAt = time,
CreatedBy = userId
});
}
await _context.ChallengeGroupChallenges.AddRangeAsync(challengeGroupChallengeList);
}
if (challengesToRemove?.Count() > 0)
{
var removeList = _context.ChallengeGroupChallenges
.Where(_ => _.ChallengeGroupId == challengeGroup.Id
&& challengesToRemove.Contains(_.ChallengeId));
_context.ChallengeGroupChallenges.RemoveRange(removeList);
}
await _context.SaveChangesAsync();
return challengeGroup;
}
public override async Task RemoveSaveAsync(int userId, int challengeGroupId)
{
var challengeGroupChallenges = await _context.ChallengeGroupChallenges
.Where(_ => _.ChallengeGroupId == challengeGroupId)
.ToListAsync();
_context.ChallengeGroupChallenges.RemoveRange(challengeGroupChallenges);
await base.RemoveSaveAsync(userId, challengeGroupId);
}
public async Task<bool> StubInUseAsync(int siteId, string stub)
{
return await DbSet
.AsNoTracking()
.Where(_ => _.SiteId == siteId && _.Stub == stub)
.AnyAsync();
}
}
}
|
haraldnagel/gra4
|
src/GRA.Data/Repository/ChallengeGroupRepository.cs
|
C#
|
mit
| 7,420
|
<table class="ui very basic celled table">
<thead>
<tr>
<th>Nom complet</th>
<th>Téléphone</th>
<th>Adresse mail</th>
<th>JEH assignés</th>
<th>Paie par JEH</th>
<th>Actions</th>
</tr>
</thead>
<tfoot ng-if="projectService.selectedProject.userHasRights">
<tr>
<th colspan="6">
<form name="consultantForm" ng-submit="consultantForm.$valid && addConsultant()" novalidate>
<div class="ui centered grid">
<div class="five wide column">
<ng-dropdown data-label="fullName" ng-option="userService.users" data-value="id"
ng-model="consultant.user" required="true"></ng-dropdown>
</div>
<div class="four wide column">
<div class="ui input">
<input placeholder="Nombre de JEH..." type="number" ng-model="consultant.jehAssigned"
required="true"/>
</div>
</div>
<div class="four wide column">
<div class="ui input">
<input placeholder="Paie par JEH..." type="number" ng-model="consultant.payByJeh"
required="true"/>
</div>
</div>
<div class="three wide column">
<input type="submit" value="Ajouter" class="ui green button"
ng-class="{ 'disabled': consultantForm.$invalid }"/>
</div>
</div>
</form>
</th>
</tr>
</tfoot>
<tbody>
<tr ng-repeat="consultant in consultantService.currentProjectConsultants">
<td>
<a ui-sref="hr.userDetailsTab({id : consultant.user.id})">
{{consultant.user.fullName}}<br>
</a>
</td>
<td>{{consultant.user.tel}}</td>
<td>{{consultant.user.email}}</td>
<td>{{consultant.jehAssigned}}</td>
<td>{{consultant.payByJeh}}</td>
<td>
<div class="ui icon buttons" ng-if="uaService.rightLevel >= 4">
<button class="ui red icon button" data-tooltip="Supprimer" ng-click="deleteConsultant(consultant.id)">
<i class="remove icon"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
|
nsorin/DoleticRESTClient
|
app/components/ua/projectDetailsTab/consultant-table/consultant-table.template.html
|
HTML
|
mit
| 2,531
|
package org.multibit.hd.ui.fest.use_cases.keepkey;
import org.fest.swing.fixture.FrameFixture;
import org.multibit.hd.testing.hardware_wallet_fixtures.HardwareWalletFixture;
import org.multibit.hd.ui.fest.use_cases.AbstractHardwareWalletFestUseCase;
import java.util.Map;
/**
* <p>Use case to provide the following to FEST testing:</p>
* <ul>
* <li>Verify the Keepkey "request master public key" screen</li>
* </ul>
*
* <p>Require the panel view to be showing (event triggered earlier)</p>
*
* @since 0.0.5
*/
public class KeepKeyRequestMasterPublicKeyUseCase extends AbstractHardwareWalletFestUseCase {
/**
* @param window The FEST window frame fixture
* @param hardwareWalletFixture The hardware wallet fixture
*/
public KeepKeyRequestMasterPublicKeyUseCase(FrameFixture window, HardwareWalletFixture hardwareWalletFixture) {
super(window, hardwareWalletFixture);
}
@Override
public void execute(Map<String, Object> parameters) {
// This transitional panel is too variable to trap reliably
pauseForViewReset();
}
}
|
bitcoin-solutions/multibit-hd
|
mbhd-swing/src/test/java/org/multibit/hd/ui/fest/use_cases/keepkey/KeepKeyRequestMasterPublicKeyUseCase.java
|
Java
|
mit
| 1,081
|
$(document).ready(function() {
$(".issue-list").on("click", "div", function() {
$(".issue-list .selected").removeClass("selected");
$(this).addClass("selected");
});
$('[data-behaviour="issue-view"]').on("click", "button", function() {
var view = "issue-" + $(this).data("view");
$(".issue-list").removeClass("issue-minimal").removeClass("issue-compact").removeClass("issue-detailed")
.addClass(view);
});
});
|
loz/tyne-core
|
vendor/assets/javascripts/tyne_core/issue_selection.js
|
JavaScript
|
mit
| 441
|
#include <iostream>
#include <stdexcept>
using std::cout;
using std::endl;
struct my_exception : public virtual std::runtime_error {
// To allow this to be thrown directly in the tests below.
explicit my_exception(const std::string &what)
: std::runtime_error(what)
{}
protected:
my_exception()
// This won't be called because of virtual inheritance.
: std::runtime_error("::my_exception")
{}
};
int main(const int argc, const char * const * const argv) {
try {
cout << "Throwing ::my_exception" << endl;
throw ::my_exception("my_what");
} catch(const std::runtime_error &ex) {
cout << "Caught std::runtime_error: " << ex.what() << endl;
}
}
|
processwarp/processwarp
|
test/emscripten/core/test_exceptions_virtual_inheritance.cpp
|
C++
|
mit
| 693
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Julia Package Listing - Testing Information</title>
<style>
/* -- Mix of julialang.org, Bootstrap 3, and custom -- */
body {
background-color: white;
font-family: Georgia, 'Liberation Serif', serif;
font-size: 14px;
color: #333;
line-height: 1.42857143;
}
.site {
max-width: 785px;
margin: 2.5em auto 2em;
padding: 0 1.5em;
}
a {
color: #428bca;
text-decoration: none;
}
h1, h2, h3, h4, h5, h6 {
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
h1, h2, h3 {
margin-top: 20px;
margin-bottom: 10px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
margin-top: 10px;
margin-bottom: 10px;
}
.titlebox {
text-align: center;
font-size: 120%;
margin-top: 3em;
}
.tests_pass { background-color: #11AA11; } /*Tests passing*/
.tests_fail { background-color: #DD3333; } /*Tests failed*/
.no_tests { background-color: #3333DD; } /*Tests missing*/
.not_possible { background-color: #222222; } /*Package excused*/
.statusbox {
width: 12px;
height: 12px;
display: inline-block;
}
hr {
margin-top: 10px;
margin-bottom: 0px;
border: 0;
border-top: 1px solid #eee;
}
.pkglisting h2 { margin-bottom: 0px; }
pre {margin: 0;}
@media (min-width: 785px) {
.pkglisting {
display: table;
width: 100%;
}
.pkgnamedesc {
display: table-cell;
width: 50%;
}
.pkgvertest {
display: table-cell;
width:50%;
text-align: right
}
}
</style>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-44252521-5', 'iainnz.github.io');
ga('send', 'pageview');
</script>
</head>
<body>
<div class="site">
<!-- HEADER -->
<div class="titlebox">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="210px" height="142px" viewBox="0 0 310 216" enable-background="new 0 0 310 216" xml:space="preserve">
<!-- blue dot -->
<circle fill="#6b85dd" stroke="#4266d5" stroke-width="3" cx="50.5" cy="58.665" r="16.5"></circle>
<!-- red dot -->
<circle fill="#d66661" stroke="#c93d39" stroke-width="3" cx="212.459" cy="60.249" r="16.5"></circle>
<!-- green dot -->
<circle fill="#6bab5b" stroke="#3b972e" stroke-width="3" cx="233.834" cy="23.874" r="16.5"></circle>
<!-- purple dot -->
<circle fill="#aa7dc0" stroke="#945bb0" stroke-width="3" cx="255.459" cy="59.999" r="16.5"></circle>
<!-- "j" -->
<path fill="#252525" d="M37.216,138.427c0-15.839,0.006-31.679-0.018-47.517c-0.001-0.827,0.169-1.234,1.043-1.47
c7.876-2.127,15.739-4.308,23.606-6.47c1.33-0.366,1.333-0.36,1.333,1.019c0,25.758,0.015,51.517-0.012,77.274
c-0.006,5.514,0.245,11.032-0.272,16.543c-0.628,6.69-2.15,13.092-6.438,18.506c-3.781,4.771-8.898,7.25-14.767,8.338
c-6.599,1.222-13.251,1.552-19.934,0.938c-4.616-0.423-9.045-1.486-12.844-4.363c-2.863-2.168-4.454-4.935-3.745-8.603
c0.736-3.806,3.348-5.978,6.861-7.127c2.262-0.74,4.628-0.872,6.994-0.53c1.823,0.264,3.42,1.023,4.779,2.288
c1.38,1.284,2.641,2.674,3.778,4.177c0.872,1.15,1.793,2.256,2.991,3.086c2.055,1.426,4,0.965,5.213-1.216
c0.819-1.473,0.997-3.106,1.173-4.731c0.255-2.348,0.255-4.707,0.256-7.062C37.218,167.145,37.216,152.786,37.216,138.427z"></path>
<!-- "u" -->
<path fill="#252525" d="M125.536,162.479c-2.908,2.385-5.783,4.312-8.88,5.904c-10.348,5.323-20.514,4.521-30.324-1.253
c-6.71-3.95-11.012-9.849-12.52-17.606c-0.236-1.213-0.363-2.438-0.363-3.688c0.01-19.797,0.017-39.593-0.02-59.39
c-0.002-1.102,0.285-1.357,1.363-1.351c7.798,0.049,15.597,0.044,23.396,0.003c0.95-0.005,1.177,0.25,1.175,1.183
c-0.027,19.356-0.025,38.713-0.018,58.07c0.002,6.34,3.599,10.934,9.672,12.42c2.13,0.521,4.19,0.396,6.173-0.6
c4.26-2.139,7.457-5.427,10.116-9.307c0.333-0.487,0.224-1,0.224-1.51c0.007-19.635,0.016-39.271-0.02-58.904
c-0.002-1.083,0.255-1.369,1.353-1.361c7.838,0.052,15.677,0.045,23.515,0.004c0.916-0.005,1.103,0.244,1.102,1.124
c-0.025,27.677-0.026,55.353,0.002,83.024c0.001,0.938-0.278,1.099-1.139,1.095c-7.918-0.028-15.837-0.028-23.756-0.001
c-0.815,0.003-1.1-0.166-1.073-1.037C125.581,167.117,125.536,164.928,125.536,162.479z"></path>
<!-- "l" -->
<path fill="#252525" d="M187.423,107.08c0,20.637-0.011,41.273,0.026,61.91c0.003,1.119-0.309,1.361-1.381,1.355
c-7.799-0.052-15.598-0.047-23.396-0.008c-0.898,0.008-1.117-0.222-1.115-1.115c0.021-39.074,0.021-78.147,0-117.226
c0-0.811,0.189-1.169,1.006-1.392c7.871-2.149,15.73-4.327,23.584-6.545c1.045-0.295,1.308-0.17,1.306,0.985
C187.412,65.727,187.423,86.403,187.423,107.08z"></path>
<!-- "i" -->
<path fill="#252525" d="M223.46,126.477c0,14.155-0.011,28.312,0.021,42.467c0.002,1.027-0.164,1.418-1.332,1.408
c-7.838-0.061-15.676-0.047-23.516-0.01c-0.881,0.004-1.121-0.189-1.119-1.104c0.026-26.153,0.025-52.307,0-78.458
c0-0.776,0.203-1.101,0.941-1.302c7.984-2.172,15.972-4.35,23.938-6.596c1.049-0.296,1.08,0.031,1.078,0.886
C223.454,98.004,223.46,112.239,223.46,126.477z"></path>
<!-- "a" -->
<path fill="#252525" d="M277.695,163.6c-0.786,0.646-1.404,1.125-2,1.635c-4.375,3.746-9.42,5.898-15.16,6.42
c-5.792,0.527-11.479,0.244-16.934-2.047c-12.08-5.071-15.554-17.188-11.938-27.448c1.799-5.111,5.472-8.868,9.831-11.94
c5.681-4.003,12.009-6.732,18.504-9.074c5.576-2.014,11.186-3.939,16.955-5.347c0.445-0.104,0.773-0.243,0.757-0.854
c-0.136-4.389,0.261-8.79-0.479-13.165c-1.225-7.209-6.617-10.013-12.895-9.348c-0.516,0.055-1.029,0.129-1.536,0.241
c-4.877,1.081-7.312,4.413-7.374,10.127c-0.02,1.729-0.229,3.418-0.693,5.084c-0.906,3.229-2.969,5.354-6.168,6.266
c-3.422,0.979-6.893,0.998-10.23-0.305c-6.529-2.543-8.877-10.164-5.12-16.512c2.249-3.799,5.606-6.4,9.461-8.405
c6.238-3.246,12.914-4.974,19.896-5.537c7.565-0.61,15.096-0.366,22.49,1.507c4.285,1.085,8.312,2.776,11.744,5.657
c4.473,3.749,6.776,8.647,6.812,14.374c0.139,21.477,0.096,42.951,0.143,64.428c0.002,0.799-0.248,0.983-1.021,0.98
c-8.035-0.025-16.074-0.023-24.113-0.001c-0.716,0.002-0.973-0.146-0.941-0.915C277.736,167.562,277.695,165.698,277.695,163.6z
M277.695,126.393c-4.793,2.104-9.25,4.373-13.287,7.408c-2.151,1.618-4.033,3.483-5.732,5.581
c-4.229,5.226-1.988,13.343,1.693,16.599c1.592,1.406,3.359,1.906,5.419,1.521c1.621-0.307,3.149-0.857,4.549-1.734
c1.521-0.951,2.949-2.072,4.539-2.887c2.31-1.18,2.97-2.861,2.894-5.445C277.561,140.484,277.695,133.527,277.695,126.393z"></path>
</svg>
<h1>
<a href="http://github.com/JuliaReducePkg/ReduceAlgebra.jl" name="ReduceAlgebra">ReduceAlgebra</a>
</h1>
<h4>
<a href="http://github.com/JuliaReducePkg">JuliaReducePkg</a>
</h4>
<p>
<a href="http://pkg.julialang.org#ReduceAlgebra">← Back to package list</a>
</p>
</div>
<p>
If you think that there is an error in how your package is being tested or represented, please file an issue at <a href="https://github.com/JuliaCI/PackageEvaluator.jl/">PackageEvaluator.jl</a>, making sure to read the FAQ first.
</p>
<h3>Badges</h3>
<h4>Julia v0.6</h4>
<img src="../badges/ReduceAlgebra_0.6.svg">
<br>
<a href="http://pkg.julialang.org/badges/ReduceAlgebra_0.6.svg">http://pkg.julialang.org/badges/ReduceAlgebra_0.6.svg</a>
<pre>[](http://pkg.julialang.org/detail/ReduceAlgebra)</pre>
<h3>Most Recent Test Logs</h3>
<ul>
<li>
<a href="../logs/ReduceAlgebra_0.6.log">Julia v0.6</a>
</li>
</ul>
<h3>Version and Status History</h3>
<h4>Julia v0.6</h4>
<pre>2018-06-20 to 2018-08-04, v0.0.1, Tests pass.
</pre>
</div>
</body>
</html>
|
IainNZ/packages.julialang.org
|
detail/ReduceAlgebra.html
|
HTML
|
mit
| 8,759
|
<a href='https://github.com/angular/angular.js/edit/v1.4.x/src/Angular.js?message=docs(angular.isDate)%3A%20describe%20your%20change...#L486' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<a href='https://github.com/angular/angular.js/tree/v1.4.0-beta.3/src/Angular.js#L486' class='view-source pull-right btn btn-primary'>
<i class="glyphicon glyphicon-zoom-in"> </i>View Source
</a>
<header class="api-profile-header">
<h1 class="api-profile-header-heading">angular.isDate</h1>
<ol class="api-profile-header-structure naked-list step-list">
<li>
- function in module <a href="api/ng">ng</a>
</li>
</ol>
</header>
<div class="api-profile-description">
<p>Determines if a value is a date.</p>
</div>
<div>
<h2 id="usage">Usage</h2>
<p><code>angular.isDate(value);</code></p>
<section class="api-section">
<h3>Arguments</h3>
<table class="variables-matrix input-arguments">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
value
</td>
<td>
<a href="" class="label type-hint type-hint-object">*</a>
</td>
<td>
<p>Reference to check.</p>
</td>
</tr>
</tbody>
</table>
</section>
<h3>Returns</h3>
<table class="variables-matrix return-arguments">
<tr>
<td><a href="" class="label type-hint type-hint-boolean">boolean</a></td>
<td><p>True if <code>value</code> is a <code>Date</code>.</p>
</td>
</tr>
</table>
</div>
|
parinyacp/helpdesk
|
website/public_html/js/asset/angular/docs/partials/api/ng/function/angular.isDate.html
|
HTML
|
mit
| 1,678
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport"/>
<meta content="telephone=no" name="format-detection"/>
<meta content="address=no" name="format-detection"/>
<title> 臑俞穴
</title>
<link href="./css/reset.css?v=1" rel="stylesheet" type="text/css"/>
<link href="./css/case.css?v=3" rel="stylesheet" type="text/css"/>
<link href="./css/cm.css?v=7" rel="stylesheet" type="text/css"/>
<link href="./css/banner.css" rel="stylesheet" type="text/css"/>
</head>
<body class="bg-fff">
<section class="acupoint-info">
<div class="a-img"><img alt="" src="http://img02.sogoucdn.com/app/a/200574/a00e1e345b094d199e5a43b57d257836.jpg"/></div>
<div class="case-content">
<ul class="info-list">
<li><span>【穴位名】</span><p>臑俞穴</p></li>
<li><span>【功效】</span><p>舒筋活络,化痰消肿。
</p></li>
<li><span>【主治】</span><p>主臂酸无力,肩痛引胛,寒热气肿胫痛。</p></li>
<li><span>【取穴方法】</span><p>在肩部,当腋后纹头直上,肩胛冈下缘凹陷中。</p></li>
<li><span>【穴位配伍】</span><p>配肩髃、曲池治肩臂疼痛。
</p></li>
</ul>
</div>
</section>
</body>
<!--zly-->
</html>
|
hucaihua/cmssp
|
server/html/point/412.html
|
HTML
|
mit
| 1,272
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace CacheCow.Tests.Server.Integration.MiniServer
{
public class InMemoryServer: HttpMessageHandler
{
private HttpServer _httpServer;
private HttpMessageInvoker _invoker;
public InMemoryServer(HttpConfiguration configuration)
{
_httpServer = new HttpServer(configuration);
_invoker = new HttpMessageInvoker(_httpServer);
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return _invoker.SendAsync(request, cancellationToken);
}
}
}
|
Hotkey/CacheCow
|
test/CacheCow.Tests/Server/Integration/MiniServer/InMemoryServer.cs
|
C#
|
mit
| 815
|
#include <memory>
template <typename T>
class queue {
public:
queue() : _head(new node()), _tail(_head.get()) { }
queue(const queue& other) = delete;
queue& operator= (const queue& other) = delete;
std::shared_ptr<T> try_pop() {
if (_head.get() == _tail)
return std::shared_ptr<T>();
const std::shared_ptr<T> res(_head->data);
std::unique_ptr<node> old_head = std::move(_head);
_head = std::move(old_head->next);
return res;
}
void push(T new_value) {
std::shared_ptr<T> new_data(
std::make_shared<T>(std::move(new_value)));
std::unique_ptr<node> p(new node);
_tail->data = new_data;
const node* new_tail = p.get();
_tail->next = std::move(p);
_tail = new_tail;
}
private:
struct node {
std::shared_ptr<T> data;
std::unique_ptr<node> next;
};
std::unique_ptr<node> _head;
node* _tail;
};
int main() {
return 0;
}
|
ordinary-developer/book_c_plus_plus_concurrency_in_action_a_williams
|
code/ch_6-LOCK-BASED_CONCURRENT_DATA_STRUCTURES/06-a_queue_with_a_dummy_node/main.cpp
|
C++
|
mit
| 1,105
|
#include <thread>
#include <iostream>
#include <memory>
class scoped_thread {
std::thread t;
public:
explicit scoped_thread(std::thread t_):
t(std::move(t_))
{
if (!t.joinable())
throw std::logic_error("No thread");
}
~scoped_thread()
{
std::cout << "destructor calling" << std::endl;
t.join();
}
scoped_thread(const scoped_thread&) = delete;
scoped_thread& operator= (scoped_thread const&) = delete;
};
struct func {
int& i;
func(int& i_) : i(i_) { }
void operator() () {
for (unsigned j = 0; j < 1000000; ++j) {
do_something();
}
}
void do_something() {
std::cout << "[another thread]: " << " working" << std::endl;
}
};
void do_something_in_current_thread() {
std::cout << "[current thread]: " << " working" << std::endl;
}
void f() {
int some_local_state;
auto scoped_thread_ptr = std::make_unique<scoped_thread>(
std::thread(func(some_local_state)));
do_something_in_current_thread();
}
int main() {
f();
return 0;
}
|
ordinary-developer/book_c_plus_plus_concurrency_in_action_a_williams
|
code/ch_2-BASIC_THREAD_MANAGEMENT/17-scope_thread/main.cpp
|
C++
|
mit
| 1,166
|
package org.ethereum.jsonrpc;
import org.ethereum.util.ByteUtil;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
/**
* Created by Ruben on 19/11/2015.
*/
public class TypeConverter {
public static byte[] StringNumberAsBytes(String input) {
return ByteUtil.bigIntegerToBytes(StringDecimalToBigInteger(input));
}
public static BigInteger StringNumberAsBigInt(String input) throws Exception {
if (input.startsWith("0x"))
return TypeConverter.StringHexToBigInteger(input);
else
return TypeConverter.StringDecimalToBigInteger(input);
}
public static BigInteger StringHexToBigInteger(String input) {
String hexa = input.substring(2);
return new BigInteger(hexa, 16);
}
private static BigInteger StringDecimalToBigInteger(String input) {
return new BigInteger(input);
}
public static byte[] StringHexToByteArray(String x) throws Exception {
if (x.startsWith("0x")) {
x = x.substring(2);
}
if (x.length() % 2 != 0) x = "0" + x;
return Hex.decode(x);
}
public static String toJsonHex(byte[] x) {
return "0x"+Hex.toHexString(x);
}
public static String toJsonHex(String x) {
return "0x"+x;
}
public static String toJsonHex(long n) {
return "0x"+Long.toHexString(n);
}
public static String toJsonHex(BigInteger n) {
return "0x"+ n.toString(16);
}
}
|
gcc2ge/ethereumj
|
ethereumj-core/src/main/java/org/ethereum/jsonrpc/TypeConverter.java
|
Java
|
mit
| 1,495
|
/**
* ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v21.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var context_1 = require("../../context/context");
var componentMetadataProvider_1 = require("./componentMetadataProvider");
var utils_1 = require("../../utils");
var AgComponentUtils = /** @class */ (function () {
function AgComponentUtils() {
}
AgComponentUtils.prototype.adaptFunction = function (propertyName, hardcodedJsFunction, componentFromFramework, source) {
if (hardcodedJsFunction == null) {
return {
component: null,
componentFromFramework: componentFromFramework,
source: source,
paramsFromSelector: null
};
}
var metadata = this.componentMetadataProvider.retrieve(propertyName);
if (metadata && metadata.functionAdapter) {
return {
componentFromFramework: componentFromFramework,
component: metadata.functionAdapter(hardcodedJsFunction),
source: source,
paramsFromSelector: null
};
}
return null;
};
AgComponentUtils.prototype.adaptCellRendererFunction = function (callback) {
var Adapter = /** @class */ (function () {
function Adapter() {
}
Adapter.prototype.refresh = function (params) {
return false;
};
Adapter.prototype.getGui = function () {
var callbackResult = callback(this.params);
var type = typeof callbackResult;
if (type === 'string' || type === 'number' || type === 'boolean') {
return utils_1._.loadTemplate('<span>' + callbackResult + '</span>');
}
else {
return callbackResult;
}
};
Adapter.prototype.init = function (params) {
this.params = params;
};
return Adapter;
}());
return Adapter;
};
AgComponentUtils.prototype.doesImplementIComponent = function (candidate) {
if (!candidate) {
return false;
}
return candidate.prototype && 'getGui' in candidate.prototype;
};
__decorate([
context_1.Autowired("componentMetadataProvider"),
__metadata("design:type", componentMetadataProvider_1.ComponentMetadataProvider)
], AgComponentUtils.prototype, "componentMetadataProvider", void 0);
AgComponentUtils = __decorate([
context_1.Bean("agComponentUtils")
], AgComponentUtils);
return AgComponentUtils;
}());
exports.AgComponentUtils = AgComponentUtils;
|
cdnjs/cdnjs
|
ajax/libs/ag-grid/21.2.0/lib/components/framework/agComponentUtils.js
|
JavaScript
|
mit
| 3,634
|
angular.module('netanimations.subnets', [])
.controller('SubnetsCtrl', function ($state, $scope, $ionicPopup, $translate, $compile) {
TweenLite.defaultEase = Power1.easeInOut;
$scope.end = false;
$scope.restart = function () {
tl.seek(0);
$scope.end = false;
};
var tl = new TimelineLite();
$scope.tl = tl;
$scope.accessibilityGo = function (op, state) {
switch (op) {
case 'exit':
$scope.tl.seek(0);
$scope.tl.play();
$state.go(state);
break;
case 'next':
cleanContentInfo();
$scope.tl.resume();
break;
case 'back':
cleanContentInfo();
$scope.tl.seek(state); //checkpoint de retrocesso
$scope.tl.play();
break;
case 'restart':
cleanContentInfo();
$scope.tl.seek(state);
$scope.tl.play();
break;
}
};
//initialize
var navBarHeight = 68;
var subnets = '.subnets';
var board = '.subnets-board'
var whiteBoard = '.white-board';
var subnetMask = '.subnet-mask';
var destinationIp1 = '.destination-ip-1';
var subnetIp1 = '.subnet-ip-1';
var subnetIp2 = '.subnet-ip-2';
var convertingToBit = '.conveting-to-bit';
var subnetMaskBit = '.subnet-mask-bit';
var destinationIp1Bit = '.destination-ip-1-bit';
var realizingLogicAnd = '.realizing-logic-and';
var subnetIp1Bit = '.subnet-ip-1-bit';
var convertingToDecimal = '.converting-to-decimal';
var subnetPackage = '.subnet-package';
var destinationIp2 = '.destination-ip-2';
var destinationIp2Bit = '.destination-ip-2-bit';
var subnetIp2Bit = '.subnet-ip-2-bit';
var widthScreen = window.screen.width;
var heightScreen = window.screen.height - navBarHeight;
// white board
var whiteBoardWidth = widthScreen * 0.9;
var whiteBoardHeight = heightScreen * 0.95;
//actions
var show = { opacity: 1 };
var hide = { opacity: 0 };
// initialize background
//tl.set(subnets, {width:subnetsWidth}).set(subnets, {y:0}).set(subnets, {x:center});
var subnetsHeight = heightScreen * 0.80;
var subnetsWidth = subnetsHeight * 1.9116;
tl.set(subnets, { height: subnetsHeight })
.set(subnets, { y: heightScreen * 0.05 });
//var subnetsWidth = document.getElementsByClassName('subnets')[0].width;
var center = ((subnetsWidth / 2) - (widthScreen / 2)) * -1;
tl.set(subnets, { x: center });
var left = 0;
var right = (subnetsWidth - widthScreen) * -1;
// black boarder board
var boardWidth = subnetsWidth * 0.35;
var boardHeight = heightScreen * 0.10
//initialize black border board
var boardY = heightScreen * 0.27;
var boardX = getPositionX(boardWidth);
tl.set(board, {
width: boardWidth,
x: boardX,
y: boardY,
height: boardHeight,
opacity: 0
});
//initialize white board
tl.set(whiteBoard, {
width: whiteBoardWidth,
height: whiteBoardHeight,
x: getPositionX(whiteBoardWidth),
opacity: 0
});
//initialize ips
tl.set(subnetMask, hide);
tl.set(subnetIp1, hide);
tl.set(subnetIp2, hide);
tl.set(destinationIp1, hide);
tl.set(convertingToBit, hide);
tl.set(subnetMaskBit, hide);
tl.set(destinationIp1Bit, hide);
tl.set(realizingLogicAnd, hide);
tl.set(subnetIp1Bit, hide);
tl.set(convertingToDecimal, hide);
tl.set(subnetPackage, hide);
tl.set(destinationIp2, hide);
tl.set(destinationIp2Bit, hide);
tl.set(subnetIp2Bit, hide);
tl.set(subnetMask, {
x: getPositionX(whiteBoardWidth) + 20
});
tl.set(destinationIp1, {
x: getPositionX(whiteBoardWidth) + 20,
y: heightScreen * 0.075
});
tl.set(convertingToBit, {
y: heightScreen * 0.15,
x: getPositionX(whiteBoardWidth) + 20
});
tl.set(subnetMaskBit, {
y: heightScreen * 0.30,
x: getPositionX(whiteBoardWidth) + 20
})
tl.set(destinationIp1Bit, {
y: heightScreen * 0.45,
x: getPositionX(whiteBoardWidth) + 20
});
tl.set(destinationIp2Bit, {
y: heightScreen * 0.45,
x: getPositionX(whiteBoardWidth) + 20
});
tl.set(realizingLogicAnd, {
y: heightScreen * 0.55,
x: getPositionX(whiteBoardWidth) + 20
});
tl.set(subnetIp1Bit, {
y: heightScreen * 0.65,
x: getPositionX(whiteBoardWidth) + 20
});
tl.set(subnetIp2Bit, {
y: heightScreen * 0.65,
x: getPositionX(whiteBoardWidth) + 20
});
tl.set(convertingToDecimal, {
y: heightScreen * 0.75,
x: getPositionX(whiteBoardWidth) + 20
})
tl.set(subnetIp1, {
y: heightScreen * 0.825,
x: getPositionX(whiteBoardWidth) + 20
});
tl.set(subnetIp2, {
y: heightScreen * 0.825,
x: getPositionX(whiteBoardWidth) + 20
});
// initialize package
var packageY = subnetsHeight * 0.6;
var packageX = subnetsWidth * 0.07;
tl.set(subnetPackage, {
y: packageY,
x: packageX,
rotation: 42
});
var audiovisualPreference = $scope.audiovisual;
var audio = new Audio();
//audio.src = 'audio/subnets/1-2.ogg';
audio.addEventListener('loadedmetadata', function () {
console.log("Load " + audio.src + ", for: " + audio.duration + "seconds.");
});
// initialize animation
tl.add("step1");
tl.call(function () {
initialPopup(tl, $translate, $ionicPopup, $state, $scope, $compile, 'INFO', 'SUBNETS_PRESENTATION_0');
});
tl.to('.animationFrame', 0.5, { x: 0 }); //dummy step - do not remove
if (audiovisualPreference) {
tl.to(audio, 1, { onComplete: function () { playAudio(audio, 'audio/subnets/1-2.ogg') } });
tl.to(board, 11, show);
tl.to(board, 2, hide);
}
else {
tl.to(board, 1, { opacity: 1 });
tl.to(board, 1, { opacity: 0 });
}
tl.add("step2");
tl.call(function () {
commonPopup(tl, $scope, $compile, $translate, $ionicPopup, 'INFO', 'SUBNETS_PRESENTATION_01', "step1", "step1");
});
tl.to('.animationFrame', 1, { x: 0 }); //dummy step - do not remove
boardHeight = heightScreen * 0.20;
boardWidth = subnetsWidth * 0.40;
boardY = heightScreen * 0.35;
boardX = getPositionX(boardWidth);
if (audiovisualPreference) {
//audio.src = 'audio/subnets/2-3.ogg';
tl.to(audio, 1, { onComplete: function () { playAudio(audio, 'audio/subnets/2-3.ogg') } });
tl.to(subnets, 4, { x: left });
tl.to(board, 1, {
height: boardHeight,
width: boardWidth,
y: boardY, x: boardX
});
tl.to(board, 4, show);
tl.to(board, 1, hide);
}
else {
tl.to(subnets, 1, { x: left });
tl.to(board, 0, {
height: boardHeight,
width: boardWidth,
y: boardY, x: boardX
});
tl.to(board, 1, show);
tl.to(board, 1, hide);
}
tl.add("step3");
tl.call(function () {
commonPopup(tl, $scope, $compile, $translate, $ionicPopup, 'INFO', 'SUBNETS_PRESENTATION_02', "step2", "step1");
});
tl.to('.animationFrame', 1, { x: 0 }); //dummy step - do not remove
if (audiovisualPreference) {
tl.to(audio, 1, { onComplete: function () { playAudio(audio, 'audio/subnets/3-4.ogg') } });
tl.to(subnets, 4, { x: right });
//tl.to(board, 0.1, { x: boardX });
tl.to(board, 7, show);
tl.to(board, 1, hide);
}
else {
tl.to(subnets, 1, { x: right });
tl.to(board, 0.1, { x: boardX });
tl.to(board, 1, show);
tl.to(board, 1, hide);
}
tl.add("step4");
tl.call(function () {
commonPopup(tl, $scope, $compile, $translate, $ionicPopup, 'INFO', 'SUBNETS_PRESENTATION_03', "step3", "step1");
});
tl.to('.animationFrame', 1, { x: 0 }); //dummy step - do not remove
tl.add("step5");
tl.call(function () {
commonPopup(tl, $scope, $compile, $translate, $ionicPopup, 'INFO', 'SUBNETS_PRESENTATION_04', "step4", "step1");
});
tl.to('.animationFrame', 1, { x: 0 }); //dummy step - do not remove
if (audiovisualPreference) {
tl.to(audio, 1, { onComplete: function () { playAudio(audio, 'audio/subnets/5-6.ogg') } });
tl.to(whiteBoard, 3, show);
tl.to(subnetMask, 3, show);
tl.to(destinationIp1, 3, show);
tl.to(convertingToBit, 3, show);
tl.to(subnetMaskBit, 3, show);
tl.to(destinationIp1Bit, 3, show);
tl.to(realizingLogicAnd, 3, show);
tl.to(subnetIp1Bit, 3, show);
tl.to(convertingToDecimal, 3, show);
tl.to(subnetIp1, 3, show);
tl.to(subnetMask, 0.1, hide);
tl.to(destinationIp1, 0.1, hide);
tl.to(convertingToBit, 0.1, hide);
tl.to(subnetMaskBit, 0.1, hide);
tl.to(destinationIp1Bit, 0.1, hide);
tl.to(realizingLogicAnd, 0.1, hide);
tl.to(subnetIp1Bit, 0.1, hide);
tl.to(convertingToDecimal, 0.1, hide);
}
else {
tl.to(whiteBoard, 1, show);
tl.to(subnetMask, 1, show);
tl.to(destinationIp1, 1, show);
tl.to(convertingToBit, 2, show);
tl.to(subnetMaskBit, 2, show);
tl.to(destinationIp1Bit, 1, show);
tl.to(realizingLogicAnd, 1, show);
tl.to(subnetIp1Bit, 1, show);
tl.to(convertingToDecimal, 1.5, show);
tl.to(subnetIp1, 1, show);
tl.to(subnetMask, 0.1, hide);
tl.to(destinationIp1, 0.1, hide);
tl.to(convertingToBit, 0.1, hide);
tl.to(subnetMaskBit, 0.1, hide);
tl.to(destinationIp1Bit, 0.1, hide);
tl.to(realizingLogicAnd, 0.1, hide);
tl.to(subnetIp1Bit, 0.1, hide);
tl.to(convertingToDecimal, 0.1, hide);
}
tl.to('.animationFrame', 3, { x: 0 }); //dummy step - do not remove
tl.add("step6");
tl.call(function () {
commonPopup(tl, $scope, $compile, $translate, $ionicPopup, 'INFO', 'SUBNETS_PRESENTATION_05', "step5", "step1");
});
tl.to('.animationFrame', 1, { x: 0 }); //dummy step - do not remove
boardHeight = heightScreen * 0.28;
boardY = heightScreen * 0.30;
packageX = subnetsWidth * 0.33;
packageY = subnetsHeight * 0.99;
if (audiovisualPreference) {
tl.to(audio, 1, { onComplete: function () { playAudio(audio, 'audio/subnets/6-7.ogg') } });
tl.to(subnetIp1, 3, { y: heightScreen * 0.30, x: widthScreen * 0.40 });
tl.to(whiteBoard, 1, hide);
tl.to(board, 0.1, { height: boardHeight, y: boardY });
tl.to(board, 1, show);
tl.to('.animationFrame', 3, { x: 0 }); //dummy step - do not remove
tl.to(subnetIp1, 0.1, hide);
tl.to(board, 3, hide);
tl.to(subnetPackage, 1, show);
tl.to(subnetPackage, 3, { y: packageY, x: packageX });
tl.to(subnetPackage, 1, hide);
}
else {
tl.to(subnetIp1, 1, { y: heightScreen * 0.30, x: widthScreen * 0.40 });
tl.to(whiteBoard, 1, hide);
tl.to(board, 0.1, { height: boardHeight, y: boardY });
tl.to(board, 1, show);
tl.to('.animationFrame', 3, { x: 0 }); //dummy step - do not remove
tl.to(subnetIp1, 0.1, hide);
tl.to(board, 1, hide);
tl.to(subnetPackage, 1, show);
tl.to(subnetPackage, 4, { y: packageY, x: packageX });
tl.to(subnetPackage, 1, hide);
}
tl.add("step7");
tl.call(function () {
commonPopup(tl, $scope, $compile, $translate, $ionicPopup, 'INFO', 'SUBNETS_PRESENTATION_06', "step6", "step1");
});
tl.to('.animationFrame', 1, { x: 0 }); //dummy step - do not remove
tl.set(destinationIp2, {
x: getPositionX(whiteBoardWidth) + 20,
y: heightScreen * 0.075
});
if(audiovisualPreference){
tl.to(audio, 1, {onComplete: function(){playAudio(audio, 'audio/subnets/7-8.ogg')}});
tl.to(whiteBoard, 3, show);
tl.to(subnetMask, 3, show);
tl.to(destinationIp2, 3, show);
tl.to(convertingToBit, 3, show);
tl.to(subnetMaskBit, 3, show);
tl.to(destinationIp2Bit, 3, show);
tl.to(realizingLogicAnd, 3, show);
tl.to(subnetIp2Bit, 3, show);
tl.to(convertingToDecimal, 3, show);
tl.to(subnetIp2, 3, show);
tl.to(subnetMask, 0.1, hide);
tl.to(destinationIp2, 0.1, hide);
tl.to(convertingToBit, 0.1, hide);
tl.to(subnetMaskBit, 0.1, hide);
tl.to(destinationIp2Bit, 0.1, hide);
tl.to(realizingLogicAnd, 0.1, hide);
tl.to(subnetIp2Bit, 0.1, hide);
tl.to(convertingToDecimal, 0.1, hide);
tl.to(subnetIp2, 1, hide);
tl.to(whiteBoard, 1, hide);
tl.to(subnetPackage, 3, show);
packageX = subnetsWidth * 0.20;
packageY = subnetsHeight * 0.80;
tl.to(subnetPackage, 3, { y: packageY, x: packageX });
tl.to(subnetPackage, 3, { rotation: 0 });
tl.to(subnets, 3, { x: center });
}
else{
tl.to(whiteBoard, 1, show);
tl.to(subnetMask, 1, show);
tl.to(destinationIp2, 1, show);
tl.to(convertingToBit, 1, show);
tl.to(subnetMaskBit, 1, show);
tl.to(destinationIp2Bit, 1, show);
tl.to(realizingLogicAnd, 1, show);
tl.to(subnetIp2Bit, 1, show);
tl.to(convertingToDecimal, 1, show);
tl.to(subnetIp2, 1, show);
tl.to(subnetMask, 0.1, hide);
tl.to(destinationIp2, 0.1, hide);
tl.to(convertingToBit, 0.1, hide);
tl.to(subnetMaskBit, 0.1, hide);
tl.to(destinationIp2Bit, 0.1, hide);
tl.to(realizingLogicAnd, 0.1, hide);
tl.to(subnetIp2Bit, 0.1, hide);
tl.to(convertingToDecimal, 0.1, hide);
tl.to(subnetIp2, 1, hide);
tl.to(whiteBoard, 1, hide);
tl.to(subnetPackage, 1, show);
packageX = subnetsWidth * 0.20;
packageY = subnetsHeight * 0.80;
tl.to(subnetPackage, 3, { y: packageY, x: packageX });
tl.to(subnetPackage, 1, { rotation: 0 });
tl.to(subnets, 2, { x: center });
}
tl.add("step8");
tl.call(function () {
commonPopup(tl, $scope, $compile, $translate, $ionicPopup, 'INFO', 'SUBNETS_PRESENTATION_07', "step7", "step1");
});
tl.to('.animationFrame', 1, { x: 0 }); //dummy step - do not remove
packageX = subnetsWidth * 0.07;
packageY = subnetsHeight * 0.99;
if(audiovisualPreference){
tl.to(audio, 1, {onComplete: function(){playAudio(audio, 'audio/subnets/9-10.ogg')}});
tl.to(subnets, 3, { x: left });
tl.to(subnetPackage, 1, { rotation: -42 });
tl.to(subnetPackage, 3, { y: packageY, x: packageX });
tl.to(subnetPackage, 1, hide);
}
else{
tl.to(subnets, 2, { x: left });
tl.to(subnetPackage, 1, { rotation: -42 });
tl.to(subnetPackage, 3, { y: packageY, x: packageX });
tl.to(subnetPackage, 1, hide);
}
tl.to('.animationFrame', 1, { x: 0 }); //dummy step - do not remove
tl.call(function () {
endPopup(tl, $translate, $ionicPopup, $state, $scope, $compile, 'END', 'SUBNETS_PRESENTATION_6', "step8", "step1");
});
});
function getPositionX(width) {
var dif = window.screen.width - width;
return dif / 2;
}
|
Sutil/netanimations
|
www/js/app/subnets.js
|
JavaScript
|
cc0-1.0
| 15,065
|
/**
* CustomGroupHandler.cpp
*
* Created on: Mar 5, 2015
* Author: pschultz
*/
#include "CustomGroupHandler.hpp"
#include "InputLayer.hpp"
#include "GTLayer.hpp"
#include "ComparisonLayer.hpp"
namespace PVMLearning{
PV::ParamGroupType CustomGroupHandler::getGroupType(char const * keyword) {
PV::ParamGroupType result = PV::UnrecognizedGroupType;
if (keyword == NULL) { return result; }
else if (!strcmp(keyword, "InputLayer")) { result = PV::LayerGroupType; }
else if (!strcmp(keyword, "GTLayer")) { result = PV::LayerGroupType; }
else if (!strcmp(keyword, "ComparisonLayer")) { result = PV::LayerGroupType; }
return result;
}
PV::HyPerLayer * CustomGroupHandler::createLayer(char const * keyword, char const * name, PV::HyPerCol * hc) {
PV::HyPerLayer * layer = NULL;
if (keyword == NULL || getGroupType(keyword) != PV::LayerGroupType) { return layer; }
else if (!strcmp(keyword, "InputLayer")) { layer = new InputLayer(name, hc); }
else if (!strcmp(keyword, "GTLayer")) { layer = new GTLayer(name, hc); }
else if (!strcmp(keyword, "ComparisonLayer")) { layer = new ComparisonLayer(name, hc); }
if (layer==NULL) {
fprintf(stderr, "Rank %d process unable to create %s \"%s\"\n", hc->columnId(), keyword, name);
exit(EXIT_FAILURE);
}
return layer;
}
} // namespace PVMatchingPursuit
|
PetaVision/projects
|
mlearning/tests/MLPTest/src/CustomGroupHandler.cpp
|
C++
|
epl-1.0
| 1,357
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_25) on Thu Sep 12 10:52:56 BST 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface com.hp.hpl.jena.sparql.algebra.OpVisitor (Apache Jena ARQ)</title>
<meta name="date" content="2013-09-12">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface com.hp.hpl.jena.sparql.algebra.OpVisitor (Apache Jena ARQ)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/hp/hpl/jena/sparql/algebra/class-use/OpVisitor.html" target="_top">Frames</a></li>
<li><a href="OpVisitor.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface com.hp.hpl.jena.sparql.algebra.OpVisitor" class="title">Uses of Interface<br>com.hp.hpl.jena.sparql.algebra.OpVisitor</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.hp.hpl.jena.sparql.algebra">com.hp.hpl.jena.sparql.algebra</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.hp.hpl.jena.sparql.algebra.op">com.hp.hpl.jena.sparql.algebra.op</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.hp.hpl.jena.sparql.algebra.optimize">com.hp.hpl.jena.sparql.algebra.optimize</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.hp.hpl.jena.sparql.engine.ref">com.hp.hpl.jena.sparql.engine.ref</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.hp.hpl.jena.sparql.sse.writers">com.hp.hpl.jena.sparql.sse.writers</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.hp.hpl.jena.sparql.algebra">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> in <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/package-summary.html">com.hp.hpl.jena.sparql.algebra</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/package-summary.html">com.hp.hpl.jena.sparql.algebra</a> that implement <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/BeforeAfterVisitor.html" title="class in com.hp.hpl.jena.sparql.algebra">BeforeAfterVisitor</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpAsQuery.Converter.html" title="class in com.hp.hpl.jena.sparql.algebra">OpAsQuery.Converter</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitorBase.html" title="class in com.hp.hpl.jena.sparql.algebra">OpVisitorBase</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitorByType.html" title="class in com.hp.hpl.jena.sparql.algebra">OpVisitorByType</a></strong></code>
<div class="block">A visitor helper that maps all visits to a few general ones</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitorByTypeBase.html" title="class in com.hp.hpl.jena.sparql.algebra">OpVisitorByTypeBase</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Transformer.ApplyTransformVisitor.html" title="class in com.hp.hpl.jena.sparql.algebra">Transformer.ApplyTransformVisitor</a></strong></code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/package-summary.html">com.hp.hpl.jena.sparql.algebra</a> with parameters of type <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Op.html" title="interface in com.hp.hpl.jena.sparql.algebra">Op</a></code></td>
<td class="colLast"><span class="strong">Transformer.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Transformer.html#transform(com.hp.hpl.jena.sparql.algebra.Transform, com.hp.hpl.jena.sparql.expr.ExprTransform, com.hp.hpl.jena.sparql.algebra.Op, com.hp.hpl.jena.sparql.algebra.OpVisitor, com.hp.hpl.jena.sparql.algebra.OpVisitor)">transform</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Transform.html" title="interface in com.hp.hpl.jena.sparql.algebra">Transform</a> transform,
<a href="../../../../../../../com/hp/hpl/jena/sparql/expr/ExprTransform.html" title="interface in com.hp.hpl.jena.sparql.expr">ExprTransform</a> exprTransform,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Op.html" title="interface in com.hp.hpl.jena.sparql.algebra">Op</a> op,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> beforeVisitor,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> afterVisitor)</code>
<div class="block">Transformation with specific Transform and ExprTransform applied</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Op.html" title="interface in com.hp.hpl.jena.sparql.algebra">Op</a></code></td>
<td class="colLast"><span class="strong">Transformer.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Transformer.html#transform(com.hp.hpl.jena.sparql.algebra.Transform, com.hp.hpl.jena.sparql.algebra.Op, com.hp.hpl.jena.sparql.algebra.OpVisitor, com.hp.hpl.jena.sparql.algebra.OpVisitor)">transform</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Transform.html" title="interface in com.hp.hpl.jena.sparql.algebra">Transform</a> transform,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Op.html" title="interface in com.hp.hpl.jena.sparql.algebra">Op</a> op,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> beforeVisitor,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> afterVisitor)</code>
<div class="block">Transformation with specific Transform and default ExprTransform (apply transform inside pattern expressions like NOT EXISTS)</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Op.html" title="interface in com.hp.hpl.jena.sparql.algebra">Op</a></code></td>
<td class="colLast"><span class="strong">Transformer.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Transformer.html#transformSkipService(com.hp.hpl.jena.sparql.algebra.Transform, com.hp.hpl.jena.sparql.expr.ExprTransform, com.hp.hpl.jena.sparql.algebra.Op, com.hp.hpl.jena.sparql.algebra.OpVisitor, com.hp.hpl.jena.sparql.algebra.OpVisitor)">transformSkipService</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Transform.html" title="interface in com.hp.hpl.jena.sparql.algebra">Transform</a> transform,
<a href="../../../../../../../com/hp/hpl/jena/sparql/expr/ExprTransform.html" title="interface in com.hp.hpl.jena.sparql.expr">ExprTransform</a> exprTransform,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Op.html" title="interface in com.hp.hpl.jena.sparql.algebra">Op</a> op,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> beforeVisitor,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> afterVisitor)</code>
<div class="block">Transform an algebra expression except skip (leave alone) any OpService nodes</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Op.html" title="interface in com.hp.hpl.jena.sparql.algebra">Op</a></code></td>
<td class="colLast"><span class="strong">Transformer.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Transformer.html#transformSkipService(com.hp.hpl.jena.sparql.algebra.Transform, com.hp.hpl.jena.sparql.algebra.Op, com.hp.hpl.jena.sparql.algebra.OpVisitor, com.hp.hpl.jena.sparql.algebra.OpVisitor)">transformSkipService</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Transform.html" title="interface in com.hp.hpl.jena.sparql.algebra">Transform</a> transform,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Op.html" title="interface in com.hp.hpl.jena.sparql.algebra">Op</a> op,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> beforeVisitor,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> afterVisitor)</code>
<div class="block">Transform an algebra expression except skip (leave alone) any OpService nodes</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">Op.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Op.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><span class="strong">OpWalker.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpWalker.html#walk(com.hp.hpl.jena.sparql.algebra.Op, com.hp.hpl.jena.sparql.algebra.OpVisitor)">walk</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Op.html" title="interface in com.hp.hpl.jena.sparql.algebra">Op</a> op,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> visitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><span class="strong">OpWalker.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpWalker.html#walk(com.hp.hpl.jena.sparql.algebra.Op, com.hp.hpl.jena.sparql.algebra.OpVisitor, com.hp.hpl.jena.sparql.algebra.OpVisitor, com.hp.hpl.jena.sparql.algebra.OpVisitor)">walk</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Op.html" title="interface in com.hp.hpl.jena.sparql.algebra">Op</a> op,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> visitor,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> beforeVisitor,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> afterVisitor)</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/package-summary.html">com.hp.hpl.jena.sparql.algebra</a> with parameters of type <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/BeforeAfterVisitor.html#BeforeAfterVisitor(com.hp.hpl.jena.sparql.algebra.OpVisitor, com.hp.hpl.jena.sparql.algebra.OpVisitor, com.hp.hpl.jena.sparql.algebra.OpVisitor)">BeforeAfterVisitor</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> mainVisitor,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> beforeVisitor,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> afterVisitor)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.hp.hpl.jena.sparql.algebra.op">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> in <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/package-summary.html">com.hp.hpl.jena.sparql.algebra.op</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/package-summary.html">com.hp.hpl.jena.sparql.algebra.op</a> with parameters of type <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpTriple.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpTriple.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpTopN.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpTopN.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpExt.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpExt.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpSequence.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpSequence.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpConditional.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpConditional.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpBGP.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpBGP.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpGroup.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpGroup.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpDiff.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpDiff.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpGraph.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpGraph.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpService.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpService.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpTable.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpTable.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpProcedure.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpProcedure.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpQuad.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpQuad.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpJoin.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpJoin.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpQuadPattern.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpQuadPattern.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpDatasetNames.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpDatasetNames.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpUnion.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpUnion.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpPath.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpPath.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpReduced.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpReduced.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpList.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpList.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpNull.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpNull.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpOrder.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpOrder.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpAssign.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpAssign.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpQuadBlock.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpQuadBlock.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpMinus.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpMinus.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpLeftJoin.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpLeftJoin.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpSlice.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpSlice.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpPropFunc.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpPropFunc.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpLabel.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpLabel.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpProject.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpProject.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpDisjunction.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpDisjunction.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpDistinct.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpDistinct.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpFilter.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpFilter.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">OpExtend.</span><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/op/OpExtend.html#visit(com.hp.hpl.jena.sparql.algebra.OpVisitor)">visit</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> opVisitor)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.hp.hpl.jena.sparql.algebra.optimize">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> in <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/optimize/package-summary.html">com.hp.hpl.jena.sparql.algebra.optimize</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/optimize/package-summary.html">com.hp.hpl.jena.sparql.algebra.optimize</a> that implement <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/optimize/OpVisitorExprPrepare.html" title="class in com.hp.hpl.jena.sparql.algebra.optimize">OpVisitorExprPrepare</a></strong></code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/optimize/package-summary.html">com.hp.hpl.jena.sparql.algebra.optimize</a> with parameters of type <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/optimize/ExprTransformApplyTransform.html#ExprTransformApplyTransform(com.hp.hpl.jena.sparql.algebra.Transform, com.hp.hpl.jena.sparql.algebra.OpVisitor, com.hp.hpl.jena.sparql.algebra.OpVisitor)">ExprTransformApplyTransform</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/Transform.html" title="interface in com.hp.hpl.jena.sparql.algebra">Transform</a> transform,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> beforeVisitor,
<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> afterVisitor)</code> </td>
</tr>
<tr class="rowColor">
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/optimize/ExprVisitorApplyVisitor.html#ExprVisitorApplyVisitor(com.hp.hpl.jena.sparql.algebra.OpVisitor)">ExprVisitorApplyVisitor</a></strong>(<a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> visitor)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.hp.hpl.jena.sparql.engine.ref">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> in <a href="../../../../../../../com/hp/hpl/jena/sparql/engine/ref/package-summary.html">com.hp.hpl.jena.sparql.engine.ref</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../com/hp/hpl/jena/sparql/engine/ref/package-summary.html">com.hp.hpl.jena.sparql.engine.ref</a> that implement <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/engine/ref/EvaluatorDispatch.html" title="class in com.hp.hpl.jena.sparql.engine.ref">EvaluatorDispatch</a></strong></code>
<div class="block">Class to provide type-safe eval() dispatch using the visitor support of Op</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.hp.hpl.jena.sparql.sse.writers">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a> in <a href="../../../../../../../com/hp/hpl/jena/sparql/sse/writers/package-summary.html">com.hp.hpl.jena.sparql.sse.writers</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../com/hp/hpl/jena/sparql/sse/writers/package-summary.html">com.hp.hpl.jena.sparql.sse.writers</a> that implement <a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">OpVisitor</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/hp/hpl/jena/sparql/sse/writers/WriterOp.OpWriterWorker.html" title="class in com.hp.hpl.jena.sparql.sse.writers">WriterOp.OpWriterWorker</a></strong></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/hp/hpl/jena/sparql/algebra/OpVisitor.html" title="interface in com.hp.hpl.jena.sparql.algebra">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/hp/hpl/jena/sparql/algebra/class-use/OpVisitor.html" target="_top">Frames</a></li>
<li><a href="OpVisitor.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p>
</body>
</html>
|
vuk/Clojure-Movies
|
resources/apache-jena/javadoc-arq/com/hp/hpl/jena/sparql/algebra/class-use/OpVisitor.html
|
HTML
|
epl-1.0
| 41,686
|
package org.opendaylight.controller.sal.match.extensible;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.opendaylight.controller.sal.utils.NetUtils;
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class NwDst extends MatchField<InetAddress> {
private static final long serialVersionUID = 1L;
public static final String TYPE = "NW_DST";
private InetAddress address;
private InetAddress mask;
/**
* Creates a Match field for the network destination address
*
* @param address
* the network address
* @param mask
* the network mask
*/
public NwDst(InetAddress address, InetAddress mask) {
super(TYPE);
this.address = address;
this.mask = mask;
}
// To satisfy JAXB
private NwDst() {
super(TYPE);
}
public NwDst(InetAddress address) {
super(TYPE);
this.address = address;
this.mask = null;
}
@Override
public InetAddress getValue() {
return address;
}
@Override
@XmlElement(name = "value")
protected String getValueString() {
return address.getHostAddress();
}
@Override
public InetAddress getMask() {
return mask;
}
@Override
@XmlElement(name = "mask")
protected String getMaskString() {
return (mask == null) ? "null" : mask.getHostAddress();
}
@Override
public boolean isValid() {
if (address != null) {
if (mask != null) {
return address instanceof Inet4Address && mask instanceof Inet4Address
|| address instanceof Inet6Address && mask instanceof Inet6Address;
}
return true;
}
return false;
}
@Override
public boolean hasReverse() {
return true;
}
@Override
public NwSrc getReverse() {
return new NwSrc(address, mask);
}
@Override
public NwDst clone() {
return new NwDst(address, mask);
}
@Override
public boolean isV6() {
return address instanceof Inet6Address;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((mask == null) ? 0 : mask.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof NwDst)) {
return false;
}
NwDst other = (NwDst) obj;
// Equality to be checked against prefix addresses
int thisMaskLen = (this.mask == null) ? ((this.address instanceof Inet4Address) ? 32 : 128) : NetUtils
.getSubnetMaskLength(this.mask);
int otherMaskLen = (other.mask == null) ? ((other.address instanceof Inet4Address) ? 32 : 128) : NetUtils
.getSubnetMaskLength(other.mask);
return NetUtils.getSubnetPrefix(address, thisMaskLen).equals(
NetUtils.getSubnetPrefix(other.address, otherMaskLen));
}
}
|
niuqg/controller
|
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwDst.java
|
Java
|
epl-1.0
| 3,485
|
/*===========================================================================*/
/* */
/* This file is part of the SYMPHONY Branch, Cut, and Price Library. */
/* */
/* SYMPHONY was jointly developed by Ted Ralphs (ted@lehigh.edu) and */
/* Laci Ladanyi (ladanyi@us.ibm.com). */
/* */
/* (c) Copyright 2000-2013 Ted Ralphs. All Rights Reserved. */
/* */
/* This software is licensed under the Eclipse Public License. Please see */
/* accompanying file for terms. */
/* */
/*===========================================================================*/
#ifndef _USER_H
#define _USER_H
/*---------------------------------------------------------------------------*\
* Use this data structure to store the value of any run-time parameters.
\*---------------------------------------------------------------------------*/
typedef struct USER_PARAMETERS {
/* Name of file containing the instance data */
char infile[MAX_FILE_NAME_LENGTH + 1];
} user_parameters;
/*---------------------------------------------------------------------------*\
* Use this data structure to store the instance data after it is read in.
\*---------------------------------------------------------------------------*/
typedef struct USER_PROBLEM {
int colnum; /* Number of columns in base matrix */
int rownum; /* Number of rows in base matrix */
user_parameters par; /* Parameters */
// number of cones
int num_cones;
// type of cone 0 for LORENTZ cone and 1 for ROTATED LORENTZ cone
int * cone_type;
int * cone_size;
int ** cone_members;
char * is_int;
double * curr_solution;
} user_problem;
#endif
|
tkralphs/SYMPHONY
|
SYMPHONY/Applications/MISOCO/include/user.h
|
C
|
epl-1.0
| 2,138
|
/*-
*******************************************************************************
* Copyright (c) 2011, 2017 Diamond Light Source Ltd.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Gerring - initial API and implementation and/or initial documentation
* Baha El-Kassaby - Removal of IHierchicalDataFile and HObject usage
*******************************************************************************/
package org.eclipse.dawnsci.hdf5.editor;
import java.text.DecimalFormat;
import java.util.Arrays;
import org.eclipse.dawnsci.analysis.api.tree.Attribute;
import org.eclipse.dawnsci.analysis.api.tree.DataNode;
import org.eclipse.dawnsci.analysis.api.tree.GroupNode;
import org.eclipse.dawnsci.analysis.api.tree.Node;
import org.eclipse.dawnsci.analysis.api.tree.NodeLink;
import org.eclipse.january.dataset.IDataset;
import org.eclipse.january.dataset.ILazyDataset;
import org.eclipse.january.dataset.StringDataset;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.swt.graphics.Image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class H5LabelProvider extends ColumnLabelProvider implements ITableLabelProvider {
private static final Logger logger = LoggerFactory.getLogger(H5LabelProvider.class);
public H5LabelProvider() {
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
// TODO Auto-generated method stub
return null;
}
/**
* { "Name", "Class", "Dims", "Type", "Size" };
*/
@Override
public String getColumnText(Object element, int columnIndex) {
if (element == null)
return null;
Object object = null;
if (element instanceof Attribute) {
object = (Attribute) element;
} else if (element instanceof NodeLink) {
object = (NodeLink) element;
} else {
return null;
}
switch(columnIndex) {
case 0:
if(object instanceof Attribute)
return ((Attribute)object).getName();
else if (object instanceof NodeLink)
return ((NodeLink)object).getName();
return "";
case 1:
if(object instanceof Attribute)
return "Attribute";
else if (object instanceof NodeLink) {
Node node = ((NodeLink)object).getDestination();
if (node instanceof GroupNode) {
return "Group";
} else if (node instanceof DataNode) {
return "Dataset";
} else {
return object.getClass().getConstructors()[0].getName();
}
}
return "";
case 2:
if (object instanceof NodeLink) {
Node node = ((NodeLink)object).getDestination();
if (node instanceof DataNode) {
DataNode datanode = (DataNode) node;
int[] shape = datanode.getDataset().getShape();
if (shape==null) return "";
return Arrays.toString(shape);
}
}
return "";
case 3:
if (object instanceof NodeLink) {
Node node = ((NodeLink)object).getDestination();
if (node instanceof DataNode) {
DataNode datanode = (DataNode) node;
String typename = datanode.getTypeName();
return ""+typename;
}
}
return "";
case 4:
if (object instanceof NodeLink) {
Node node = ((NodeLink)object).getDestination();
if (node instanceof DataNode) {
DataNode datanode = (DataNode) node;
ILazyDataset lazy = datanode.getDataset();
long memSize = getSize(lazy);
if (memSize<0) return "";
return formatSize(memSize);
}
}
return "";
default:
return null;
}
}
private long getSize(ILazyDataset data) {
try {
IDataset slice = data.getSlice();
int bpi = slice.getItemBytes();
if (bpi != 0) {
int[] shape = slice.getShape();
if (shape == null)
return -1;
long size = shape[0];
for (int i = 1; i < shape.length; i++)
size *= shape[i];
return bpi * size;
} else {
if (slice instanceof StringDataset) {
StringDataset strdata = (StringDataset) slice;
String[] dataArray = strdata.getData();
String string = dataArray[0];
long size = string.length();
return size;
}
return -1;
}
} catch (Exception e) {
logger.debug("Error getting size:" + e.getMessage());
return -1;
}
}
private static final double BASE = 1024, KB = BASE, MB = KB * BASE, GB = MB * BASE;
private static final DecimalFormat df = new DecimalFormat("#.##");
public static String formatSize(double size) {
if (size >= GB) {
return df.format(size / GB) + " GB";
}
if (size >= MB) {
return df.format(size / MB) + " MB";
}
if (size >= KB) {
return df.format(size / KB) + " KB";
}
return "" + (int) size + " bytes";
}
@Override
public void dispose() {
}
}
|
belkassaby/dawnsci
|
org.eclipse.dawnsci.hdf5.editor/src/org/eclipse/dawnsci/hdf5/editor/H5LabelProvider.java
|
Java
|
epl-1.0
| 4,846
|
package org.eclipse.birt.report.designer.internal.ui.ide.propertyeditor;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.HyperLinkDescriptorProvider;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.dialogs.HyperlinkBuilder;
import org.eclipse.birt.report.designer.ui.util.ExceptionUtil;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.ActionHandle;
import org.eclipse.birt.report.model.api.CommandStack;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.ui.PlatformUI;
public class IDEHyperLinkDescriptorProvider extends HyperLinkDescriptorProvider
{
public boolean hyperLinkSelected( )
{
boolean flag = true;
HyperlinkBuilder dialog = new HyperlinkBuilder( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ) ,true );
getActionStack( ).startTrans( Messages.getString( "HyperLinkPage.Menu.Save" ) ); //$NON-NLS-1$
ActionHandle handle = getActionHandle( );
if ( handle == null )
{
try
{
handle = DEUtil.setAction( (ReportItemHandle) DEUtil.getInputFirstElement( input ),
StructureFactory.createAction( ) );
}
catch ( SemanticException e1 )
{
getActionStack( ).rollback( );
ExceptionUtil.handle( e1 );
return false;
}
}
dialog.setInput( handle );
boolean isOK = dialog.open( ) == Dialog.OK;
if ( isOK )
{
getActionStack( ).commit( );
flag = true;
}
else
{
getActionStack( ).rollback( );
flag = false;
}
return flag;
}
public boolean hyperLinkDeleted( )
{
ActionHandle handle = getActionHandle( );
if ( handle != null )
{
getActionStack( ).startTrans(
Messages.getString( "HyperLinkPage.Menu.Save" ) ); //$NON-NLS-1$
try
{
handle.drop( );
}
catch ( SemanticException e1 )
{
getActionStack( ).rollback( );
ExceptionUtil.handle( e1 );
return false;
}
getActionStack( ).commit( );
return true;
}
return false;
}
private CommandStack getActionStack( )
{
return SessionHandleAdapter.getInstance( ).getCommandStack( );
}
private ActionHandle getActionHandle( )
{
return DEUtil.getActionHandle( (ReportItemHandle) DEUtil.getInputFirstElement( input ) );
}
}
|
sguan-actuate/birt
|
UI/org.eclipse.birt.report.designer.ui.ide/src/org/eclipse/birt/report/designer/internal/ui/ide/propertyeditor/IDEHyperLinkDescriptorProvider.java
|
Java
|
epl-1.0
| 2,711
|
/*******************************************************************************
* Copyright (c) 2004, 2010 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.chart.style;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.attribute.ColorDefinition;
import org.eclipse.birt.chart.model.attribute.StyledComponent;
/**
* This interface allows access/manipulation to styles for granular chart
* components.
*/
public interface IStyleProcessor
{
/**
* Returns the style as per given component name.
*
* @param name
* @return style element
*/
IStyle getStyle( Chart model, StyledComponent name );
/**
* Process styles for the whole chart model
*
* @param model
* chart model
* @since 2.6
*/
void processStyle( Chart model );
/**
* To set the default background color.
*
* @param color
* default background color
*/
void setDefaultBackgroundColor( ColorDefinition cd );
/**
* Get the default background color.
*
* @return color
*/
ColorDefinition getDefaultBackgroundColor( );
/**
* Use custom value to update chart model.
*
* @param model
* the target chart model.
* @param obj
* this object is used to update chart model.
*
* @return <code>true</code> means updated successfully.
*/
boolean updateChart( Chart model, Object obj );
/**
* Indicates if chart need to inherit some basic styles from container.
*
* @return
*/
boolean needInheritingStyles( );
}
|
Charling-Huang/birt
|
chart/org.eclipse.birt.chart.engine/src/org/eclipse/birt/chart/style/IStyleProcessor.java
|
Java
|
epl-1.0
| 1,935
|
/*
* Licensed Materials - Property of IBM
* © Copyright IBM Corporation 2015. All Rights Reserved.
*/
package com.ibm.mil.readyapps.summit.utilities;
import android.content.Context;
import java.io.IOException;
import java.util.Properties;
/**
* Helper class for retrieving values from a Worklight client property file.
*
* @author John Petitto
*/
public final class WLPropertyReader {
private static final String FILE_NAME = "wlclient.properties";
private static Properties properties;
/**
* The properties are read into memory on the initial creation of this class and then re-used
* on successive initializations.
*
* @param context
*/
public WLPropertyReader(Context context) {
if (properties == null) {
properties = new Properties();
try {
properties.load(context.getAssets().open(FILE_NAME));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String serverProtocol() {
return properties.getProperty("wlServerProtocol");
}
public String serverHost() {
return properties.getProperty("wlServerHost");
}
public String serverPort() {
return properties.getProperty("wlServerPort");
}
public String serverContext() {
return properties.getProperty("wlServerContext");
}
public String appId() {
return properties.getProperty("wlAppId");
}
public String appVersion() {
return properties.getProperty("wlAppVersion");
}
public String environment() {
return properties.getProperty("wlEnvironment");
}
public String uniqueId() {
return properties.getProperty("wlUid");
}
public String platformVersion() {
return properties.getProperty("wlPlatformVersion");
}
/**
* A helper method for returning the full WL server URL with proper formatting.
*
* @return A properly formatted server URL for the WL connection.
*/
public String serverUrl() {
return serverProtocol() + "://" + serverHost() + ":" + serverPort() + serverContext();
}
}
|
IBM-MIL/IBM-Ready-App-for-Retail
|
Android/app/src/main/java/com/ibm/mil/readyapps/summit/utilities/WLPropertyReader.java
|
Java
|
epl-1.0
| 2,181
|
/*************************************************************************************
* Copyright (c) 2004 Actuate Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - Initial implementation.
************************************************************************************/
package org.eclipse.birt.report.designer.ui.editors;
public interface IPageStaleType
{
/**
* None stale type.
*/
int NONE = 0;
/**
* Model had change stale type.
*/
int MODEL_CHANGED = 1;
/**
* Code had change stale type.
*/
int CODE_CHANGED = 2;
int MODEL_RELOAD = 4;
}
|
sguan-actuate/birt
|
UI/org.eclipse.birt.report.designer.ui.editors/src/org/eclipse/birt/report/designer/ui/editors/IPageStaleType.java
|
Java
|
epl-1.0
| 850
|
/***********************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
***********************************************************************/
package org.eclipse.birt.chart.examples.view.models;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.attribute.Anchor;
import org.eclipse.birt.chart.model.attribute.Angle3D;
import org.eclipse.birt.chart.model.attribute.AxisType;
import org.eclipse.birt.chart.model.attribute.ChartDimension;
import org.eclipse.birt.chart.model.attribute.IntersectionType;
import org.eclipse.birt.chart.model.attribute.LineAttributes;
import org.eclipse.birt.chart.model.attribute.LineStyle;
import org.eclipse.birt.chart.model.attribute.Orientation;
import org.eclipse.birt.chart.model.attribute.Position;
import org.eclipse.birt.chart.model.attribute.TickStyle;
import org.eclipse.birt.chart.model.attribute.impl.Angle3DImpl;
import org.eclipse.birt.chart.model.attribute.impl.ColorDefinitionImpl;
import org.eclipse.birt.chart.model.attribute.impl.LineAttributesImpl;
import org.eclipse.birt.chart.model.attribute.impl.Rotation3DImpl;
import org.eclipse.birt.chart.model.component.Axis;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.component.impl.AxisImpl;
import org.eclipse.birt.chart.model.component.impl.SeriesImpl;
import org.eclipse.birt.chart.model.data.BaseSampleData;
import org.eclipse.birt.chart.model.data.DataFactory;
import org.eclipse.birt.chart.model.data.NumberDataSet;
import org.eclipse.birt.chart.model.data.OrthogonalSampleData;
import org.eclipse.birt.chart.model.data.SampleData;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.data.TextDataSet;
import org.eclipse.birt.chart.model.data.impl.NumberDataSetImpl;
import org.eclipse.birt.chart.model.data.impl.SeriesDefinitionImpl;
import org.eclipse.birt.chart.model.data.impl.TextDataSetImpl;
import org.eclipse.birt.chart.model.impl.ChartWithAxesImpl;
import org.eclipse.birt.chart.model.layout.Legend;
import org.eclipse.birt.chart.model.type.AreaSeries;
import org.eclipse.birt.chart.model.type.impl.AreaSeriesImpl;
public class Area
{
public static final Chart createArea( )
{
ChartWithAxes cwa3DArea = ChartWithAxesImpl.create( );
cwa3DArea.setDimension( ChartDimension.THREE_DIMENSIONAL_LITERAL );
cwa3DArea.setType( "Area Chart" ); //$NON-NLS-1$
cwa3DArea.setSubType( "Overlay" ); //$NON-NLS-1$
// Title
cwa3DArea.getBlock( ).setBackground( ColorDefinitionImpl.WHITE( ) );
cwa3DArea.getTitle( ).getLabel( ).getCaption( ).setValue( "3D Area Chart" );//$NON-NLS-1$
cwa3DArea.getTitle( ).setVisible( true );
// Legend
Legend lg = cwa3DArea.getLegend( );
LineAttributes lia = lg.getOutline( );
lg.getText( ).getFont( ).setSize( 16 );
lia.setStyle( LineStyle.SOLID_LITERAL );
lg.getInsets( ).set( 10, 5, 0, 0 );
lg.getOutline( ).setVisible( false );
lg.setAnchor( Anchor.NORTH_LITERAL );
// X-Axis
Axis xAxisPrimary = cwa3DArea.getPrimaryBaseAxes( )[0];
xAxisPrimary.setType( AxisType.TEXT_LITERAL );
xAxisPrimary.getMajorGrid( ).setTickStyle( TickStyle.BELOW_LITERAL );
xAxisPrimary.getMajorGrid( )
.setLineAttributes( LineAttributesImpl.create( ColorDefinitionImpl.BLUE( ),
LineStyle.SOLID_LITERAL,
1 ) );
xAxisPrimary.getMinorGrid( ).getLineAttributes( ).setVisible( true );
xAxisPrimary.getOrigin( ).setType( IntersectionType.MIN_LITERAL );
// Y-Axis
Axis yAxisPrimary = cwa3DArea.getPrimaryOrthogonalAxis( xAxisPrimary );
yAxisPrimary.getMajorGrid( ).setTickStyle( TickStyle.LEFT_LITERAL );
yAxisPrimary.getMajorGrid( )
.setLineAttributes( LineAttributesImpl.create( ColorDefinitionImpl.BLACK( ),
LineStyle.SOLID_LITERAL,
1 ) );
yAxisPrimary.getMinorGrid( ).getLineAttributes( ).setVisible( true );
yAxisPrimary.setPercent( false );
// Z-Axis
Axis zAxis = AxisImpl.create( Axis.ANCILLARY_BASE );
zAxis.setType( AxisType.TEXT_LITERAL );
zAxis.setLabelPosition( Position.BELOW_LITERAL );
zAxis.setTitlePosition( Position.BELOW_LITERAL );
zAxis.getMajorGrid( ).setTickStyle( TickStyle.BELOW_LITERAL );
zAxis.setOrientation( Orientation.HORIZONTAL_LITERAL );
xAxisPrimary.getAncillaryAxes( ).add( zAxis );
// Data Set
TextDataSet categoryValues = TextDataSetImpl.create( new String[]{
"Jan.", "Feb.", "Mar.", "Apr", "May"} ); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$//$NON-NLS-5$
NumberDataSet orthoValues1 = NumberDataSetImpl.create( new double[]{
14.32, -19.5, 8.38, 0.34, 9.22
} );
NumberDataSet orthoValues2 = NumberDataSetImpl.create( new double[]{
4.55, 2.61, -3.18, 14.2, 10.22
} );
// X-Series
Series seCategory = SeriesImpl.create( );
seCategory.setDataSet( categoryValues );
SeriesDefinition sdX = SeriesDefinitionImpl.create( );
sdX.getSeriesPalette( ).shift( 0 );
xAxisPrimary.getSeriesDefinitions( ).add( sdX );
sdX.getSeries( ).add( seCategory );
SampleData sd = DataFactory.eINSTANCE.createSampleData( );
BaseSampleData sdBase = DataFactory.eINSTANCE.createBaseSampleData( );
sdBase.setDataSetRepresentation( "" );//$NON-NLS-1$
sd.getBaseSampleData( ).add( sdBase );
OrthogonalSampleData sdOrthogonal1 = DataFactory.eINSTANCE.createOrthogonalSampleData( );
sdOrthogonal1.setDataSetRepresentation( "" );//$NON-NLS-1$
sdOrthogonal1.setSeriesDefinitionIndex( 0 );
sd.getOrthogonalSampleData( ).add( sdOrthogonal1 );
OrthogonalSampleData sdOrthogonal2 = DataFactory.eINSTANCE.createOrthogonalSampleData( );
sdOrthogonal2.setDataSetRepresentation( "" );//$NON-NLS-1$
sdOrthogonal2.setSeriesDefinitionIndex( 1 );
sd.getOrthogonalSampleData( ).add( sdOrthogonal2 );
cwa3DArea.setSampleData( sd );
// Y-Series (1)
AreaSeries as1 = (AreaSeries) AreaSeriesImpl.create( );
as1.setSeriesIdentifier( "Series 1" );//$NON-NLS-1$
as1.setDataSet( orthoValues1 );;
as1.getLineAttributes( ).setVisible( false );
as1.getLabel( ).setVisible( true );
// Y-Series (2)
AreaSeries as2 = (AreaSeries) AreaSeriesImpl.create( );
as2.setSeriesIdentifier( "Series 2" );//$NON-NLS-1$
as2.setDataSet( orthoValues2 );
as2.getLineAttributes( ).setVisible( false );
as2.getLabel( ).setVisible( true );
SeriesDefinition sdY = SeriesDefinitionImpl.create( );
sdY.getSeriesPalette( ).shift( -1 );
yAxisPrimary.getSeriesDefinitions( ).add( sdY );
sdY.getSeries( ).add( as1 );
sdY.getSeries( ).add( as2 );
// Z-Series
SeriesDefinition sdZ = SeriesDefinitionImpl.create( );
zAxis.getSeriesDefinitions( ).add( sdZ );
// Rotate the chart
cwa3DArea.setRotation( Rotation3DImpl.create( new Angle3D[]{
Angle3DImpl.create( -10, 25, 0 )
} ) );
return cwa3DArea;
}
}
|
Charling-Huang/birt
|
chart/org.eclipse.birt.chart.examples/src/org/eclipse/birt/chart/examples/view/models/Area.java
|
Java
|
epl-1.0
| 7,151
|
package p;
public class Thing {
private Thing[] subthings;
public Thing() {
subthings = new Thing[] {};
}
private /*[*//*]*/Thing(Thing... subthings) {
this.subthings = subthings;
}
public static void main(String args[]) {
System.out.println(createThing(createThing(new Thing()), createThing(new Thing())).subthings.length);
}
public static Thing createThing(Thing... subthings) {
return new Thing(subthings);
}
}
|
maxeler/eclipse
|
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/Bugzilla/298281/Thing_out.java
|
Java
|
epl-1.0
| 436
|
/*******************************************************************************
* Copyright (c) 2010 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.csstudio.alarm.beast.msghist.model;
/** Listener gets notified when model changes.
* @author Kay Kasemir
* @author benhadj naceur @ sopra group - iter
*/
public interface ModelListener
{
/** Invoked when the model changed in some way.
* <p>
* <b>Note:</b> Call can originate from non-GUI thread.
*
* @param model Model that has new data or is somehow different
*/
public void modelChanged(Model model);
/**
* Listener on error model.
*
* @param errorMsg the error msg
*/
public void onErrorModel(final String errorMsg);
}
|
ESSICS/cs-studio
|
applications/alarm/alarm-plugins/org.csstudio.alarm.beast.msghist/src/org/csstudio/alarm/beast/msghist/model/ModelListener.java
|
Java
|
epl-1.0
| 1,069
|
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef __OCP_DMI_H
#define __OCP_DMI_H
#include <cpu/x86/msr.h>
#include <device/device.h>
#include <smbios.h>
#define TBF "To Be Filled By O.E.M."
extern msr_t xeon_sp_ppin[];
/* Override SMBIOS type 11 OEM string 1 to string 6 */
void ocp_oem_smbios_strings(struct device *dev, struct smbios_type11 *t);
/* This function allows adding the same repeated string to the table */
int smbios_add_oem_string(u8 *start, const char *str);
#endif
|
felixsinger/coreboot
|
src/drivers/ocp/dmi/ocp_dmi.h
|
C
|
gpl-2.0
| 496
|
<?php
/**
* Dropbox API class
*
* @package Dropbox
* @copyright Copyright (C) 2010 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/dropbox-php/wiki/License MIT
*/
class Dropbox_API {
/**
* Sandbox root-path
*/
const ROOT_SANDBOX = 'sandbox';
/**
* Dropbox root-path
*/
const ROOT_DROPBOX = 'dropbox';
/**
* API URl
*/
protected $api_url = 'https://api.dropbox.com/1/';
/**
* Content API URl
*/
protected $api_content_url = 'https://api-content.dropbox.com/1/';
/**
* OAuth object
*
* @var Dropbox_OAuth
*/
protected $oauth;
/**
* Default root-path, this will most likely be 'sandbox' or 'dropbox'
*
* @var string
*/
protected $root;
protected $useSSL;
/**
* Constructor
*
* @param Dropbox_OAuth Dropbox_Auth object
* @param string $root default root path (sandbox or dropbox)
*/
public function __construct(Dropbox_OAuth $oauth, $root = self::ROOT_DROPBOX, $useSSL = true) {
$this->oauth = $oauth;
$this->root = $root;
$this->useSSL = $useSSL;
if (!$this->useSSL)
{
throw new Dropbox_Exception('Dropbox REST API now requires that all requests use SSL');
}
}
/**
* Returns information about the current dropbox account
*
* @return stdclass
*/
public function getAccountInfo() {
$data = $this->oauth->fetch($this->api_url . 'account/info');
return json_decode($data['body'],true);
}
/**
* Returns a file's contents
*
* @param string $path path
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return string
*/
public function getFile($path = '', $root = null) {
if (is_null($root)) $root = $this->root;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$result = $this->oauth->fetch($this->api_content_url . 'files/' . $root . '/' . ltrim($path,'/'));
return $result['body'];
}
/**
* Uploads a new file
*
* @param string $path Target path (including filename)
* @param string $file Either a path to a file or a stream resource
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return bool
*/
public function putFile($path, $file, $root = null) {
$directory = dirname($path);
$filename = basename($path);
if($directory==='.') $directory = '';
$directory = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($directory));
// $filename = str_replace('~', '%7E', rawurlencode($filename));
if (is_null($root)) $root = $this->root;
if (is_string($file)) {
$file = fopen($file,'rb');
} elseif (!is_resource($file)) {
throw new Dropbox_Exception('File must be a file-resource or a string');
}
$result=$this->multipartFetch($this->api_content_url . 'files/' .
$root . '/' . trim($directory,'/'), $file, $filename);
if(!isset($result["httpStatus"]) || $result["httpStatus"] != 200)
throw new Dropbox_Exception("Uploading file to Dropbox failed");
return true;
}
/**
* Copies a file or directory from one location to another
*
* This method returns the file information of the newly created file.
*
* @param string $from source path
* @param string $to destination path
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return stdclass
*/
public function copy($from, $to, $root = null) {
if (is_null($root)) $root = $this->root;
$response = $this->oauth->fetch($this->api_url . 'fileops/copy', array('from_path' => $from, 'to_path' => $to, 'root' => $root), 'POST');
return json_decode($response['body'],true);
}
/**
* Creates a new folder
*
* This method returns the information from the newly created directory
*
* @param string $path
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return stdclass
*/
public function createFolder($path, $root = null) {
if (is_null($root)) $root = $this->root;
// Making sure the path starts with a /
// $path = '/' . ltrim($path,'/');
$response = $this->oauth->fetch($this->api_url . 'fileops/create_folder', array('path' => $path, 'root' => $root),'POST');
return json_decode($response['body'],true);
}
/**
* Deletes a file or folder.
*
* This method will return the metadata information from the deleted file or folder, if successful.
*
* @param string $path Path to new folder
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return array
*/
public function delete($path, $root = null) {
if (is_null($root)) $root = $this->root;
$response = $this->oauth->fetch($this->api_url . 'fileops/delete', array('path' => $path, 'root' => $root), 'POST');
return json_decode($response['body']);
}
/**
* Moves a file or directory to a new location
*
* This method returns the information from the newly created directory
*
* @param mixed $from Source path
* @param mixed $to destination path
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return stdclass
*/
public function move($from, $to, $root = null) {
if (is_null($root)) $root = $this->root;
$response = $this->oauth->fetch($this->api_url . 'fileops/move', array('from_path' => rawurldecode($from), 'to_path' => rawurldecode($to), 'root' => $root), 'POST');
return json_decode($response['body'],true);
}
/**
* Returns file and directory information
*
* @param string $path Path to receive information from
* @param bool $list When set to true, this method returns information from all files in a directory. When set to false it will only return infromation from the specified directory.
* @param string $hash If a hash is supplied, this method simply returns true if nothing has changed since the last request. Good for caching.
* @param int $fileLimit Maximum number of file-information to receive
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return array|true
*/
public function getMetaData($path, $list = true, $hash = null, $fileLimit = null, $root = null) {
if (is_null($root)) $root = $this->root;
$args = array(
'list' => $list,
);
if (!is_null($hash)) $args['hash'] = $hash;
if (!is_null($fileLimit)) $args['file_limit'] = $fileLimit;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$response = $this->oauth->fetch($this->api_url . 'metadata/' . $root . '/' . ltrim($path,'/'), $args);
/* 304 is not modified */
if ($response['httpStatus']==304) {
return true;
} else {
return json_decode($response['body'],true);
}
}
/**
* A way of letting you keep up with changes to files and folders in a user's Dropbox. You can periodically call /delta to get a list of "delta entries", which are instructions on how to update your local state to match the server's state.
*
* This method returns the information from the newly created directory
*
* @param string $cursor A string that is used to keep track of your current state. On the next call pass in this value to return delta entries that have been recorded since the cursor was returned.
* @return stdclass
*/
public function delta($cursor) {
$arg['cursor'] = $cursor;
$response = $this->oauth->fetch($this->api_url . 'delta', $arg, 'POST');
return json_decode($response['body'],true);
}
/**
* Returns a thumbnail (as a string) for a file path.
*
* @param string $path Path to file
* @param string $size small, medium or large
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @return string
*/
public function getThumbnail($path, $size = 'small', $root = null) {
if (is_null($root)) $root = $this->root;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$response = $this->oauth->fetch($this->api_content_url . 'thumbnails/' . $root . '/' . ltrim($path,'/'),array('size' => $size));
return $response['body'];
}
/**
* This method is used to generate multipart POST requests for file upload
*
* @param string $uri
* @param array $arguments
* @return bool
*/
protected function multipartFetch($uri, $file, $filename) {
/* random string */
$boundary = 'R50hrfBj5JYyfR3vF3wR96GPCC9Fd2q2pVMERvEaOE3D8LZTgLLbRpNwXek3';
$headers = array(
'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
);
$body="--" . $boundary . "\r\n";
$body.="Content-Disposition: form-data; name=file; filename=".rawurldecode($filename)."\r\n";
$body.="Content-type: application/octet-stream\r\n";
$body.="\r\n";
$body.=stream_get_contents($file);
$body.="\r\n";
$body.="--" . $boundary . "--";
// Dropbox requires the filename to also be part of the regular arguments, so it becomes
// part of the signature.
$uri.='?file=' . $filename;
return $this->oauth->fetch($uri, $body, 'POST', $headers);
}
/**
* Search
*
* Returns metadata for all files and folders that match the search query.
*
* @added by: diszo.sasil
*
* @param string $query
* @param string $root Use this to override the default root path (sandbox/dropbox)
* @param string $path
* @return array
*/
public function search($query = '', $root = null, $path = ''){
if (is_null($root)) $root = $this->root;
if(!empty($path)){
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
}
$response = $this->oauth->fetch($this->api_url . 'search/' . $root . '/' . ltrim($path,'/'),array('query' => $query));
return json_decode($response['body'],true);
}
/**
* Creates and returns a shareable link to files or folders.
*
* Note: Links created by the /shares API call expire after thirty days.
*
* @param type $path
* @param type $root
* @return type
*/
public function share($path, $root = null) {
if (is_null($root)) $root = $this->root;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$response = $this->oauth->fetch($this->api_url. 'shares/'. $root . '/' . ltrim($path, '/'), array(), 'POST');
return json_decode($response['body'],true);
}
/**
* Returns a link directly to a file.
* Similar to /shares. The difference is that this bypasses the Dropbox webserver, used to provide a preview of the file, so that you can effectively stream the contents of your media.
*
* Note: The /media link expires after four hours, allotting enough time to stream files, but not enough to leave a connection open indefinitely.
*
* @param type $path
* @param type $root
* @return type
*/
public function media($path, $root = null) {
if (is_null($root)) $root = $this->root;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$response = $this->oauth->fetch($this->api_url. 'media/'. $root . '/' . ltrim($path, '/'), array(), 'POST');
return json_decode($response['body'],true);
}
/**
* Creates and returns a copy_ref to a file. This reference string can be used to copy that file to another user's Dropbox by passing it in as the from_copy_ref parameter on /fileops/copy.
*
* @param type $path
* @param type $root
* @return type
*/
public function copy_ref($path, $root = null) {
if (is_null($root)) $root = $this->root;
$path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
$response = $this->oauth->fetch($this->api_url. 'copy_ref/'. $root . '/' . ltrim($path, '/'));
return json_decode($response['body'],true);
}
}
|
MARFMS/OwnCloud_NAC
|
3rdparty/Dropbox/API.php
|
PHP
|
gpl-2.0
| 13,179
|
<?php
/**
* @copyright Copyright (C) 1999-2013 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version //autogentag//
* @package kernel
*/
$http = eZHTTPTool::instance();
$Module = $Params['Module'];
$user = eZUser::currentUser();
$availableHandlers = eZNotificationEventFilter::availableHandlers();
$db = eZDB::instance();
$db->begin();
if ( $http->hasPostVariable( 'Store' ) )
{
foreach ( $availableHandlers as $handler )
{
$handler->storeSettings( $http, $Module );
}
}
foreach ( $availableHandlers as $handler )
{
$handler->fetchHttpInput( $http, $Module );
}
$db->commit();
$viewParameters = array( 'offset' => $Params['Offset'] );
$tpl = eZTemplate::factory();
$tpl->setVariable( 'user', $user );
$tpl->setVariable( 'view_parameters', $viewParameters );
$Result = array();
$Result['content'] = $tpl->fetch( 'design:notification/settings.tpl' );
$Result['path'] = array( array( 'url' => false,
'text' => ezpI18n::tr( 'kernel/notification', 'Notification settings' ) ) );
?>
|
lexxksb/shumoff
|
kernel/notification/settings.php
|
PHP
|
gpl-2.0
| 1,125
|
// Own header:
#include <pgf/gd/interface/c/InterfaceFromC.h>
// Lua stuff:
#include <lauxlib.h>
// C stuff:
#include <stdlib.h>
#include <string.h>
// Remove once Lua Link Bug is fixed:
//
// The following is a hack to avoid a problem with the Lua lib being linked twice.
// When this happens, two version of "dummynode" exist in Lua and we must ensure that
// we never create a table using such a dummynode while using a second lib.
// The following should later be set to 0 and replaced everywhere, once this is fixed.
#define MIN_HASH_SIZE_FIX 1
// Help functions
static void set_field (lua_State* L, const char* what, const char* where)
{
if (what) {
lua_pushstring(L, what);
lua_setfield(L, -2, where);
}
}
static void init_vertex_array(pgfgd_Vertex_array* a, int count)
{
a->length = count;
a->array = (pgfgd_Vertex**) calloc(count, sizeof(pgfgd_Vertex*));
}
static void init_edge_array(pgfgd_Edge_array* a, int count)
{
a->length = count;
a->array = (pgfgd_Edge**) calloc(count, sizeof(pgfgd_Edge*));
}
static void init_arcs_array(pgfgd_Arc_array* arcs, int length)
{
arcs->length = length;
arcs->tails = (int*) calloc(length, sizeof(int));
arcs->heads = (int*) calloc(length, sizeof(int));
}
static void init_path(pgfgd_Path* a, int count)
{
a->length = count;
a->coordinates = (pgfgd_Coordinate*) calloc(count, sizeof(pgfgd_Coordinate));
a->strings = (char**) calloc(count, sizeof(char*));
}
static void clear_path(pgfgd_Path* p)
{
int i;
for (i=0; i < p->length; i++)
free(p->strings[i]);
free(p->strings);
free(p->coordinates);
p->length = 0;
p->strings = 0;
p->coordinates = 0;
}
// Option handling
struct pgfgd_OptionTable {
lua_State* state;
int kind;
int index;
};
// These are the indices of the parameters during a run of the main
// algorithm:
#define GRAPH_INDEX 1
#define VERTICES_INDEX 2
#define EDGES_INDEX 3
#define ALGORITHM_INDEX 4
// This is the index of a special table mapping vertices back to the
// index they have. It is created in the C code, but stays on the
// stack during the computations.
#define BACKINDEX_STORAGE_INDEX 5
// These are the positions of different upvalues for the C closure of
// a C algorithm.
#define FUNCTION_UPVALUE 1
#define USER_UPVALUE 2
#define DIGRAPH_OBJECT_UPVALUE 3
static pgfgd_OptionTable* make_option_table(lua_State* L, int kind, int index)
{
pgfgd_OptionTable* t = (pgfgd_OptionTable*) malloc(sizeof(pgfgd_OptionTable));
t->state = L;
t->kind = kind;
t->index = index;
return t;
}
static void push_option_table(pgfgd_OptionTable* t)
{
switch (t->kind) {
case GRAPH_INDEX:
lua_getfield(t->state, GRAPH_INDEX, "options");
break;
case VERTICES_INDEX:
lua_rawgeti(t->state, VERTICES_INDEX, t->index);
lua_getfield(t->state, -1, "options");
lua_replace(t->state, -2);
break;
case EDGES_INDEX:
lua_rawgeti(t->state, EDGES_INDEX, t->index);
lua_getfield(t->state, -1, "options");
lua_replace(t->state, -2);
break;
}
}
int pgfgd_isset(pgfgd_OptionTable* t, const char* key)
{
push_option_table(t);
lua_getfield(t->state, -1, key);
int is_nil = lua_isnil(t->state, -1);
lua_pop(t->state, 2);
return !is_nil;
}
int pgfgd_isnumber(pgfgd_OptionTable* t, const char* key)
{
push_option_table(t);
lua_getfield(t->state, -1, key);
int is_number = lua_isnumber(t->state, -1);
lua_pop(t->state, 2);
return is_number;
}
int pgfgd_isboolean(pgfgd_OptionTable* t, const char* key)
{
push_option_table(t);
lua_getfield(t->state, -1, key);
int is_bool = lua_isboolean(t->state, -1);
lua_pop(t->state, 2);
return is_bool;
}
int pgfgd_isstring(pgfgd_OptionTable* t, const char* key)
{
push_option_table(t);
lua_getfield(t->state, -1, key);
int is_string = lua_isstring(t->state, -1);
lua_pop(t->state, 2);
return is_string;
}
int pgfgd_isuser(pgfgd_OptionTable* t, const char* key)
{
push_option_table(t);
lua_getfield(t->state, -1, key);
int is_user = lua_isuserdata(t->state, -1);
lua_pop(t->state, 2);
return is_user;
}
double pgfgd_tonumber(pgfgd_OptionTable* t, const char* key)
{
push_option_table(t);
lua_getfield(t->state, -1, key);
double d = lua_tonumber(t->state, -1);
lua_pop(t->state, 2);
return d;
}
int pgfgd_toboolean(pgfgd_OptionTable* t, const char* key)
{
push_option_table(t);
lua_getfield(t->state, -1, key);
int d = lua_toboolean(t->state, -1);
lua_pop(t->state, 2);
return d;
}
char* pgfgd_tostring(pgfgd_OptionTable* t, const char* key)
{
push_option_table(t);
lua_getfield(t->state, -1, key);
const char* s = lua_tostring(t->state, -1);
char* copy = strcpy((char*) malloc(strlen(s)+1), s);
lua_pop(t->state, 2);
return copy;
}
void* pgfgd_touser(pgfgd_OptionTable* t, const char* key)
{
push_option_table(t);
lua_getfield(t->state, -1, key);
void* d = lua_touserdata(t->state, -1);
lua_pop(t->state, 2);
return d;
}
// Handling algorithms
struct pgfgd_SyntacticDigraph_internals {
lua_State* state;
};
static char* make_string_from(lua_State* L, const char* name)
{
lua_getfield(L, -1, name);
if (lua_isnil(L, -1)) {
// Field not set; return emtpy string.
lua_pop(L, 1);
return (char*) calloc(1, sizeof(char));
}
else {
const char* s = lua_tostring(L, -1);
char* copy = strcpy((char*) malloc(strlen(s)+1), s);
lua_pop(L, 1);
return copy;
}
}
static void make_coordinate(lua_State* L, pgfgd_Coordinate* c)
{
lua_getfield(L, -1, "x");
c->x = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_getfield(L, -1, "y");
c->y = lua_tonumber(L, -1);
lua_pop(L, 1);
}
static pgfgd_Path* make_empty_path(lua_State* L)
{
return (pgfgd_Path*) calloc(1, sizeof(pgfgd_Path));
}
static pgfgd_Path* make_path(lua_State* L)
{
/* Path object must be on top of stack. */
pgfgd_Path* p = make_empty_path(L);
// Fill path:
int path_length = lua_rawlen(L, -1);
if (path_length > 0) {
init_path(p, path_length);
int i;
for (i = 0; i < path_length; i++) {
lua_rawgeti(L, -1, i+1);
if (lua_isstring(L, -1)) {
const char* s = lua_tostring(L, -1);
p->strings[i] = strcpy((char*) malloc(strlen(s)+1), s);
} else {
lua_getfield(L, -1, "x");
p->coordinates[i].x = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_getfield(L, -1, "y");
p->coordinates[i].y = lua_tonumber(L, -1);
lua_pop(L, 1);
}
lua_pop(L, 1);
}
}
return p;
}
static void construct_digraph(lua_State* L, pgfgd_SyntacticDigraph* d)
{
d->internals = (pgfgd_SyntacticDigraph_internals*) calloc(1, sizeof(pgfgd_SyntacticDigraph_internals));
d->internals->state = L;
// Create the options table:
d->options = make_option_table(L, GRAPH_INDEX, 0);
// Create the vertex table
init_vertex_array(&d->vertices, lua_rawlen(L, VERTICES_INDEX));
// Create the vertices
int i;
for (i=0; i<d->vertices.length; i++) {
pgfgd_Vertex* v = (pgfgd_Vertex*) calloc(1, sizeof(pgfgd_Vertex));
// Push the vertex onto the Lua stack:
lua_rawgeti(L, VERTICES_INDEX, i+1);
// Fill v with information:
v->name = make_string_from(L, "name");
v->shape = make_string_from(L, "shape");
v->kind = make_string_from(L, "kind");
// Options:
v->options = make_option_table(L, VERTICES_INDEX, i+1);
// Index:
v->array_index = i;
// Setup pos field
lua_getfield(L, -1, "pos");
make_coordinate(L, &v->pos);
lua_pop(L, 1);
// Setup path array:
lua_getfield(L, -1, "path");
v->path = make_path(L);
lua_pop(L, 1);
// Pop the vertex
lua_pop(L, 1);
d->vertices.array[i] = v;
}
// Construct the edges:
init_edge_array(&d->syntactic_edges, lua_rawlen(L, EDGES_INDEX));
int edge_index;
for (edge_index = 0; edge_index < d->syntactic_edges.length; edge_index++) {
pgfgd_Edge* e = (pgfgd_Edge*) calloc(1, sizeof(pgfgd_Edge));
lua_rawgeti(L, EDGES_INDEX, edge_index+1);
e->direction = make_string_from(L, "direction");
e->options = make_option_table(L, EDGES_INDEX, edge_index+1);
// Index:
e->array_index = edge_index;
// Compute the tail vertex index:
lua_getfield(L, -1, "tail");
lua_gettable(L, VERTICES_INDEX);
e->tail = d->vertices.array[lua_tointeger(L, -1) - 1];
lua_pop(L, 1);
lua_getfield(L, -1, "head");
lua_gettable(L, VERTICES_INDEX);
e->head = d->vertices.array[lua_tointeger(L, -1) - 1];
lua_pop(L, 1);
// Fill path:
e->path = make_empty_path(L);
e->path->length = -1; // Means that a default path should be created.
// Pop the edge form the Lua stack:
lua_pop(L, 1);
d->syntactic_edges.array[edge_index] = e;
}
}
static void sync_digraph(lua_State* L, pgfgd_SyntacticDigraph* d)
{
// Writes back the computed position information to the digraph:
int i;
for (i=0; i<d->vertices.length; i++) {
// Push pos field of vertex:
lua_rawgeti(L, VERTICES_INDEX, i+1);
lua_getfield(L, -1, "pos");
// Set x and y coordinates:
pgfgd_Vertex* v = d->vertices.array[i];
lua_pushnumber(L, v->pos.x);
lua_setfield(L, -2, "x");
lua_pushnumber(L, v->pos.y);
lua_setfield(L, -2, "y");
// pop pos and vertex
lua_pop(L, 2);
}
// Write back the paths
int tos = lua_gettop(L);
// First, get "Coordinate.new" as a "local"
lua_getglobal(L, "require");
lua_pushstring(L, "pgf.gd.model.Path");
lua_call(L, 1, 1);
int Path_index = lua_gettop(L);
lua_getglobal(L, "require");
lua_pushstring(L, "pgf.gd.model.Coordinate");
lua_call(L, 1, 1);
lua_getfield(L, -1, "new");
int Coordinate_new_index = lua_gettop(L);
for (i=0; i < d->syntactic_edges.length; i++) {
pgfgd_Edge* e = d->syntactic_edges.array[i];
lua_rawgeti(L, EDGES_INDEX, i+1);
if (e->path->length == -1) {
// Create default path
pgfgd_path_append_moveto_tail(e);
pgfgd_path_append_lineto_head(e);
}
lua_createtable(L, e->path->length ? e->path->length : 1, MIN_HASH_SIZE_FIX);
lua_pushvalue(L, Path_index);
lua_setmetatable(L, -2);
int j;
for (j=0; j<e->path->length; j++) {
if (e->path->strings[j]) {
lua_pushstring(L, e->path->strings[j]);
lua_rawseti(L, -2, j+1);
} else {
lua_pushvalue(L, Coordinate_new_index);
lua_pushnumber(L, e->path->coordinates[j].x);
lua_pushnumber(L, e->path->coordinates[j].y);
lua_call(L, 2, 1);
lua_rawseti(L, -2, j+1);
}
}
lua_setfield(L, -2, "path");
lua_pop(L, 1); // The edge object
}
lua_settop(L, tos); // Cleanup
}
static void free_digraph(pgfgd_SyntacticDigraph* digraph)
{
int i;
for (i=0; i < digraph->vertices.length; i++) {
pgfgd_Vertex* v = digraph->vertices.array[i];
clear_path(v->path);
free(v->path);
free(v->name);
free(v->shape);
free(v->kind);
free(v->options);
free(v->incoming.array);
free(v->outgoing.array);
free(v);
}
for (i=0; i < digraph->syntactic_edges.length; i++) {
pgfgd_Edge* e = digraph->syntactic_edges.array[i];
clear_path(e->path);
free(e->path);
free(e->direction);
free(e->options);
free(e);
}
free(digraph->vertices.array);
free(digraph->syntactic_edges.array);
free(digraph->options);
free(digraph->internals);
free(digraph);
}
static int algorithm_dispatcher(lua_State* L)
{
// Create the back index table. It will be at index BACKINDEX_STORAGE_INDEX
lua_createtable(L, 0, MIN_HASH_SIZE_FIX);
// The actual function is stored in an upvalue.
pgfgd_SyntacticDigraph* digraph = (pgfgd_SyntacticDigraph*) calloc(1, sizeof(pgfgd_SyntacticDigraph));
construct_digraph(L, digraph);
pgfgd_algorithm_fun fun = lua_touserdata(L, lua_upvalueindex(FUNCTION_UPVALUE));
fun(digraph, lua_touserdata(L, lua_upvalueindex(USER_UPVALUE)));
sync_digraph(L, digraph);
free_digraph(digraph);
return 0;
}
int pgfgd_vertex_anchor(pgfgd_Vertex* v, const char* anchor, double* x, double* y)
{
lua_State* L = v->options->state;
// Ok, first, find the vertex:
lua_rawgeti(L, VERTICES_INDEX, v->array_index+1);
// Find the anchor function:
lua_getfield(L, -1, "anchor");
lua_pushvalue(L, -2);
lua_pushstring(L, anchor);
// Find the anchor:
lua_call(L, 2, 1);
if (lua_isnil(L, -1)) {
// Failed. Cleanup!
lua_pop(L, 2);
*x = 0;
*y = 0;
return 0;
} else {
lua_getfield(L, -1, "x");
*x = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_getfield(L, -1, "y");
*y = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_pop(L, 2);
return 1;
}
return 0;
}
void pgfgd_path_clear(pgfgd_Edge* e)
{
clear_path (e->path);
}
static void path_add_segment(pgfgd_Edge* edge, const char* s, int num, double a, double b, double c, double d, double e, double f)
{
if (edge->path->length == -1)
pgfgd_path_clear(edge);
int start = edge->path->length;
edge->path->length += num + 1;
edge->path->strings = (char **)
realloc(edge->path->strings, edge->path->length*sizeof(char*));
edge->path->coordinates = (pgfgd_Coordinate*)
realloc(edge->path->coordinates, edge->path->length*sizeof(pgfgd_Coordinate));
edge->path->coordinates[start].x = 0;
edge->path->coordinates[start].y = 0;
edge->path->strings[start] = strcpy((char*) malloc(strlen(s)+1), s);
if (num > 0) {
edge->path->coordinates[start+1].x = a;
edge->path->coordinates[start+1].y = b;
edge->path->strings[start+1] = 0;
}
if (num > 1) {
edge->path->coordinates[start+2].x = c;
edge->path->coordinates[start+2].y = d;
edge->path->strings[start+2] = 0;
}
if (num > 2) {
edge->path->coordinates[start+3].x = e;
edge->path->coordinates[start+3].y = f;
edge->path->strings[start+3] = 0;
}
}
void pgfgd_path_append_moveto(pgfgd_Edge* e, double x, double y)
{
path_add_segment(e, "moveto", 1, x, y, 0, 0, 0, 0);
}
void pgfgd_path_append_moveto_tail (pgfgd_Edge* e)
{
double x, y;
char* tail_anchor = pgfgd_tostring(e->tail->options, "tail anchor");
pgfgd_vertex_anchor(e->tail, tail_anchor, &x, &y);
x += e->tail->pos.x;
y += e->tail->pos.y;
pgfgd_path_append_moveto(e, x, y);
free(tail_anchor);
}
void pgfgd_path_append_lineto(pgfgd_Edge* e, double x, double y)
{
path_add_segment(e, "lineto", 1, x, y, 0, 0, 0, 0);
}
void pgfgd_path_append_lineto_head (pgfgd_Edge* e)
{
double x, y;
char* head_anchor = pgfgd_tostring(e->head->options, "head anchor");
pgfgd_vertex_anchor(e->head, head_anchor, &x, &y);
x += e->head->pos.x;
y += e->head->pos.y;
pgfgd_path_append_lineto(e, x, y);
free(head_anchor);
}
void pgfgd_path_append_curveto(pgfgd_Edge* edge, double a, double b, double c, double d, double e, double f)
{
path_add_segment(edge, "curveto", 3, a, b, c, d, e, f);
}
void pgfgd_path_append_closepath(pgfgd_Edge* e)
{
path_add_segment(e, "closepath", 0, 0, 0, 0, 0, 0, 0);
}
// Handling digraphs
struct pgfgd_Digraph {
lua_State* state;
const char* name;
pgfgd_SyntacticDigraph* syntactic_digraph;
};
pgfgd_Digraph* pgfgd_get_digraph (pgfgd_SyntacticDigraph* g, const char* graph_name)
{
lua_State* L = g->internals->state;
lua_getfield(L, ALGORITHM_INDEX, graph_name);
if (lua_isnil(L, -1))
luaL_error(L, "digraph named %s not found in algorithm class", graph_name);
lua_pop(L, 1);
pgfgd_Digraph* new = (pgfgd_Digraph*) calloc(1, sizeof(pgfgd_Digraph));
new->state = L;
new->name = graph_name;
new->syntactic_digraph = g;
return new;
}
int pgfgd_digraph_num_vertices (pgfgd_Digraph* g)
{
lua_getfield(g->state, ALGORITHM_INDEX, g->name);
lua_getfield(g->state, -1, "vertices");
int num = lua_rawlen(g->state, -1);
lua_pop(g->state, 2);
return num;
}
static void push_digraph_and_backindex(pgfgd_Digraph* g)
{
lua_State* L = g->state;
// Get digraph
lua_getfield(L, ALGORITHM_INDEX, g->name);
int digraph_pos = lua_gettop(L);
// Get entry in back index table
lua_pushvalue(L, digraph_pos);
lua_gettable(L, BACKINDEX_STORAGE_INDEX);
int backtable_pos = lua_gettop(L);
if (lua_isnil(L, backtable_pos)) {
// Aha. We need to install a new table:
lua_pop(L, 1); // Get rid of nil
lua_createtable(L, 0, MIN_HASH_SIZE_FIX);
lua_pushvalue(L, digraph_pos); // The digraph object
lua_pushvalue(L, backtable_pos); // The new table
lua_settable(L, BACKINDEX_STORAGE_INDEX);
// Fill the table:
lua_getfield(L, digraph_pos, "vertices");
int vertex_pos = lua_gettop(L);
int i;
int n = lua_rawlen(L, -1);
for (i = 1; i <= n; i++) {
lua_rawgeti(L, vertex_pos, i);
lua_pushinteger(L, i);
lua_settable(L, backtable_pos);
}
lua_pop(L, 1);
}
}
static pgfgd_Arc_array* build_c_array_of_arcs_from_lua_array_of_arcs(pgfgd_Digraph* g)
{
lua_State* L = g->state;
pgfgd_Arc_array* arcs = (pgfgd_Arc_array*) calloc(1, sizeof(pgfgd_Arc_array));
int array_pos = lua_gettop(L);
push_digraph_and_backindex(g);
int backtable_pos = lua_gettop(L);
// Get number of arcs:
init_arcs_array(arcs, lua_rawlen(L, array_pos));
int i;
for (i = 1; i<=arcs->length; i++) {
lua_rawgeti(L, array_pos, i); // Get arcs[i]
// The tail field:
lua_getfield(L, -1, "tail");
lua_gettable(L, backtable_pos);
arcs->tails[i-1] = lua_tointeger(L, -1);
lua_pop(L, 1); // The number
// The head field:
lua_getfield(L, -1, "head");
lua_gettable(L, backtable_pos);
arcs->heads[i-1] = lua_tointeger(L, -1);
lua_pop(L, 1); // The number
lua_pop(L, 1); // Pop arcs[i]
}
lua_settop(L, array_pos);
return arcs;
}
pgfgd_Arc_array* pgfgd_digraph_arcs (pgfgd_Digraph* g)
{
lua_getfield(g->state, ALGORITHM_INDEX, g->name);
lua_getfield(g->state, -1, "arcs");
pgfgd_Arc_array* a = build_c_array_of_arcs_from_lua_array_of_arcs(g);
lua_pop(g->state, 2);
return a;
}
pgfgd_Vertex* pgfgd_digraph_syntactic_vertex (pgfgd_Digraph* g, int v)
{
int tos = lua_gettop(g->state);
pgfgd_Vertex* return_me = 0;
lua_getfield(g->state, ALGORITHM_INDEX, g->name);
lua_getfield(g->state, -1, "vertices");
lua_rawgeti(g->state, -1, v);
lua_gettable(g->state, VERTICES_INDEX);
if (lua_isnumber(g->state, -1)) {
return_me = g->syntactic_digraph->vertices.array[lua_tointeger(g->state, -1)-1];
}
lua_settop(g->state, tos);
return return_me;
}
int pgfgd_digraph_isarc (pgfgd_Digraph* g, int tail, int head)
{
lua_State* L = g->state;
int is_arc = 0;
lua_getfield(L, ALGORITHM_INDEX, g->name);
int digraph_pos = lua_gettop(L);
lua_getfield(L, digraph_pos, "vertices");
int vertices_pos = lua_gettop(L);
// Call digraph:connected(tail, head)
lua_pushvalue(L, lua_upvalueindex(DIGRAPH_OBJECT_UPVALUE));
lua_getfield(L, -1, "arc");
lua_pushvalue(L, digraph_pos);
lua_rawgeti(L, vertices_pos, tail);
lua_rawgeti(L, vertices_pos, head);
lua_call(L, 3, 1);
is_arc = !lua_isnil(L, -1);
lua_settop(L, digraph_pos-1);
return is_arc;
}
pgfgd_Arc_array* pgfgd_digraph_incoming (pgfgd_Digraph* g, int v)
{
lua_State* L = g->state;
lua_getfield(L, ALGORITHM_INDEX, g->name);
int digraph_pos = lua_gettop(L);
lua_getfield(L, digraph_pos, "vertices");
int vertices_pos = lua_gettop(L);
// Call digraph:connected(tail, head)
lua_pushvalue(L, lua_upvalueindex(DIGRAPH_OBJECT_UPVALUE));
lua_getfield(L, -1, "incoming");
lua_pushvalue(L, digraph_pos);
lua_rawgeti(L, vertices_pos, v);
lua_call(L, 2, 1);
pgfgd_Arc_array* a = build_c_array_of_arcs_from_lua_array_of_arcs(g);
lua_settop(L, digraph_pos-1);
return a;
}
pgfgd_Arc_array* pgfgd_digraph_outgoing (pgfgd_Digraph* g, int v)
{
lua_State* L = g->state;
lua_getfield(L, ALGORITHM_INDEX, g->name);
int digraph_pos = lua_gettop(L);
lua_getfield(L, digraph_pos, "vertices");
int vertices_pos = lua_gettop(L);
// Call digraph:connected(tail, head)
lua_pushvalue(L, lua_upvalueindex(DIGRAPH_OBJECT_UPVALUE));
lua_getfield(L, -1, "outgoing");
lua_pushvalue(L, digraph_pos);
lua_rawgeti(L, vertices_pos, v);
lua_call(L, 2, 1);
pgfgd_Arc_array* a = build_c_array_of_arcs_from_lua_array_of_arcs(g);
lua_settop(L, digraph_pos-1);
return a;
}
pgfgd_Edge_array* pgfgd_digraph_syntactic_edges (pgfgd_Digraph* g, int tail, int head)
{
pgfgd_Edge_array* edges = (pgfgd_Edge_array*) calloc(1, sizeof(pgfgd_Edge_array));
// First, get the arc in the syntatic digraph.
lua_State* L = g->state;
int tos = lua_gettop(L);
lua_getfield(L, ALGORITHM_INDEX, g->name);
int digraph_pos = lua_gettop(L);
lua_getfield(L, digraph_pos, "vertices");
int vertices_pos = lua_gettop(L);
// Call digraph:arc(tail, head)
lua_pushvalue(L, lua_upvalueindex(DIGRAPH_OBJECT_UPVALUE));
int digraph_class_index = lua_gettop(L);
lua_getfield(L, digraph_class_index, "arc");
lua_pushvalue(L, digraph_pos);
lua_rawgeti(L, vertices_pos, tail);
lua_rawgeti(L, vertices_pos, head);
lua_call(L, 3, 1);
if (!lua_isnil(L, -1)) {
// Get syntactic_digraph of the arc:
lua_getfield(L, -1, "syntactic_digraph");
// Call syntactic_digraph:arc(tail, head)
lua_getfield(L, digraph_class_index, "arc");
lua_pushvalue(L, -2);
lua_rawgeti(L, vertices_pos, tail);
lua_rawgeti(L, vertices_pos, head);
lua_call(L, 3, 1);
if (!lua_isnil(L, -1)) {
lua_getfield(L, -1, "syntactic_edges");
int syntactic_edges_index = lua_gettop(L);
int n = lua_rawlen(L, syntactic_edges_index);
init_edge_array(edges, n);
int i;
for (i=1; i<=n; i++) {
lua_rawgeti(L, syntactic_edges_index, i);
lua_gettable(L, EDGES_INDEX);
if (!lua_isnumber(L, -1)) {
pgfgd_digraph_free_edge_array(edges);
luaL_error(L, "syntactic edge index not found");
}
int p = lua_tonumber(L, -1);
edges->array[i-1] = g->syntactic_digraph->syntactic_edges.array[p-1];
}
}
}
lua_settop(L, tos);
return edges;
}
void pgfgd_digraph_free (pgfgd_Digraph* g)
{
free(g);
}
void pgfgd_digraph_free_arc_array (pgfgd_Arc_array* arcs)
{
free (arcs->tails);
free (arcs->heads);
free (arcs);
}
void pgfgd_digraph_free_edge_array (pgfgd_Edge_array* edges)
{
free (edges->array);
free (edges);
}
// Handling declarations
struct pgfgd_Declaration {
const char* key;
const char* summary;
const char* type;
const char* initial;
void* initial_user;
const char* default_value;
const char* alias;
const char* alias_function_string;
const char* documentation;
const char* documentation_in;
pgfgd_algorithm_fun algorithm;
void* algorithm_user;
const char* phase;
int use_length;
const char** use_keys;
const char** use_values_strings;
void** use_values_user;
int examples_length;
const char** examples;
int pre_length;
const char** pre;
int post_length;
const char** post;
};
pgfgd_Declaration* pgfgd_new_key (const char* key)
{
pgfgd_Declaration* d = (pgfgd_Declaration*) calloc(1, sizeof(pgfgd_Declaration));
d->key = key;
return d;
}
void pgfgd_declare(struct lua_State* state, pgfgd_Declaration* d)
{
if (d && d->key) {
int tos = lua_gettop(state);
lua_gc(state, LUA_GCSTOP, 0); // Remove once Lua Link Bug is fixed
// Find declare function:
lua_getglobal(state, "require");
lua_pushstring(state, "pgf.gd.interface.InterfaceToAlgorithms");
lua_call(state, 1, 1);
lua_getfield(state, -1, "declare");
// Build a Lua table:
lua_createtable(state, 0, 11);
set_field (state, d->key, "key");
set_field (state, d->summary, "summary");
set_field (state, d->type, "type");
set_field (state, d->initial, "initial");
set_field (state, d->documentation, "documentation");
set_field (state, d->documentation_in, "documentation_in");
set_field (state, d->default_value, "default");
set_field (state, d->alias, "alias");
set_field (state, d->alias_function_string, "alias_function_string");
set_field (state, d->phase, "phase");
if (d->initial_user) {
lua_pushlightuserdata(state, d->initial_user);
lua_setfield(state, -2, "initial");
}
if (d->use_length > 0) {
lua_createtable(state, d->use_length, MIN_HASH_SIZE_FIX);
int i;
for (i=0; i < d->use_length; i++) {
lua_createtable(state, 0, 2);
set_field(state, d->use_keys[i], "key");
if (d->use_values_strings[i])
set_field(state, d->use_values_strings[i], "value");
if (d->use_values_user[i]) {
lua_pushlightuserdata(state, d->use_values_user[i]);
lua_setfield(state, -2, "value");
}
lua_rawseti(state, -2, i+1);
}
lua_setfield(state, -2, "use");
}
if (d->pre) {
lua_createtable(state, 0, d->pre_length);
int i;
for (i=0; i < d->pre_length; i++) {
lua_pushboolean(state, 1);
lua_setfield(state, -2, d->pre[i]);
}
lua_setfield(state, -2, "preconditions");
}
if (d->post) {
lua_createtable(state, 0, d->post_length);
int i;
for (i=0; i < d->post_length; i++) {
lua_pushboolean(state, 1);
lua_setfield(state, -2, d->post[i]);
}
lua_setfield(state, -2, "postconditions");
}
if (d->examples) {
lua_createtable(state, d->examples_length, MIN_HASH_SIZE_FIX);
int i;
for (i=0; i < d->examples_length; i++) {
lua_pushstring(state, d->examples[i]);
lua_rawseti(state, -2, i+1);
}
lua_setfield(state, -2, "examples");
}
if (d->algorithm) {
// The algorithm function and the user data is stored as lightuserdate upvalue
lua_pushlightuserdata(state, (void *) d->algorithm);
lua_pushlightuserdata(state, (void *) d->algorithm_user);
// Find the Digraph.arc function and store it as the second upvalue:
lua_getglobal(state, "require");
lua_pushstring(state, "pgf.gd.model.Digraph");
lua_call(state, 1, 1);
lua_pushcclosure(state, algorithm_dispatcher, 3);
lua_setfield(state, -2, "algorithm_written_in_c");
}
// Call the declare function:
lua_call(state, 1, 0);
// Cleanup:
lua_settop(state, tos);
lua_gc(state, LUA_GCRESTART, 0); // Remove once Lua Link Bug is fixed
}
}
void pgfgd_key_add_use(pgfgd_Declaration* d, const char* key, const char* value)
{
d->use_length++;
d->use_keys = (const char **) realloc(d->use_keys, d->use_length*sizeof(const char*));
d->use_values_strings = (const char **) realloc(d->use_values_strings, d->use_length*sizeof(const char*));
d->use_values_user = (void **) realloc(d->use_values_user, d->use_length*sizeof(void*));
d->use_keys [d->use_length-1] = key;
d->use_values_strings[d->use_length-1] = value;
d->use_values_user [d->use_length-1] = 0;
}
void pgfgd_key_add_use_user(pgfgd_Declaration* d, const char* key, void* value)
{
d->use_length++;
d->use_keys = (const char **) realloc(d->use_keys, d->use_length*sizeof(const char*));
d->use_values_strings = (const char **) realloc(d->use_values_strings, d->use_length*sizeof(const char*));
d->use_values_user = (void **) realloc(d->use_values_user, d->use_length*sizeof(void*));
d->use_keys [d->use_length-1] = key;
d->use_values_strings[d->use_length-1] = 0;
d->use_values_user [d->use_length-1] = value;
}
void pgfgd_key_add_example(pgfgd_Declaration* d, const char* s)
{
d->examples_length++;
d->examples = (const char **) realloc(d->examples, d->examples_length*sizeof(const char*));
d->examples[d->examples_length-1] = s;
}
void pgfgd_key_add_precondition(pgfgd_Declaration* d, const char* s)
{
d->pre_length++;
d->pre = (const char **) realloc(d->pre, d->pre_length*sizeof(const char*));
d->pre[d->pre_length-1] = s;
}
void pgfgd_key_add_postcondition(pgfgd_Declaration* d, const char* s)
{
d->post_length++;
d->post = (const char **) realloc(d->post, d->post_length*sizeof(const char*));
d->post[d->post_length-1] = s;
}
void pgfgd_key_summary(pgfgd_Declaration* d, const char* s)
{
d->summary = s;
}
void pgfgd_key_type(pgfgd_Declaration* d, const char* s)
{
d->type = s;
}
void pgfgd_key_initial(pgfgd_Declaration* d, const char* s)
{
d->initial = s;
}
void pgfgd_key_initial_user(pgfgd_Declaration* d, void* s)
{
d->initial_user = s;
}
void pgfgd_key_default(pgfgd_Declaration* d, const char* s)
{
d->default_value = s;
}
void pgfgd_key_alias(pgfgd_Declaration* d, const char* s)
{
d->alias = s;
}
void pgfgd_key_alias_function(pgfgd_Declaration* d, const char* s)
{
d->alias_function_string = s;
}
void pgfgd_key_documentation(pgfgd_Declaration* d, const char* s)
{
d->documentation = s;
}
void pgfgd_key_documentation_in(pgfgd_Declaration* d, const char* s)
{
d->documentation_in = s;
}
void pgfgd_key_phase(pgfgd_Declaration* d, const char* s)
{
d->phase = s;
}
void pgfgd_key_algorithm(pgfgd_Declaration* d, pgfgd_algorithm_fun f, void* user_data)
{
d->algorithm = f;
d->algorithm_user = user_data;
}
void pgfgd_free_key(pgfgd_Declaration* d)
{
if (d) {
free(d->examples);
free(d->use_keys);
free(d->use_values_user);
free(d->use_values_strings);
free(d);
}
}
|
fzimmermann89/texlive.js
|
texlive/texmf-dist/source/generic/pgf/c/graphdrawing/pgf/gd/interface/c/InterfaceFromC.c
|
C
|
gpl-2.0
| 29,582
|
/* Manage a process's keyrings
*
* Copyright (C) 2004-2005, 2008 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/keyctl.h>
#include <linux/fs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/security.h>
#include <linux/user_namespace.h>
#include <asm/uaccess.h>
#include "internal.h"
/* Session keyring create vs join semaphore */
static DEFINE_MUTEX(key_session_mutex);
/* User keyring creation semaphore */
static DEFINE_MUTEX(key_user_keyring_mutex);
/* The root user's tracking struct */
struct key_user root_key_user = {
.usage = ATOMIC_INIT(3),
.cons_lock = __MUTEX_INITIALIZER(root_key_user.cons_lock),
.lock = __SPIN_LOCK_UNLOCKED(root_key_user.lock),
.nkeys = ATOMIC_INIT(2),
.nikeys = ATOMIC_INIT(2),
.uid = GLOBAL_ROOT_UID,
};
/*
* Install the user and user session keyrings for the current process's UID.
*/
int install_user_keyrings(void)
{
struct user_struct *user;
const struct cred *cred;
struct key *uid_keyring, *session_keyring;
key_perm_t user_keyring_perm;
char buf[20];
int ret;
uid_t uid;
user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;
cred = current_cred();
user = cred->user;
uid = from_kuid(cred->user_ns, user->uid);
kenter("%p{%u}", user, uid);
if (user->uid_keyring && user->session_keyring) {
kleave(" = 0 [exist]");
return 0;
}
mutex_lock(&key_user_keyring_mutex);
ret = 0;
if (!user->uid_keyring) {
/* get the UID-specific keyring
* - there may be one in existence already as it may have been
* pinned by a session, but the user_struct pointing to it
* may have been destroyed by setuid */
sprintf(buf, "_uid.%u", uid);
uid_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(uid_keyring)) {
uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_IN_QUOTA, NULL);
if (IS_ERR(uid_keyring)) {
ret = PTR_ERR(uid_keyring);
goto error;
}
}
/* get a default session keyring (which might also exist
* already) */
sprintf(buf, "_uid_ses.%u", uid);
session_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(session_keyring)) {
session_keyring =
keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_IN_QUOTA, NULL);
if (IS_ERR(session_keyring)) {
ret = PTR_ERR(session_keyring);
goto error_release;
}
/* we install a link from the user session keyring to
* the user keyring */
ret = key_link(session_keyring, uid_keyring);
if (ret < 0)
goto error_release_both;
}
/* install the keyrings */
user->uid_keyring = uid_keyring;
user->session_keyring = session_keyring;
}
mutex_unlock(&key_user_keyring_mutex);
kleave(" = 0");
return 0;
error_release_both:
key_put(session_keyring);
error_release:
key_put(uid_keyring);
error:
mutex_unlock(&key_user_keyring_mutex);
kleave(" = %d", ret);
return ret;
}
/*
* Install a fresh thread keyring directly to new credentials. This keyring is
* allowed to overrun the quota.
*/
int install_thread_keyring_to_cred(struct cred *new)
{
struct key *keyring;
keyring = keyring_alloc("_tid", new->uid, new->gid, new,
KEY_POS_ALL | KEY_USR_VIEW,
KEY_ALLOC_QUOTA_OVERRUN, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
new->thread_keyring = keyring;
return 0;
}
/*
* Install a fresh thread keyring, discarding the old one.
*/
static int install_thread_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
BUG_ON(new->thread_keyring);
ret = install_thread_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
/*
* Install a process keyring directly to a credentials struct.
*
* Returns -EEXIST if there was already a process keyring, 0 if one installed,
* and other value on any other error
*/
int install_process_keyring_to_cred(struct cred *new)
{
struct key *keyring;
if (new->process_keyring)
return -EEXIST;
keyring = keyring_alloc("_pid", new->uid, new->gid, new,
KEY_POS_ALL | KEY_USR_VIEW,
KEY_ALLOC_QUOTA_OVERRUN, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
new->process_keyring = keyring;
return 0;
}
/*
* Make sure a process keyring is installed for the current process. The
* existing process keyring is not replaced.
*
* Returns 0 if there is a process keyring by the end of this function, some
* error otherwise.
*/
static int install_process_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
ret = install_process_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret != -EEXIST ? ret : 0;
}
return commit_creds(new);
}
/*
* Install a session keyring directly to a credentials struct.
*/
int install_session_keyring_to_cred(struct cred *cred, struct key *keyring)
{
unsigned long flags;
struct key *old;
might_sleep();
/* create an empty session keyring */
if (!keyring) {
flags = KEY_ALLOC_QUOTA_OVERRUN;
if (cred->session_keyring)
flags = KEY_ALLOC_IN_QUOTA;
keyring = keyring_alloc("_ses", cred->uid, cred->gid, cred,
KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ,
flags, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
} else {
__key_get(keyring);
}
/* install the keyring */
old = cred->session_keyring;
rcu_assign_pointer(cred->session_keyring, keyring);
if (old)
key_put(old);
return 0;
}
/*
* Install a session keyring, discarding the old one. If a keyring is not
* supplied, an empty one is invented.
*/
static int install_session_keyring(struct key *keyring)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
ret = install_session_keyring_to_cred(new, keyring);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
/*
* Handle the fsuid changing.
*/
void key_fsuid_changed(struct task_struct *tsk)
{
/* update the ownership of the thread keyring */
BUG_ON(!tsk->cred);
if (tsk->cred->thread_keyring) {
down_write(&tsk->cred->thread_keyring->sem);
tsk->cred->thread_keyring->uid = tsk->cred->fsuid;
up_write(&tsk->cred->thread_keyring->sem);
}
}
/*
* Handle the fsgid changing.
*/
void key_fsgid_changed(struct task_struct *tsk)
{
/* update the ownership of the thread keyring */
BUG_ON(!tsk->cred);
if (tsk->cred->thread_keyring) {
down_write(&tsk->cred->thread_keyring->sem);
tsk->cred->thread_keyring->gid = tsk->cred->fsgid;
up_write(&tsk->cred->thread_keyring->sem);
}
}
/*
* Search the process keyrings attached to the supplied cred for the first
* matching key.
*
* The search criteria are the type and the match function. The description is
* given to the match function as a parameter, but doesn't otherwise influence
* the search. Typically the match function will compare the description
* parameter to the key's description.
*
* This can only search keyrings that grant Search permission to the supplied
* credentials. Keyrings linked to searched keyrings will also be searched if
* they grant Search permission too. Keys can only be found if they grant
* Search permission to the credentials.
*
* Returns a pointer to the key with the key usage count incremented if
* successful, -EAGAIN if we didn't find any matching key or -ENOKEY if we only
* matched negative keys.
*
* In the case of a successful return, the possession attribute is set on the
* returned key reference.
*/
key_ref_t search_my_process_keyrings(struct keyring_search_context *ctx)
{
key_ref_t key_ref, ret, err;
/* we want to return -EAGAIN or -ENOKEY if any of the keyrings were
* searchable, but we failed to find a key or we found a negative key;
* otherwise we want to return a sample error (probably -EACCES) if
* none of the keyrings were searchable
*
* in terms of priority: success > -ENOKEY > -EAGAIN > other error
*/
key_ref = NULL;
ret = NULL;
err = ERR_PTR(-EAGAIN);
/* search the thread keyring first */
if (ctx->cred->thread_keyring) {
key_ref = keyring_search_aux(
make_key_ref(ctx->cred->thread_keyring, 1), ctx);
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* search the process keyring second */
if (ctx->cred->process_keyring) {
key_ref = keyring_search_aux(
make_key_ref(ctx->cred->process_keyring, 1), ctx);
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
if (ret)
break;
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* search the session keyring */
if (ctx->cred->session_keyring) {
rcu_read_lock();
key_ref = keyring_search_aux(
make_key_ref(rcu_dereference(ctx->cred->session_keyring), 1),
ctx);
rcu_read_unlock();
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
if (ret)
break;
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* or search the user-session keyring */
else if (ctx->cred->user->session_keyring) {
key_ref = keyring_search_aux(
make_key_ref(ctx->cred->user->session_keyring, 1),
ctx);
if (!IS_ERR(key_ref))
goto found;
switch (PTR_ERR(key_ref)) {
case -EAGAIN: /* no key */
if (ret)
break;
case -ENOKEY: /* negative key */
ret = key_ref;
break;
default:
err = key_ref;
break;
}
}
/* no key - decide on the error we're going to go for */
key_ref = ret ? ret : err;
found:
return key_ref;
}
/*
* Search the process keyrings attached to the supplied cred for the first
* matching key in the manner of search_my_process_keyrings(), but also search
* the keys attached to the assumed authorisation key using its credentials if
* one is available.
*
* Return same as search_my_process_keyrings().
*/
key_ref_t search_process_keyrings(struct keyring_search_context *ctx)
{
struct request_key_auth *rka;
key_ref_t key_ref, ret = ERR_PTR(-EACCES), err;
might_sleep();
key_ref = search_my_process_keyrings(ctx);
if (!IS_ERR(key_ref))
goto found;
err = key_ref;
/* if this process has an instantiation authorisation key, then we also
* search the keyrings of the process mentioned there
* - we don't permit access to request_key auth keys via this method
*/
if (ctx->cred->request_key_auth &&
ctx->cred == current_cred() &&
ctx->index_key.type != &key_type_request_key_auth
) {
const struct cred *cred = ctx->cred;
/* defend against the auth key being revoked */
down_read(&cred->request_key_auth->sem);
if (key_validate(ctx->cred->request_key_auth) == 0) {
rka = ctx->cred->request_key_auth->payload.data;
ctx->cred = rka->cred;
key_ref = search_process_keyrings(ctx);
ctx->cred = cred;
up_read(&cred->request_key_auth->sem);
if (!IS_ERR(key_ref))
goto found;
ret = key_ref;
} else {
up_read(&cred->request_key_auth->sem);
}
}
/* no key - decide on the error we're going to go for */
if (err == ERR_PTR(-ENOKEY) || ret == ERR_PTR(-ENOKEY))
key_ref = ERR_PTR(-ENOKEY);
else if (err == ERR_PTR(-EACCES))
key_ref = ret;
else
key_ref = err;
found:
return key_ref;
}
/*
* See if the key we're looking at is the target key.
*/
int lookup_user_key_possessed(const struct key *key, const void *target)
{
return key == target;
}
/*
* Look up a key ID given us by userspace with a given permissions mask to get
* the key it refers to.
*
* Flags can be passed to request that special keyrings be created if referred
* to directly, to permit partially constructed keys to be found and to skip
* validity and permission checks on the found key.
*
* Returns a pointer to the key with an incremented usage count if successful;
* -EINVAL if the key ID is invalid; -ENOKEY if the key ID does not correspond
* to a key or the best found key was a negative key; -EKEYREVOKED or
* -EKEYEXPIRED if the best found key was revoked or expired; -EACCES if the
* found key doesn't grant the requested permit or the LSM denied access to it;
* or -ENOMEM if a special keyring couldn't be created.
*
* In the case of a successful return, the possession attribute is set on the
* returned key reference.
*/
key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,
key_perm_t perm)
{
struct keyring_search_context ctx = {
.match = lookup_user_key_possessed,
.flags = (KEYRING_SEARCH_NO_STATE_CHECK |
KEYRING_SEARCH_LOOKUP_DIRECT),
};
struct request_key_auth *rka;
struct key *key;
key_ref_t key_ref, skey_ref;
int ret;
try_again:
ctx.cred = get_current_cred();
key_ref = ERR_PTR(-ENOKEY);
switch (id) {
case KEY_SPEC_THREAD_KEYRING:
if (!ctx.cred->thread_keyring) {
if (!(lflags & KEY_LOOKUP_CREATE))
goto error;
ret = install_thread_keyring();
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error;
}
goto reget_creds;
}
key = ctx.cred->thread_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_PROCESS_KEYRING:
if (!ctx.cred->process_keyring) {
if (!(lflags & KEY_LOOKUP_CREATE))
goto error;
ret = install_process_keyring();
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error;
}
goto reget_creds;
}
key = ctx.cred->process_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_SESSION_KEYRING:
if (!ctx.cred->session_keyring) {
/* always install a session keyring upon access if one
* doesn't exist yet */
ret = install_user_keyrings();
if (ret < 0)
goto error;
if (lflags & KEY_LOOKUP_CREATE)
ret = join_session_keyring(NULL);
else
ret = install_session_keyring(
ctx.cred->user->session_keyring);
if (ret < 0)
goto error;
goto reget_creds;
} else if (ctx.cred->session_keyring ==
ctx.cred->user->session_keyring &&
lflags & KEY_LOOKUP_CREATE) {
ret = join_session_keyring(NULL);
if (ret < 0)
goto error;
goto reget_creds;
}
rcu_read_lock();
key = rcu_dereference(ctx.cred->session_keyring);
__key_get(key);
rcu_read_unlock();
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_USER_KEYRING:
if (!ctx.cred->user->uid_keyring) {
ret = install_user_keyrings();
if (ret < 0)
goto error;
}
key = ctx.cred->user->uid_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_USER_SESSION_KEYRING:
if (!ctx.cred->user->session_keyring) {
ret = install_user_keyrings();
if (ret < 0)
goto error;
}
key = ctx.cred->user->session_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_GROUP_KEYRING:
/* group keyrings are not yet supported */
key_ref = ERR_PTR(-EINVAL);
goto error;
case KEY_SPEC_REQKEY_AUTH_KEY:
key = ctx.cred->request_key_auth;
if (!key)
goto error;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_REQUESTOR_KEYRING:
if (!ctx.cred->request_key_auth)
goto error;
down_read(&ctx.cred->request_key_auth->sem);
if (test_bit(KEY_FLAG_REVOKED,
&ctx.cred->request_key_auth->flags)) {
key_ref = ERR_PTR(-EKEYREVOKED);
key = NULL;
} else {
rka = ctx.cred->request_key_auth->payload.data;
key = rka->dest_keyring;
__key_get(key);
}
up_read(&ctx.cred->request_key_auth->sem);
if (!key)
goto error;
key_ref = make_key_ref(key, 1);
break;
default:
key_ref = ERR_PTR(-EINVAL);
if (id < 1)
goto error;
key = key_lookup(id);
if (IS_ERR(key)) {
key_ref = ERR_CAST(key);
goto error;
}
key_ref = make_key_ref(key, 0);
/* check to see if we possess the key */
ctx.index_key.type = key->type;
ctx.index_key.description = key->description;
ctx.index_key.desc_len = strlen(key->description);
ctx.match_data = key;
kdebug("check possessed");
skey_ref = search_process_keyrings(&ctx);
kdebug("possessed=%p", skey_ref);
if (!IS_ERR(skey_ref)) {
key_put(key);
key_ref = skey_ref;
}
break;
}
/* unlink does not use the nominated key in any way, so can skip all
* the permission checks as it is only concerned with the keyring */
if (lflags & KEY_LOOKUP_FOR_UNLINK) {
ret = 0;
goto error;
}
if (!(lflags & KEY_LOOKUP_PARTIAL)) {
ret = wait_for_key_construction(key, true);
switch (ret) {
case -ERESTARTSYS:
goto invalid_key;
default:
if (perm)
goto invalid_key;
case 0:
break;
}
} else if (perm) {
ret = key_validate(key);
if (ret < 0)
goto invalid_key;
}
ret = -EIO;
if (!(lflags & KEY_LOOKUP_PARTIAL) &&
!test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
goto invalid_key;
/* check the permissions */
ret = key_task_permission(key_ref, ctx.cred, perm);
if (ret < 0)
goto invalid_key;
key->last_used_at = current_kernel_time().tv_sec;
error:
put_cred(ctx.cred);
return key_ref;
invalid_key:
key_ref_put(key_ref);
key_ref = ERR_PTR(ret);
goto error;
/* if we attempted to install a keyring, then it may have caused new
* creds to be installed */
reget_creds:
put_cred(ctx.cred);
goto try_again;
}
/*
* Join the named keyring as the session keyring if possible else attempt to
* create a new one of that name and join that.
*
* If the name is NULL, an empty anonymous keyring will be installed as the
* session keyring.
*
* Named session keyrings are joined with a semaphore held to prevent the
* keyrings from going away whilst the attempt is made to going them and also
* to prevent a race in creating compatible session keyrings.
*/
long join_session_keyring(const char *name)
{
const struct cred *old;
struct cred *new;
struct key *keyring;
long ret, serial;
new = prepare_creds();
if (!new)
return -ENOMEM;
old = current_cred();
/* if no name is provided, install an anonymous keyring */
if (!name) {
ret = install_session_keyring_to_cred(new, NULL);
if (ret < 0)
goto error;
serial = new->session_keyring->serial;
ret = commit_creds(new);
if (ret == 0)
ret = serial;
goto okay;
}
/* allow the user to join or create a named keyring */
mutex_lock(&key_session_mutex);
/* look for an existing keyring of this name */
keyring = find_keyring_by_name(name, false);
if (PTR_ERR(keyring) == -ENOKEY) {
/* not found - try and create a new one */
keyring = keyring_alloc(
name, old->uid, old->gid, old,
KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ | KEY_USR_LINK,
KEY_ALLOC_IN_QUOTA, NULL);
if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
}
} else if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
} else if (keyring == new->session_keyring) {
key_put(keyring);
ret = 0;
goto error2;
}
/* we've got a keyring - now to install it */
ret = install_session_keyring_to_cred(new, keyring);
if (ret < 0)
goto error2;
commit_creds(new);
mutex_unlock(&key_session_mutex);
ret = keyring->serial;
key_put(keyring);
okay:
return ret;
error2:
mutex_unlock(&key_session_mutex);
error:
abort_creds(new);
return ret;
}
/*
* Replace a process's session keyring on behalf of one of its children when
* the target process is about to resume userspace execution.
*/
void key_change_session_keyring(struct callback_head *twork)
{
const struct cred *old = current_cred();
struct cred *new = container_of(twork, struct cred, rcu);
if (unlikely(current->flags & PF_EXITING)) {
put_cred(new);
return;
}
new-> uid = old-> uid;
new-> euid = old-> euid;
new-> suid = old-> suid;
new->fsuid = old->fsuid;
new-> gid = old-> gid;
new-> egid = old-> egid;
new-> sgid = old-> sgid;
new->fsgid = old->fsgid;
new->user = get_uid(old->user);
new->user_ns = get_user_ns(old->user_ns);
new->group_info = get_group_info(old->group_info);
new->securebits = old->securebits;
new->cap_inheritable = old->cap_inheritable;
new->cap_permitted = old->cap_permitted;
new->cap_effective = old->cap_effective;
new->cap_ambient = old->cap_ambient;
new->cap_bset = old->cap_bset;
new->jit_keyring = old->jit_keyring;
new->thread_keyring = key_get(old->thread_keyring);
new->process_keyring = key_get(old->process_keyring);
security_transfer_creds(new, old);
commit_creds(new);
}
/*
* Make sure that root's user and user-session keyrings exist.
*/
static int __init init_root_keyring(void)
{
return install_user_keyrings();
}
late_initcall(init_root_keyring);
|
moonman/linux-fslc-sr
|
security/keys/process_keys.c
|
C
|
gpl-2.0
| 20,942
|
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*
COPYING CONDITIONS NOTICE:
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation, and provided that the
following conditions are met:
* Redistributions of source code must retain this COPYING
CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
PATENT MARKING NOTICE (below), and the PATENT RIGHTS
GRANT (below).
* Redistributions in binary form must reproduce this COPYING
CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
PATENT MARKING NOTICE (below), and the PATENT RIGHTS
GRANT (below) in the documentation and/or other materials
provided with the distribution.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
COPYRIGHT NOTICE:
TokuDB, Tokutek Fractal Tree Indexing Library.
Copyright (C) 2007-2013 Tokutek, Inc.
DISCLAIMER:
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
UNIVERSITY PATENT NOTICE:
The technology is licensed by the Massachusetts Institute of
Technology, Rutgers State University of New Jersey, and the Research
Foundation of State University of New York at Stony Brook under
United States of America Serial No. 11/760379 and to the patents
and/or patent applications resulting from it.
PATENT MARKING NOTICE:
This software is covered by US Patent No. 8,185,551.
This software is covered by US Patent No. 8,489,638.
PATENT RIGHTS GRANT:
"THIS IMPLEMENTATION" means the copyrightable works distributed by
Tokutek as part of the Fractal Tree project.
"PATENT CLAIMS" means the claims of patents that are owned or
licensable by Tokutek, both currently or in the future; and that in
the absence of this license would be infringed by THIS
IMPLEMENTATION or by using or running THIS IMPLEMENTATION.
"PATENT CHALLENGE" shall mean a challenge to the validity,
patentability, enforceability and/or non-infringement of any of the
PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.
Tokutek hereby grants to you, for the term and geographical scope of
the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to
make, have made, use, offer to sell, sell, import, transfer, and
otherwise run, modify, and propagate the contents of THIS
IMPLEMENTATION, where such license applies only to the PATENT
CLAIMS. This grant does not include claims that would be infringed
only as a consequence of further modifications of THIS
IMPLEMENTATION. If you or your agent or licensee institute or order
or agree to the institution of patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that
THIS IMPLEMENTATION constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any rights
granted to you under this License shall terminate as of the date
such litigation is filed. If you or your agent or exclusive
licensee institute or order or agree to the institution of a PATENT
CHALLENGE, then Tokutek may terminate any rights granted to you
under this License.
*/
#ident "Copyright (c) 2007-2013 Tokutek Inc. All rights reserved."
#include "test.h"
/* Do I return EINVAL when passing in NULL for something that would otherwise be strdup'd? */
#include <stdlib.h>
#include <sys/stat.h>
#include <errno.h>
#include <db.h>
// TOKU_TEST_FILENAME is defined in the Makefile
DB_ENV *env;
DB *db;
int
test_main (int UU(argc), char UU(*const argv[])) {
int r;
toku_os_recursive_delete(TOKU_TEST_FILENAME);
r=toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO); assert(r==0);
r=db_env_create(&env, 0); assert(r==0);
r=env->set_data_dir(env, NULL); assert(r==EINVAL);
r=env->open(env, TOKU_TEST_FILENAME, DB_CREATE|DB_PRIVATE, S_IRWXU+S_IRWXG+S_IRWXO); assert(r==0);
env->set_errpfx(env, NULL); assert(1); //Did not crash.
r=env->set_tmp_dir(env, NULL); assert(r==EINVAL);
r=env->close(env, 0); assert(r==0);
return 0;
}
|
edf-hpc/mariadb-galera
|
storage/tokudb/ft-index/src/tests/test_db_env_strdup_null.cc
|
C++
|
gpl-2.0
| 4,861
|
<html>
<head>
<title>
Scid Help:
Graph windows
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<STYLE TYPE="text/css">
<!--
body { background: #ffffff; }
h1, h2, h3, h4, h5 { color: #990000; }
h1 { align: center; }
-->
</STYLE>
</head>
<body bgcolor="#ffffff">
<h1>Graph windows</h1>
<p>
Scid has a number of windows which display information graphically.
They are explained below.
</p>
<h3><a name="Filter">Filter Graph window</a></h3>
<p>
The <b><i><font color="#990000">Filter Graph</font></i></b> window shows trends by date or by
Elo rating for the games in the current filter, compared to the
entire database. For example, it is useful when the <a href="Tree.html">tree</a>
is open as a tool showing how the current opening position has changed
in popularity in recent years or decades, or whether it is especially
popular among higher-rated players such as grandmasters.
Each point on the graph represents the number of games in the filter
per 1000 games in the entire database, for a particular date or Elo
rating range.
</p>
<p>
When plotting the Filter graph by rating, Scid uses the average (mean)
rating for each game. Estimate ratings (such as those in the spelling file)
are not used. If one player in a game has a rating but the opponent
does not, the opponent is presumed to have the same up to a limit of 2200.
For example, if one player is rated 2500 and the opponent has no rating,
the mean rating is (2500+2200)/2=2350.
</p>
<h3><a name="Rating">Rating Graph window</a></h3>
<p>
The <b><i><font color="#990000">Rating Graph</font></i></b> window shows the rating history of one
player or the two players of the current game.
You can produce the graph for a single player by pressing the
<b>Rating graph</b> button in the <a href="PInfo.html">player information</a>
window, or produce it for the two players of the current game by
selecting <b>Rating graph</b> from the <b><font color="#007000">[Tools]</font></b> menu.
</p>
<h3><a name="Score">Score Graph window</a></h3>
<p>
The <b><i><font color="#990000">Score Graph</font></i></b> window shows the numeric evaluations (scores)
stored in the comments of the current game as a graph.
You can click the left mouse button anywhere in the score graph to go to the
corresponding position in the game.
</p>
<p>
Two types of evaluation comment are recognized: those produced by
the Scid <a href="Analysis.html">analysis</a> window (which have the format
<ul>
<li><b>1.e4 {"+0.25 ...."}</b></li>
</ul>
and are always scores from White's perspective) and those produced
by the Crafty annotate command (which have the format
<ul>
<li><b>1.e4 ({9:+0.25} ....)</b></li>
</ul>
and are also scores from White's perspective).
</p>
<h3><a name="Tree">Tree Graph window</a></h3>
<p>
The <b><i><font color="#990000">Tree Graph</font></i></b> window is available from the tree
window. It shows the performance of the most popular moves from the
current position. More information is available from the
<a href="Tree.html\#Graph">Tree</a> help page.
</p>
<p><center><font size=-1>(Updated: Scid 3.3, April 2002)</font></center></p>
</body>
</html>
|
Raimondi/scid
|
help/Graphs.html
|
HTML
|
gpl-2.0
| 3,149
|
/*
* Copyright (C) 2013 Michal Podhradsky
* Utah State University, http://aggieair.usu.edu/
*
* This file is part of paparazzi.
*
* paparazzi is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* paparazzi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with paparazzi; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* @file ahrs_gx3.c
*
* Driver for Microstrain GX3 IMU/AHRS subsystem
*
* Takes care of configuration of the IMU, communication and parsing
* the received packets. See GX3 datasheet for configuration options.
*
* @author Michal Podhradsky <michal.podhradsky@aggiemail.usu.edu>
*/
#include "subsystems/ahrs/ahrs_gx3.h"
// for ahrs_register_impl
#include "subsystems/ahrs.h"
#define GX3_CHKSM(_ubx_payload) (uint16_t)((uint16_t)(*((uint8_t*)_ubx_payload+66+1))|(uint16_t)(*((uint8_t*)_ubx_payload+66+0))<<8)
/**
* Axis definition: X axis pointing forward, Y axis pointing to the right and Z axis pointing down.
* Positive pitch : nose up
* Positive roll : right wing down
* Positive yaw : clockwise
*/
struct AhrsGX3 ahrs_gx3;
static inline bool_t gx3_verify_chk(volatile uint8_t *buff_add);
static inline float bef(volatile uint8_t *c);
/* Big Endian to Float */
static inline float bef(volatile uint8_t *c)
{
float f;
int8_t *p;
p = ((int8_t *)&f) + 3;
*p-- = *c++;
*p-- = *c++;
*p-- = *c++;
*p = *c;
return f;
}
static inline bool_t gx3_verify_chk(volatile uint8_t *buff_add)
{
uint16_t i, chk_calc;
chk_calc = 0;
for (i = 0; i < GX3_MSG_LEN - 2; i++) {
chk_calc += (uint8_t) * buff_add++;
}
return (chk_calc == ((((uint16_t) * buff_add) << 8) + (uint8_t) * (buff_add + 1)));
}
void ahrs_gx3_align(void)
{
ahrs_gx3.is_aligned = FALSE;
//make the gyros zero, takes 10s (specified in Byte 4 and 5)
uart_transmit(&GX3_PORT, 0xcd);
uart_transmit(&GX3_PORT, 0xc1);
uart_transmit(&GX3_PORT, 0x29);
uart_transmit(&GX3_PORT, 0x27);
uart_transmit(&GX3_PORT, 0x10);
ahrs_gx3.is_aligned = TRUE;
}
#if PERIODIC_TELEMETRY
#include "subsystems/datalink/telemetry.h"
static void send_gx3(struct transport_tx *trans, struct link_device *dev)
{
pprz_msg_send_GX3_INFO(trans, dev, AC_ID,
&ahrs_gx3.freq,
&ahrs_gx3.packet.chksm_error,
&ahrs_gx3.packet.hdr_error,
&ahrs_gx3.chksm);
}
#endif
/*
* GX3 can be set up during the startup, or it can be configured to
* start sending data automatically after power up.
*/
void imu_impl_init(void)
{
// Initialize variables
ahrs_gx3.is_aligned = FALSE;
// Initialize packet
ahrs_gx3.packet.status = GX3PacketWaiting;
ahrs_gx3.packet.msg_idx = 0;
ahrs_gx3.packet.msg_available = FALSE;
ahrs_gx3.packet.chksm_error = 0;
ahrs_gx3.packet.hdr_error = 0;
// It is necessary to wait for GX3 to power up for proper initialization
for (uint32_t startup_counter = 0; startup_counter < IMU_GX3_LONG_DELAY * 2; startup_counter++) {
__asm("nop");
}
#ifdef GX3_INITIALIZE_DURING_STARTUP
#pragma message "GX3 initializing"
/*
// FOR NON-CONTINUOUS MODE UNCOMMENT THIS
//4 byte command for non-Continous Mode so we can set the other settings
uart_transmit(&GX3_PORT, 0xc4);
uart_transmit(&GX3_PORT, 0xc1);
uart_transmit(&GX3_PORT, 0x29);
uart_transmit(&GX3_PORT, 0x00); // stop
*/
//Sampling Settings (0xDB)
uart_transmit(&GX3_PORT, 0xdb); //set update speed
uart_transmit(&GX3_PORT, 0xa8);
uart_transmit(&GX3_PORT, 0xb9);
//set rate of IMU link, is 1000/IMU_DIV
#define IMU_DIV1 0
#define IMU_DIV2 2
#define ACC_FILT_DIV 2
#define MAG_FILT_DIV 30
#ifdef GX3_SAVE_SETTINGS
uart_transmit(&GX3_PORT, 0x02);//set params and save them in non-volatile memory
#else
uart_transmit(&GX3_PORT, 0x02); //set and don't save
#endif
uart_transmit(&GX3_PORT, IMU_DIV1);
uart_transmit(&GX3_PORT, IMU_DIV2);
uart_transmit(&GX3_PORT, 0b00000000); //set options byte 8 - GOOD
uart_transmit(&GX3_PORT, 0b00000011); //set options byte 7 - GOOD
//0 - calculate orientation, 1 - enable coning & sculling, 2-3 reserved, 4 - no little endian data,
// 5 - no NaN supressed, 6 - disable finite size correction, 7 - reserved,
// 8 - enable magnetometer, 9 - reserved, 10 - enable magnetic north compensation, 11 - enable gravity compensation
// 12 - no quaternion calculation, 13-15 reserved
uart_transmit(&GX3_PORT, ACC_FILT_DIV);
uart_transmit(&GX3_PORT, MAG_FILT_DIV); //mag window filter size == 33hz
uart_transmit(&GX3_PORT, 0x00);
uart_transmit(&GX3_PORT, 10); // Up Compensation in secs, def=10s
uart_transmit(&GX3_PORT, 0x00);
uart_transmit(&GX3_PORT, 10); // North Compensation in secs
uart_transmit(&GX3_PORT, 0x00); //power setting = 0, high power/bw
uart_transmit(&GX3_PORT, 0x00); //rest of the bytes are 0
uart_transmit(&GX3_PORT, 0x00);
uart_transmit(&GX3_PORT, 0x00);
uart_transmit(&GX3_PORT, 0x00);
uart_transmit(&GX3_PORT, 0x00);
// OPTIONAL: realign up and north
/*
uart_transmit(&GX3_PORT, 0xdd);
uart_transmit(&GX3_PORT, 0x54);
uart_transmit(&GX3_PORT, 0x4c);
uart_transmit(&GX3_PORT, 3);
uart_transmit(&GX3_PORT, 10);
uart_transmit(&GX3_PORT, 10);
uart_transmit(&GX3_PORT, 0x00);
uart_transmit(&GX3_PORT, 0x00);
uart_transmit(&GX3_PORT, 0x00);
uart_transmit(&GX3_PORT, 0x00);
*/
//Another wait loop for proper GX3 init
for (uint32_t startup_counter = 0; startup_counter < IMU_GX3_LONG_DELAY; startup_counter++) {
__asm("nop");
}
#ifdef GX3_SET_WAKEUP_MODE
//Mode Preset (0xD5)
uart_transmit(&GX3_PORT, 0xD5);
uart_transmit(&GX3_PORT, 0xBA);
uart_transmit(&GX3_PORT, 0x89);
uart_transmit(&GX3_PORT, 0x02); // wake up in continuous mode
//Continuous preset (0xD6)
uart_transmit(&GX3_PORT, 0xD6);
uart_transmit(&GX3_PORT, 0xC6);
uart_transmit(&GX3_PORT, 0x6B);
uart_transmit(&GX3_PORT, 0xc8); // accel, gyro, R
#endif
//4 byte command for Continous Mode
uart_transmit(&GX3_PORT, 0xc4);
uart_transmit(&GX3_PORT, 0xc1);
uart_transmit(&GX3_PORT, 0x29);
uart_transmit(&GX3_PORT, 0xc8); // accel,gyro,R
// Reset gyros to zero
ahrs_gx3_align();
#endif
#if PERIODIC_TELEMETRY
register_periodic_telemetry(DefaultPeriodic, "GX3_INFO", send_gx3);
#endif
}
void imu_periodic(void)
{
/* IF IN NON-CONTINUOUS MODE, REQUEST DATA NOW
uart_transmit(&GX3_PORT, 0xc8); // accel,gyro,R
*/
}
void gx3_packet_read_message(void)
{
ahrs_gx3.accel.x = bef(&ahrs_gx3.packet.msg_buf[1]);
ahrs_gx3.accel.y = bef(&ahrs_gx3.packet.msg_buf[5]);
ahrs_gx3.accel.z = bef(&ahrs_gx3.packet.msg_buf[9]);
ahrs_gx3.rate.p = bef(&ahrs_gx3.packet.msg_buf[13]);
ahrs_gx3.rate.q = bef(&ahrs_gx3.packet.msg_buf[17]);
ahrs_gx3.rate.r = bef(&ahrs_gx3.packet.msg_buf[21]);
ahrs_gx3.rmat.m[0] = bef(&ahrs_gx3.packet.msg_buf[25]);
ahrs_gx3.rmat.m[1] = bef(&ahrs_gx3.packet.msg_buf[29]);
ahrs_gx3.rmat.m[2] = bef(&ahrs_gx3.packet.msg_buf[33]);
ahrs_gx3.rmat.m[3] = bef(&ahrs_gx3.packet.msg_buf[37]);
ahrs_gx3.rmat.m[4] = bef(&ahrs_gx3.packet.msg_buf[41]);
ahrs_gx3.rmat.m[5] = bef(&ahrs_gx3.packet.msg_buf[45]);
ahrs_gx3.rmat.m[6] = bef(&ahrs_gx3.packet.msg_buf[49]);
ahrs_gx3.rmat.m[7] = bef(&ahrs_gx3.packet.msg_buf[53]);
ahrs_gx3.rmat.m[8] = bef(&ahrs_gx3.packet.msg_buf[57]);
ahrs_gx3.time = (uint32_t)(ahrs_gx3.packet.msg_buf[61] << 24 |
ahrs_gx3.packet.msg_buf[62] << 16 |
ahrs_gx3.packet.msg_buf[63] << 8 |
ahrs_gx3.packet.msg_buf[64]);
ahrs_gx3.chksm = GX3_CHKSM(ahrs_gx3.packet.msg_buf);
ahrs_gx3.freq = 62500.0 / (float)(ahrs_gx3.time - ahrs_gx3.ltime);
ahrs_gx3.ltime = ahrs_gx3.time;
// Acceleration
VECT3_SMUL(ahrs_gx3.accel, ahrs_gx3.accel, 9.80665); // Convert g into m/s2
// for compatibility with fixed point interface
ACCELS_BFP_OF_REAL(imu.accel, ahrs_gx3.accel);
// Rates
// for compatibility with fixed point interface
RATES_BFP_OF_REAL(imu.gyro, ahrs_gx3.rate);
struct FloatRates body_rate;
/* compute body rates */
struct FloatRMat *body_to_imu_rmat = orientationGetRMat_f(&imu.body_to_imu);
FLOAT_RMAT_TRANSP_RATEMULT(body_rate, *body_to_imu_rmat, ahrs_gx3.rate);
/* Set state */
stateSetBodyRates_f(&body_rate);
// Attitude
struct FloatRMat ltp_to_body_rmat;
FLOAT_RMAT_COMP(ltp_to_body_rmat, ahrs_gx3.rmat, *body_to_imu_rmat);
#if AHRS_USE_GPS_HEADING && USE_GPS
struct FloatEulers ltp_to_body_eulers;
float_eulers_of_rmat(<p_to_body_eulers, <p_to_body_rmat);
float course_f = (float)DegOfRad(gps.course / 1e7);
if (course_f > 180.0) {
course_f -= 360.0;
}
ltp_to_body_eulers.psi = (float)RadOfDeg(course_f);
stateSetNedToBodyEulers_f(<p_to_body_eulers);
#else // !AHRS_USE_GPS_HEADING
#ifdef IMU_MAG_OFFSET
struct FloatEulers ltp_to_body_eulers;
float_eulers_of_rmat(<p_to_body_eulers, <p_to_body_rmat);
ltp_to_body_eulers.psi -= ahrs_gx3.mag_offset;
stateSetNedToBodyEulers_f(<p_to_body_eulers);
#else
stateSetNedToBodyRMat_f(<p_to_body_rmat);
#endif // IMU_MAG_OFFSET
#endif // !AHRS_USE_GPS_HEADING
}
/* GX3 Packet Collection */
void gx3_packet_parse(uint8_t c)
{
switch (ahrs_gx3.packet.status) {
case GX3PacketWaiting:
ahrs_gx3.packet.msg_idx = 0;
if (c == GX3_HEADER) {
ahrs_gx3.packet.status++;
ahrs_gx3.packet.msg_buf[ahrs_gx3.packet.msg_idx] = c;
ahrs_gx3.packet.msg_idx++;
} else {
ahrs_gx3.packet.hdr_error++;
}
break;
case GX3PacketReading:
ahrs_gx3.packet.msg_buf[ahrs_gx3.packet.msg_idx] = c;
ahrs_gx3.packet.msg_idx++;
if (ahrs_gx3.packet.msg_idx == GX3_MSG_LEN) {
if (gx3_verify_chk(ahrs_gx3.packet.msg_buf)) {
ahrs_gx3.packet.msg_available = TRUE;
} else {
ahrs_gx3.packet.msg_available = FALSE;
ahrs_gx3.packet.chksm_error++;
}
ahrs_gx3.packet.status = 0;
}
break;
default:
ahrs_gx3.packet.status = 0;
ahrs_gx3.packet.msg_idx = 0;
break;
}
}
void ahrs_gx3_init(void)
{
/* set ltp_to_imu so that body is zero */
struct FloatQuat *body_to_imu_quat = orientationGetQuat_f(&imu.body_to_imu);
QUAT_COPY(ahrs_gx3.ltp_to_imu_quat, *body_to_imu_quat);
#ifdef IMU_MAG_OFFSET
ahrs_gx3.mag_offset = IMU_MAG_OFFSET;
#else
ahrs_gx3.mag_offset = 0.0;
#endif
ahrs_gx3.is_aligned = FALSE;
}
void ahrs_gx3_register(void)
{
ahrs_gx3_init();
/// @TODO: provide enable function
ahrs_register_impl(NULL);
}
/* no scaling */
void imu_scale_gyro(struct Imu *_imu __attribute__((unused))) {}
void imu_scale_accel(struct Imu *_imu __attribute__((unused))) {}
void imu_scale_mag(struct Imu *_imu __attribute__((unused))) {}
|
rudischilder/gr10_1
|
sw/airborne/subsystems/ahrs/ahrs_gx3.c
|
C
|
gpl-2.0
| 11,313
|
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sched.h>
#include <rk_api.h>
/* Number of iteration per task */
#define MAX_RESOURCE_SET_NAME_LEN 20
#define MILLISEC_TO_NANOSEC 1000000LL
#define NANOSEC_LL 1000000000LL
#define NUM_PROCESS 32
int main(int argc, char *argv[]){
int i;
int rd;
int ret;
struct cpu_reserve_attr cpu_attr;
struct timespec now;
int pid[NUM_PROCESS] = {0,};
int cpuid;
long long C, T, D;
char R[MAX_RESOURCE_SET_NAME_LEN];
memset(&cpu_attr, 0, sizeof(cpu_attr));
/* Default values */
for (cpuid = 0; cpuid < 2; cpuid++) {
//for (cpuid = 0; cpuid < 1; cpuid++) {
ret = fork();
if (ret != 0) continue;
pid[cpuid] = getpid();
if (cpuid == 0) {
C = 5 * MILLISEC_TO_NANOSEC;
T = 50 * MILLISEC_TO_NANOSEC;
D = 50 * MILLISEC_TO_NANOSEC;
}
else {
C = 110 * MILLISEC_TO_NANOSEC;
T = 1000 * MILLISEC_TO_NANOSEC;
D = 1000 * MILLISEC_TO_NANOSEC;
}
//T = D = (100 - cpuid) * MILLISEC_TO_NANOSEC;
clock_gettime(CLOCK_REALTIME, &now);
//sprintf(R, "RSET%ld", now.tv_nsec / 1000000 + now.tv_sec * 1000);
sprintf(R, "RSET%d", getpid());
//printf("Affine CPU : %d\n", cpuid);
//printf("Compute Time : %lld\n", C);
//printf("Reserve Period : %lld\n", T);
//printf("Reserve Deadline: %lld\n", D);
cpu_set_t cpus;
CPU_ZERO(&cpus);
CPU_SET(0, &cpus);
cpu_attr.compute_time.tv_sec=(C/NANOSEC_LL);
cpu_attr.period.tv_sec=(T/NANOSEC_LL);
cpu_attr.deadline.tv_sec=(D/NANOSEC_LL);
cpu_attr.blocking_time.tv_sec=0;
cpu_attr.start_time.tv_sec=0;
cpu_attr.compute_time.tv_nsec=(C%NANOSEC_LL);
cpu_attr.period.tv_nsec=(T%NANOSEC_LL);
cpu_attr.deadline.tv_nsec=(D%NANOSEC_LL);
cpu_attr.blocking_time.tv_nsec=0;
cpu_attr.start_time.tv_nsec=0;
cpu_attr.reserve_mode.sch_mode = RSV_HARD;
cpu_attr.reserve_mode.enf_mode = RSV_HARD;
cpu_attr.reserve_mode.rep_mode = RSV_SOFT;
cpu_attr.cpunum = 0;
//sched_setaffinity(getpid(), sizeof(cpus), &cpus);
rd = rk_resource_set_create(R, 1, 1, CPURSV_MIGRATION_DEFAULT);
rk_cpu_reserve_create(rd, &cpu_attr);
rk_resource_set_attach_process(rd, getpid(), NULL);
//while (1);
//return;
execv("../busyloop", NULL);
//rt_wait_for_next_period();
//printf("Resource Set Name is %s and Descriptor is %d\n",R, rd);
}
sleep(2);
printf("## Enter any key to kill all child processes\n");
getchar();
for (cpuid = 0; cpuid < NUM_PROCESS; cpuid++) {
kill(pid[cpuid], 9);
}
return 0;
}
|
leeymcj/linuxrk-tk1
|
mcrkmod/tests/multicore/prio-test.c
|
C
|
gpl-2.0
| 2,499
|
/*
* Universal Media Server, for streaming any medias to DLNA
* compatible renderers based on the http://www.ps3mediaserver.org.
* Copyright (C) 2012 UMS developers.
*
* This program is a free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.util;
import java.util.Locale;
import org.apache.commons.lang.WordUtils;
/**
* This class is a utility class for translation between {@link java.util.Locale}'s
* <a href="https://en.wikipedia.org/wiki/IETF_language_tag">IEFT BCP 47</a> and
* UMS' language files. See <a href="http://r12a.github.io/apps/subtags/">here
* for subtag lookup</a>. If UMS languages are removed or added, this class needs
* to be updated. The class is immutable.
*
* @author Nadahar
* @since 5.2.3
*/
public final class Languages {
/*
* If the below list is changed, methods localeToLanguageCode() and
* languageCodeToLanguageCode() must be updated correspondingly.
*/
private final static String[] UMS_BCP47_CODES = {
"ar", // Arabic
"bg", // Bulgarian
"ca", // Catalan, Valencian
"zh-Hans", // Chinese, Han (Simplified variant)
"zh-Hant", // Chinese, Han (Traditional variant)
"cs", // Czech
"da", // Danish
"nl", // Dutch, Flemish
"en-GB", // English, United Kingdom
"en-US", // English, United States
"fi", // Finnish
"fr", // French
"de", // German
"el", // Modern Greek
"iw", // Hebrew (Java prefers the deprecated "iw" to "he")
"is", // Icelandic
"it", // Italian
"ja", // Japanese
"ko", // Korean
"no", // Norwegian
"pl", // Polish
"pt", // Portuguese
"pt-BR", // Brazilian Portuguese
"ro", // Romanian, Moldavian, Moldovan
"ru", // Russian
"sl", // Slovenian
"es", // Spanish, Castilian
"sv", // Swedish
"tr", // Turkish
};
private final static String[] UMS_LANGUAGES = new String[UMS_BCP47_CODES.length];
static {
for (int i = 0; i < UMS_BCP47_CODES.length; i++) {
UMS_LANGUAGES[i] = WordUtils.capitalize(Locale.forLanguageTag(UMS_BCP47_CODES[i]).getDisplayName(Locale.getDefault()));
}
}
private static String localeToLanguageCode(Locale locale) {
/*
* This might seem redundant, but a language can also contain a
* country/region and a variant. Stating that e.g language
* "ar" should return "ar" means that "messages_ar.properties"
* will be used for any country/region and variant of Arabic.
* This should be true until UMS contains multiple dialects of Arabic,
* in which case different codes would have to be returned for the
* different dialects.
*/
if (locale == null) {
return null;
}
String languageCode = locale.getLanguage();
if (languageCode != null && !languageCode.isEmpty()) {
switch (languageCode) {
case "en":
if (locale.getCountry().equalsIgnoreCase("GB")) {
return "en-GB";
} else {
return "en-US";
}
case "pt":
if (locale.getCountry().equalsIgnoreCase("BR")) {
return "pt-BR";
} else {
return "pt";
}
case "nb":
case "nn":
return "no";
case "cmn":
case "zh":
if (locale.getScript().equalsIgnoreCase("Hans")) {
return "zh-Hans";
} else if (locale.getCountry().equalsIgnoreCase("CN") || locale.getCountry().equalsIgnoreCase("SG")) {
return "zh-Hans";
} else {
return "zh-Hant";
}
default:
return languageCode;
}
} else {
return null;
}
}
private static String languageCodeToLanguageCode(String languageCode) {
/*
* Performs the same conversion as localeToLanguageCode() but from a
* language tag instead of a Locale.
*/
if (languageCode == null) {
return null;
} else if (languageCode.isEmpty()) {
return "";
}
switch (languageCode.toLowerCase(Locale.US)) {
case "en-gb":
return "en-GB";
case "pt-br":
return "pt-BR";
case "cmn-cn":
case "cmn-sg":
case "cmn-hans":
case "zh-cn":
case "zh-sg":
case "zh-hans":
return "zh-Hans";
default:
if (languageCode.indexOf("-") > 0) {
languageCode = languageCode.substring(0, languageCode.indexOf("-"));
}
if (languageCode.equalsIgnoreCase("nb") || languageCode.equalsIgnoreCase("nn")) {
return "no";
} else if (languageCode.equalsIgnoreCase("cmn") || languageCode.equalsIgnoreCase("zh")) {
return "zh-Hant";
} else if (languageCode.equalsIgnoreCase("en")) {
return "en-US";
} else {
return languageCode.toLowerCase(Locale.US);
}
}
}
/**
* Verifies if a given <a href="https://en.wikipedia.org/wiki/IETF_language_tag">IEFT BCP 47</a>
* language tag is supported by UMS.
* @param languageCode The language tag in IEFT BCP 47 format.
* @return The result.
*/
public static boolean isValid(String languageCode) {
if (languageCode != null && !languageCode.isEmpty()) {
for (String code : UMS_BCP47_CODES) {
if (code.equalsIgnoreCase(languageCode)) {
return true;
}
}
}
return false;
}
/**
* Verifies if a given {@link java.util.Locale} is supported by UMS.
* @param locale The {@link java.util.Locale}.
* @return The result.
*/
public static boolean isValid(Locale locale) {
return isValid(localeToLanguageCode(locale));
}
/**
* Verifies if a given <a href="https://en.wikipedia.org/wiki/IETF_language_tag">IEFT BCP 47</a>
* language tag is or can be converted into a language tag supported by UMS.
* @param languageCode The language tag in IEFT BCP 47 format.
* @return The result.
*/
public static boolean isCompatible(String languageCode) {
return isValid(languageCodeToLanguageCode(languageCode));
}
/** Returns a correctly capitalized <a href="https://en.wikipedia.org/wiki/IETF_language_tag">IEFT BCP 47</a>
* language tag if the language tag is supported by UMS, or returns null.
* @param languageCode The IEFT BCP 47 compatible language tag.
* @return The IEFT BCP 47 formatted language tag.
*/
public static String toLanguageCode(String languageCode) {
if (languageCode != null && !languageCode.isEmpty()) {
languageCode = languageCodeToLanguageCode(languageCode);
for (String code : UMS_BCP47_CODES) {
if (code.equalsIgnoreCase(languageCode)) {
return code;
}
}
}
return null;
}
/** Returns a correctly capitalized <a href="https://en.wikipedia.org/wiki/IETF_language_tag">IEFT BCP 47</a>
* language tag if the language tag is supported by UMS, or returns null.
* @param locale The {@link java.util.Locale}.
* @return The IEFT BCP 47 formatted language tag.
*/
public static String toLanguageCode(Locale locale) {
if (locale != null) {
return toLanguageCode(localeToLanguageCode(locale));
}
return null;
}
/**
* Returns a UMS supported {@link java.util.Locale} from the given
* <code>Local</code> if it can be found (<code>en</code> is translated to
* <code>en-US</code>, <code>zh</code> to <code>zh-Hant</code> etc.).
* Returns <code>null</code> if a valid <code>Locale</code> cannot be found.
* @param locale Source {@link java.util.Locale}.
* @return Resulting {@link java.util.Locale}.
*/
public static Locale toLocale(Locale locale) {
if (locale != null) {
String code = localeToLanguageCode(locale);
if (code != null && isValid(code)) {
return Locale.forLanguageTag(code);
}
}
return null;
}
/**
* Returns a UMS supported {@link java.util.Locale} from the given
* <a href="https://en.wikipedia.org/wiki/IETF_language_tag">IEFT BCP 47</a>
* if it can be found (<code>en</code> is translated to <code>en-US</code>,
* <code>zh</code> to <code>zh-Hant</code> etc.). Returns <code>null</code>
* if a valid <code>Locale</code> cannot be found.
* @param locale Source {@link java.util.Locale}.
* @return Resulting {@link java.util.Locale}.
*/
public static Locale toLocale(String languageCode) {
if (languageCode != null) {
String code = languageCodeToLanguageCode(languageCode);
if (isValid(code)) {
return Locale.forLanguageTag(code);
}
}
return null;
}
public static String[] getLanguageTags() {
return UMS_BCP47_CODES;
}
public static String[] getLanguageNames() {
return UMS_LANGUAGES;
}
}
|
mindwarper/UniversalMediaServer
|
src/main/java/net/pms/util/Languages.java
|
Java
|
gpl-2.0
| 8,858
|
/*
* ProFTPD - FTP server daemon
* Copyright (c) 2004-2008 The ProFTPD Project team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* As a special exemption, The ProFTPD Project team and other respective
* copyright holders give permission to link this program with OpenSSL, and
* distribute the resulting executable, without including the source code for
* OpenSSL in the source distribution.
*/
/* Table management
* $Id: table.h,v 1.7 2008/05/13 05:41:47 castaglia Exp $
*/
#ifndef PR_TABLE_H
#define PR_TABLE_H
#include "conf.h"
typedef struct tab_key {
struct tab_key *next;
void *key_data;
size_t key_datasz;
unsigned int hash;
unsigned nents;
} pr_table_key_t;
typedef struct tab_entry {
struct tab_entry *next, *prev;
unsigned int idx;
pr_table_key_t *key;
void *value_data;
size_t value_datasz;
} pr_table_entry_t;
typedef struct table_rec pr_table_t;
/* Add an entry in the table under the given key. The char * pointer
* is stored directly, NOT a copy of the memory to which it points.
* If value_datasz is 0, value_data is assumed to be a NUL-terminated string
* and strlen() is called on it.
*/
int pr_table_add(pr_table_t *tab, const char *key_data, void *value_data,
size_t value_datasz);
/* Add an entry in the table under the given key, making a duplicate of
* the given value from the table's pool. If value_datasz is 0, value_data
* is assumed to be a NUL-terminated string and strlen() is called on it.
*/
int pr_table_add_dup(pr_table_t *tab, const char *key_data, void *value_data,
size_t value_datasz);
/* Allocates a new table from the given pool. flags can be used to
* determine the table behavior, e.g. will it allow multiple entries under
* the same key (PR_TABLE_FL_MULTI_VALUE).
*/
pr_table_t *pr_table_alloc(pool *p, int flags);
#define PR_TABLE_FL_MULTI_VALUE 0x0001
#define PR_TABLE_FL_USE_CACHE 0x0002
/* Returns the number of entries stored in the table.
*/
int pr_table_count(pr_table_t *tab);
/* Similar to Perl's map() function, this function executes the given
* callback on every entry in the table, passing in the key/value stored and a
* pointer to user-provided data. DO NOT ALTER the table inside the callback
* function by adding or removing entries; it will alter the iterator state,
* possibly causing entries to be skipped.
*
* This function is useful for when completely freeing an entire table and
* everything in it: do() a free() function on the items, then free the table.
*
* The flags argument alters how the calling is done: a callback can return -1
* to halt the iteration, unless PR_TABLE_DO_FL_ALL is used.
*/
int pr_table_do(pr_table_t *tab, int cb(const void *key_data,
size_t key_datasz, void *value_data, size_t value_datasz, void *user_data),
void *user_data, int flags);
#define PR_TABLE_DO_FL_ALL 0x0010
/* Remove all entries from the table, emptying it.
*/
int pr_table_empty(pr_table_t *tab);
/* Returns a count of the number of entries stored under that key. This
* means that these tables allow multiple entries under the same key; it is
* up to higher-level APIs to impose restrictions such as avoiding duplicates.
*/
int pr_table_exists(pr_table_t *tab, const char *key_data);
/* Free the given empty table. If the table is not empty, -1 will be
* returned, and errno set to EPERM.
*/
int pr_table_free(pr_table_t *tab);
/* Returns the value stored under the given key, or NULL if there is no
* entry in the table for the given key. If value_datasz is not NULL,
* the size of the returned value will be stored in it.
*/
void *pr_table_get(pr_table_t *tab, const char *key_data,
size_t *value_datasz);
/* Retrieve the next key, for iterating over the entire table. Returns
* NULL when the end of the table has been reached.
*/
void *pr_table_next(pr_table_t *tab);
/* Returns the value stored under the given key, and removes that entry from
* the table. If value_datasz is not NULL, the size of the returned value
* will be stored in it.
*/
void *pr_table_remove(pr_table_t *tab, const char *key_data,
size_t *value_datasz);
/* Rewind to the start of the table before iterating using pr_table_next().
*/
int pr_table_rewind(pr_table_t *tab);
/* Changes the value stored under the given key to the provided value.
* Returns -1 if no such key is in the table. Note that only the first
* encountered value under the key is set; this may be need to be called
* multiple times in order to set all entries under that key; call
* pr_table_exists() to find the number of entries to change.
*/
int pr_table_set(pr_table_t *tab, const char *key_data, void *value_data,
size_t value_datasz);
/* Change some of the characteristics of an allocated table tab via
* the control cmd. pr_table_ctl() can only be called on an empty table.
* Returns 0 on success, -1 on failure (with errno set appropriately).
*
* cmd may have one of the following values:
*
* PR_TABLE_CTL_SET_ENT_INSERT
* Sets a callback that handles inserting a table entry into its chain.
* The default insertor inserts new entries at the start of the chain;
* some tables may require that new entries be inserted at the end of
* of the chain.
*
* The arg parameter must be a pointer to a function with the following
* signature:
*
* void (*func)(pr_table_entry_t **head, pr_table_entry_t *ent)
*
* The function will be called with head as a pointer to the head of
* the chain into which ent will be inserted.
*
* If arg is NULL, the default insertor will be used.
*
* PR_TABLE_CTL_SET_ENT_REMOVE
* Sets a callback that handles removing a table entry for its chain.
*
* The arg parameter must be a pointer to a function with the following
* signature:
*
* void (*func)(pr_table_entry_t **head, pr_table_entry_t *ent)
*
* The function will be called with head as a pointer to the head of
* the chain from which ent will be removed.
*
* If arg is NULL, the default remover will be used.
*
* PR_TABLE_CTL_SET_FLAGS
* Sets the flags on the given table. These flags have the same
* values as the flags used in pr_table_alloc().
*
* PR_TABLE_CTL_SET_KEY_CMP
* Sets a callback for handling key comparisons. The default comparator
* uses strcmp() on the key data; some tables may require other
* comparators, especially if the key data are not strings.
*
* The arg parameter must be a pointer to a function with the following
* signature:
*
* int (*func)(const void *key1, size_t keysz1, const void *key2,
* size_t keysz2)
*
* If arg is NULL, the default comparator will be used.
*
* PR_TABLE_CTL_SET_KEY_HASH
* Sets a callback for handling the calculation of a hash value for
* given key data. The default hash algorithm is the same used in Perl.
*
* The arg parameter must be a pointer to a function with the following
* signature:
*
* unsigned int (*func)(const void *key, size_t keysz)
*
* If arg is NULL, the default hash function will be used.
*
* PR_TABLE_CTL_SET_NCHAINS
* Sets the number of chains in a table. New entries are hashed, then
* distributed among the chains in a manner that hopefully provides
* minimum lookup times. If a table will be holding a large number of
* entries, a larger number of chains will ensure a better distribution.
* The default number of chains is 32.
*/
int pr_table_ctl(pr_table_t *tab, int cmd, void *arg);
#define PR_TABLE_CTL_SET_ENT_INSERT 1
#define PR_TABLE_CTL_SET_ENT_REMOVE 2
#define PR_TABLE_CTL_SET_FLAGS 3
#define PR_TABLE_CTL_SET_KEY_CMP 4
#define PR_TABLE_CTL_SET_KEY_HASH 5
#define PR_TABLE_CTL_SET_NCHAINS 6
/* Dump table information. */
void pr_table_dump(void (*)(const char *, ...), pr_table_t *tab);
/* Same as pr_table_add(), except that the key data to use is treated as
* an opaque memory region of size key_datasz. This function should be
* used if the lookup key is not a string.
*
* Unlike pr_table_add(), though, if value_datasz is zero, it is not
* assumed that value_data is a NUL-terminated string. Callers of this
* function must provide the size of the given value_data.
*/
int pr_table_kadd(pr_table_t *tab, const void *key_data, size_t key_datasz,
void *value_data, size_t value_datasz);
/* Same as pr_table_exists(), except that the key data to use is treated as
* an opaque memory region of size key_datasz. This function should be
* used if the lookup key is not a string.
*/
int pr_table_kexists(pr_table_t *tab, const void *key_data, size_t key_datasz);
/* Same as pr_table_get(), except that the key data to use is treated as
* an opaque memory region of size key_datasz. This function should be
* used if the lookup key is not a string.
*/
void *pr_table_kget(pr_table_t *tab, const void *key_data,
size_t key_datasz, size_t *value_datasz);
/* Same as pr_table_remove(), except that the key data to use is treated as
* an opaque memory region of size key_datasz. This function should be
* used if the lookup key is not a string.
*/
void *pr_table_kremove(pr_table_t *tab, const void *key_data,
size_t key_datasz, size_t *value_datasz);
/* Same as pr_table_set(), except that the key data to use is treated as
* an opaque memory region of size key_datasz. This function should be
* used if the lookup key is not a string.
*/
int pr_table_kset(pr_table_t *tab, const void *key_data, size_t key_datasz,
void *value_data, size_t value_datasz);
/* Similar to pr_table_alloc(), except that the number of chains can
* be explicitly configured.
*/
pr_table_t *pr_table_nalloc(pool *p, int flags, unsigned int nchains);
/* Similar to pcalloc(), except that the requested memory is allocated
* from the table's pool.
*/
void *pr_table_pcalloc(pr_table_t *tab, size_t sz);
/* Internal use only. */
int table_handling_signal(int bool);
#endif /* PR_TABLE_H */
|
dan82840/Netgear-RBR40
|
git_home/proftpd.git/include/table.h
|
C
|
gpl-2.0
| 10,598
|
// SHE library
// Copyright (C) 2012-2014 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifndef SHE_CLIPBOARD_IMPL_H_INCLUDED
#define SHE_CLIPBOARD_IMPL_H_INCLUDED
#pragma once
#include "base/string.h"
#include "she/clipboard.h"
#ifdef _MSC_VER
#pragma warning(disable:4996) // To void MSVC warning about std::copy() with unsafe arguments
#endif
namespace she {
class ClipboardImpl : public Clipboard {
public:
~ClipboardImpl() {
}
void dispose() override {
delete this;
}
std::string getText() override {
std::string text;
if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
if (OpenClipboard(win_get_window())) {
HGLOBAL hglobal = GetClipboardData(CF_UNICODETEXT);
if (hglobal != NULL) {
LPWSTR lpstr = static_cast<LPWSTR>(GlobalLock(hglobal));
if (lpstr != NULL) {
text = base::to_utf8(lpstr).c_str();
GlobalUnlock(hglobal);
}
}
CloseClipboard();
}
}
return text;
}
void setText(const std::string& text) {
if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
if (OpenClipboard(win_get_window())) {
EmptyClipboard();
if (!text.empty()) {
std::wstring wstr = base::from_utf8(text);
int len = wstr.size();
HGLOBAL hglobal = GlobalAlloc(GMEM_MOVEABLE |
GMEM_ZEROINIT, sizeof(WCHAR)*(len+1));
LPWSTR lpstr = static_cast<LPWSTR>(GlobalLock(hglobal));
std::copy(wstr.begin(), wstr.end(), lpstr);
GlobalUnlock(hglobal);
SetClipboardData(CF_UNICODETEXT, hglobal);
}
CloseClipboard();
}
}
}
private:
std::string m_text;
};
} // namespace she
#endif
|
Mailaender/aseprite
|
src/she/clipboard_win.h
|
C
|
gpl-2.0
| 1,891
|
/******************************************************************************
*
* Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
*
******************************************************************************/
#define _HCI_INTF_C_
#include <drv_types.h>
#include <platform_ops.h>
#ifndef CONFIG_USB_HCI
#error "CONFIG_USB_HCI shall be on!\n"
#endif
#if defined (PLATFORM_LINUX) && defined (PLATFORM_WINDOWS)
#error "Shall be Linux or Windows, but not both!\n"
#endif
#ifdef CONFIG_80211N_HT
extern int rtw_ht_enable;
extern int rtw_bw_mode;
extern int rtw_ampdu_enable;//for enable tx_ampdu
#endif
#ifdef CONFIG_GLOBAL_UI_PID
int ui_pid[3] = {0, 0, 0};
#endif
extern int pm_netdev_open(struct net_device *pnetdev,u8 bnormal);
static int rtw_suspend(struct usb_interface *intf, pm_message_t message);
static int rtw_resume(struct usb_interface *intf);
int rtw_resume_process(_adapter *padapter);
static int rtw_drv_init(struct usb_interface *pusb_intf,const struct usb_device_id *pdid);
static void rtw_dev_remove(struct usb_interface *pusb_intf);
static void rtw_dev_shutdown(struct device *dev)
{
struct usb_interface *usb_intf = container_of(dev, struct usb_interface, dev);
struct dvobj_priv *dvobj = NULL;
_adapter *adapter = NULL;
int i;
DBG_871X("%s\n", __func__);
if(usb_intf)
{
dvobj = usb_get_intfdata(usb_intf);
if (dvobj)
{
for (i = 0; i<dvobj->iface_nums; i++)
{
adapter = dvobj->padapters[i];
if (adapter)
{
adapter->bSurpriseRemoved = _TRUE;
}
}
ATOMIC_SET(&dvobj->continual_io_error, MAX_CONTINUAL_IO_ERR+1);
}
}
}
#if (LINUX_VERSION_CODE<=KERNEL_VERSION(2,6,23))
/* Some useful macros to use to create struct usb_device_id */
#define USB_DEVICE_ID_MATCH_VENDOR 0x0001
#define USB_DEVICE_ID_MATCH_PRODUCT 0x0002
#define USB_DEVICE_ID_MATCH_DEV_LO 0x0004
#define USB_DEVICE_ID_MATCH_DEV_HI 0x0008
#define USB_DEVICE_ID_MATCH_DEV_CLASS 0x0010
#define USB_DEVICE_ID_MATCH_DEV_SUBCLASS 0x0020
#define USB_DEVICE_ID_MATCH_DEV_PROTOCOL 0x0040
#define USB_DEVICE_ID_MATCH_INT_CLASS 0x0080
#define USB_DEVICE_ID_MATCH_INT_SUBCLASS 0x0100
#define USB_DEVICE_ID_MATCH_INT_PROTOCOL 0x0200
#define USB_DEVICE_ID_MATCH_INT_NUMBER 0x0400
#define USB_DEVICE_ID_MATCH_INT_INFO \
(USB_DEVICE_ID_MATCH_INT_CLASS | \
USB_DEVICE_ID_MATCH_INT_SUBCLASS | \
USB_DEVICE_ID_MATCH_INT_PROTOCOL)
#define USB_DEVICE_AND_INTERFACE_INFO(vend, prod, cl, sc, pr) \
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO \
| USB_DEVICE_ID_MATCH_DEVICE, \
.idVendor = (vend), \
.idProduct = (prod), \
.bInterfaceClass = (cl), \
.bInterfaceSubClass = (sc), \
.bInterfaceProtocol = (pr)
/**
* USB_VENDOR_AND_INTERFACE_INFO - describe a specific usb vendor with a class of usb interfaces
* @vend: the 16 bit USB Vendor ID
* @cl: bInterfaceClass value
* @sc: bInterfaceSubClass value
* @pr: bInterfaceProtocol value
*
* This macro is used to create a struct usb_device_id that matches a
* specific vendor with a specific class of interfaces.
*
* This is especially useful when explicitly matching devices that have
* vendor specific bDeviceClass values, but standards-compliant interfaces.
*/
#define USB_VENDOR_AND_INTERFACE_INFO(vend, cl, sc, pr) \
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO \
| USB_DEVICE_ID_MATCH_VENDOR, \
.idVendor = (vend), \
.bInterfaceClass = (cl), \
.bInterfaceSubClass = (sc), \
.bInterfaceProtocol = (pr)
/* ----------------------------------------------------------------------- */
#endif
#define USB_VENDER_ID_REALTEK 0x0BDA
/* DID_USB_v916_20130116 */
static struct usb_device_id rtw_usb_id_tbl[] ={
#ifdef CONFIG_RTL8192C
/*=== Realtek demoboard ===*/
/****** 8188CUS ********/
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8176),.driver_info = RTL8188C_8192C},/* 8188cu 1*1 dongole */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8170),.driver_info = RTL8188C_8192C},/* 8188CE-VAU USB minCard */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x817E),.driver_info = RTL8188C_8192C},/* 8188CE-VAU USB minCard */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x817A),.driver_info = RTL8188C_8192C},/* 8188cu Slim Solo */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x817B),.driver_info = RTL8188C_8192C},/* 8188cu Slim Combo */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x817D),.driver_info = RTL8188C_8192C},/* 8188RU High-power USB Dongle */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8754),.driver_info = RTL8188C_8192C},/* 8188 Combo for BC4 */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x817F),.driver_info = RTL8188C_8192C},/* 8188RU */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x818A),.driver_info = RTL8188C_8192C},/* RTL8188CUS-VL */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x018A),.driver_info = RTL8188C_8192C},/* RTL8188CTV */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x17C0),.driver_info = RTL8188C_8192C},/* RTK demoboard - USB-N10E */
/****** 8192CUS ********/
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8177),.driver_info = RTL8188C_8192C},/* 8191cu 1*2 */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8178),.driver_info = RTL8188C_8192C},/* 8192cu 2*2 */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x817C),.driver_info = RTL8188C_8192C},/* 8192CE-VAU USB minCard */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8191),.driver_info = RTL8188C_8192C},/* 8192CU 2*2 */
{USB_DEVICE(0x1058, 0x0631),.driver_info = RTL8188C_8192C},/* Alpha, 8192CU */
/*=== Customer ID ===*/
/****** 8188CUS Dongle ********/
{USB_DEVICE(0x2019, 0xED17),.driver_info = RTL8188C_8192C},/* PCI - Edimax */
{USB_DEVICE(0x0DF6, 0x0052),.driver_info = RTL8188C_8192C},/* Sitecom - Edimax */
{USB_DEVICE(0x7392, 0x7811),.driver_info = RTL8188C_8192C},/* Edimax - Edimax */
{USB_DEVICE(0x07B8, 0x8189),.driver_info = RTL8188C_8192C},/* Abocom - Abocom */
{USB_DEVICE(0x0EB0, 0x9071),.driver_info = RTL8188C_8192C},/* NO Brand - Etop */
{USB_DEVICE(0x06F8, 0xE033),.driver_info = RTL8188C_8192C},/* Hercules - Edimax */
{USB_DEVICE(0x103C, 0x1629),.driver_info = RTL8188C_8192C},/* HP - Lite-On ,8188CUS Slim Combo */
{USB_DEVICE(0x2001, 0x3308),.driver_info = RTL8188C_8192C},/* D-Link - Alpha */
{USB_DEVICE(0x050D, 0x1102),.driver_info = RTL8188C_8192C},/* Belkin - Edimax */
{USB_DEVICE(0x2019, 0xAB2A),.driver_info = RTL8188C_8192C},/* Planex - Abocom */
{USB_DEVICE(0x20F4, 0x648B),.driver_info = RTL8188C_8192C},/* TRENDnet - Cameo */
{USB_DEVICE(0x4855, 0x0090),.driver_info = RTL8188C_8192C},/* - Feixun */
{USB_DEVICE(0x13D3, 0x3357),.driver_info = RTL8188C_8192C},/* - AzureWave */
{USB_DEVICE(0x0DF6, 0x005C),.driver_info = RTL8188C_8192C},/* Sitecom - Edimax */
{USB_DEVICE(0x0BDA, 0x5088),.driver_info = RTL8188C_8192C},/* Thinkware - CC&C */
{USB_DEVICE(0x4856, 0x0091),.driver_info = RTL8188C_8192C},/* NetweeN - Feixun */
{USB_DEVICE(0x0846, 0x9041),.driver_info = RTL8188C_8192C}, /* Netgear - Cameo */
{USB_DEVICE(0x2019, 0x4902),.driver_info = RTL8188C_8192C},/* Planex - Etop */
{USB_DEVICE(0x2019, 0xAB2E),.driver_info = RTL8188C_8192C},/* SW-WF02-AD15 -Abocom */
{USB_DEVICE(0x2001, 0x330B),.driver_info = RTL8188C_8192C}, /* D-LINK - T&W */
{USB_DEVICE(0xCDAB, 0x8010),.driver_info = RTL8188C_8192C}, /* - - compare */
{USB_DEVICE(0x0B05, 0x17BA),.driver_info = RTL8188C_8192C}, /* ASUS - Edimax */
{USB_DEVICE(0x0BDA, 0x1E1E),.driver_info = RTL8188C_8192C}, /* Intel - - */
{USB_DEVICE(0x04BB, 0x094c),.driver_info = RTL8188C_8192C}, /* I-O DATA - Edimax */
/****** 8188CTV ********/
{USB_DEVICE(0xCDAB, 0x8011),.driver_info = RTL8188C_8192C}, /* - - compare */
{USB_DEVICE(0x0BDA, 0x0A8A),.driver_info = RTL8188C_8192C}, /* Sony - Foxconn */
/****** 8188 RU ********/
{USB_DEVICE(0x0BDA, 0x317F),.driver_info = RTL8188C_8192C},/* Netcore,Netcore */
/****** 8188CE-VAU ********/
{USB_DEVICE(0x13D3, 0x3359),.driver_info = RTL8188C_8192C},/* - Azwave */
{USB_DEVICE(0x13D3, 0x3358),.driver_info = RTL8188C_8192C},/* - Azwave */
/****** 8188CUS Slim Solo********/
{USB_DEVICE(0x04F2, 0xAFF7),.driver_info = RTL8188C_8192C},/* XAVI - XAVI */
{USB_DEVICE(0x04F2, 0xAFF9),.driver_info = RTL8188C_8192C},/* XAVI - XAVI */
{USB_DEVICE(0x04F2, 0xAFFA),.driver_info = RTL8188C_8192C},/* XAVI - XAVI */
/****** 8188CUS Slim Combo ********/
{USB_DEVICE(0x04F2, 0xAFF8),.driver_info = RTL8188C_8192C},/* XAVI - XAVI */
{USB_DEVICE(0x04F2, 0xAFFB),.driver_info = RTL8188C_8192C},/* XAVI - XAVI */
{USB_DEVICE(0x04F2, 0xAFFC),.driver_info = RTL8188C_8192C},/* XAVI - XAVI */
{USB_DEVICE(0x2019, 0x1201),.driver_info = RTL8188C_8192C},/* Planex - Vencer */
/****** 8192CUS Dongle ********/
{USB_DEVICE(0x2001, 0x3307),.driver_info = RTL8188C_8192C},/* D-Link - Cameo */
{USB_DEVICE(0x2001, 0x330A),.driver_info = RTL8188C_8192C},/* D-Link - Alpha */
{USB_DEVICE(0x2001, 0x3309),.driver_info = RTL8188C_8192C},/* D-Link - Alpha */
{USB_DEVICE(0x0586, 0x341F),.driver_info = RTL8188C_8192C},/* Zyxel - Abocom */
{USB_DEVICE(0x7392, 0x7822),.driver_info = RTL8188C_8192C},/* Edimax - Edimax */
{USB_DEVICE(0x2019, 0xAB2B),.driver_info = RTL8188C_8192C},/* Planex - Abocom */
{USB_DEVICE(0x07B8, 0x8178),.driver_info = RTL8188C_8192C},/* Abocom - Abocom */
{USB_DEVICE(0x07AA, 0x0056),.driver_info = RTL8188C_8192C},/* ATKK - Gemtek */
{USB_DEVICE(0x4855, 0x0091),.driver_info = RTL8188C_8192C},/* - Feixun */
{USB_DEVICE(0x050D, 0x2102),.driver_info = RTL8188C_8192C},/* Belkin - Sercomm */
{USB_DEVICE(0x050D, 0x2103),.driver_info = RTL8188C_8192C},/* Belkin - Edimax */
{USB_DEVICE(0x20F4, 0x624D),.driver_info = RTL8188C_8192C},/* TRENDnet */
{USB_DEVICE(0x0DF6, 0x0061),.driver_info = RTL8188C_8192C},/* Sitecom - Edimax */
{USB_DEVICE(0x0B05, 0x17AB),.driver_info = RTL8188C_8192C},/* ASUS - Edimax */
{USB_DEVICE(0x0846, 0x9021),.driver_info = RTL8188C_8192C},/* Netgear - Sercomm */
{USB_DEVICE(0x0846, 0xF001),.driver_info = RTL8188C_8192C}, /* Netgear - Sercomm */
{USB_DEVICE(0x0E66, 0x0019),.driver_info = RTL8188C_8192C},/* Hawking,Edimax */
{USB_DEVICE(0x0E66, 0x0020),.driver_info = RTL8188C_8192C}, /* Hawking - Edimax */
{USB_DEVICE(0x050D, 0x1004),.driver_info = RTL8188C_8192C}, /* Belkin - Edimax */
{USB_DEVICE(0x0BDA, 0x2E2E),.driver_info = RTL8188C_8192C}, /* Intel - - */
{USB_DEVICE(0x2357, 0x0100),.driver_info = RTL8188C_8192C}, /* TP-Link - TP-Link */
{USB_DEVICE(0x06F8, 0xE035),.driver_info = RTL8188C_8192C}, /* Hercules - Edimax */
{USB_DEVICE(0x04BB, 0x0950),.driver_info = RTL8188C_8192C}, /* IO-DATA - Edimax */
{USB_DEVICE(0x0DF6, 0x0070),.driver_info = RTL8188C_8192C}, /* Sitecom - Edimax */
{USB_DEVICE(0x0789, 0x016D),.driver_info = RTL8188C_8192C}, /* LOGITEC - Edimax */
/****** 8192CE-VAU ********/
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8186),.driver_info = RTL8188C_8192C},/* Intel-Xavi( Azwave) */
#endif
#ifdef CONFIG_RTL8192D
/*=== Realtek demoboard ===*/
/****** 8192DU ********/
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8193),.driver_info = RTL8192D},/* 8192DU-VC */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8194),.driver_info = RTL8192D},/* 8192DU-VS */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8111),.driver_info = RTL8192D},/* Realtek 5G dongle for WiFi Display */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x0193),.driver_info = RTL8192D},/* 8192DE-VAU */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8171),.driver_info = RTL8192D},/* 8192DU-VC */
/*=== Customer ID ===*/
/****** 8192DU-VC ********/
{USB_DEVICE(0x2019, 0xAB2C),.driver_info = RTL8192D},/* PCI - Abocm */
{USB_DEVICE(0x2019, 0x4903),.driver_info = RTL8192D},/* PCI - ETOP */
{USB_DEVICE(0x2019, 0x4904),.driver_info = RTL8192D},/* PCI - ETOP */
{USB_DEVICE(0x07B8, 0x8193),.driver_info = RTL8192D},/* Abocom - Abocom */
/****** 8192DU-VS ********/
{USB_DEVICE(0x20F4, 0x664B),.driver_info = RTL8192D},/* TRENDnet */
{USB_DEVICE(0x04DD, 0x954F),.driver_info = RTL8192D}, /* Sharp */
{USB_DEVICE(0x04DD, 0x96A6),.driver_info = RTL8192D}, /* Sharp */
{USB_DEVICE(0x050D, 0x110A),.driver_info = RTL8192D}, /* Belkin - Edimax */
{USB_DEVICE(0x050D, 0x1105),.driver_info = RTL8192D}, /* Belkin - Edimax */
{USB_DEVICE(0x050D, 0x120A),.driver_info = RTL8192D}, /* Belkin - Edimax */
{USB_DEVICE(0x1668, 0x8102),.driver_info = RTL8192D}, /* - */
{USB_DEVICE(0x0BDA, 0xE194),.driver_info = RTL8192D}, /* - Edimax */
/****** 8192DU-WiFi Display Dongle ********/
{USB_DEVICE(0x2019, 0xAB2D),.driver_info = RTL8192D},/* Planex - Abocom ,5G dongle for WiFi Display */
#endif
#ifdef CONFIG_RTL8723A
{USB_DEVICE_AND_INTERFACE_INFO(USB_VENDER_ID_REALTEK, 0x8724,0xff,0xff,0xff),.driver_info = RTL8723A}, /* 8723AU 1*1 */
{USB_DEVICE_AND_INTERFACE_INFO(USB_VENDER_ID_REALTEK, 0x1724,0xff,0xff,0xff),.driver_info = RTL8723A}, /* 8723AU 1*1 */
{USB_DEVICE_AND_INTERFACE_INFO(USB_VENDER_ID_REALTEK, 0x0724,0xff,0xff,0xff),.driver_info = RTL8723A}, /* 8723AU 1*1 */
#endif
#ifdef CONFIG_RTL8188E
/*=== Realtek demoboard ===*/
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8179),.driver_info = RTL8188E}, /* 8188EUS */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x0179),.driver_info = RTL8188E}, /* 8188ETV */
/*=== Customer ID ===*/
/****** 8188EUS ********/
{USB_DEVICE(0x07B8, 0x8179),.driver_info = RTL8188E}, /* Abocom - Abocom */
#endif
#ifdef CONFIG_RTL8812A
/*=== Realtek demoboard ===*/
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8812),.driver_info = RTL8812},/* Default ID */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x881A),.driver_info = RTL8812},/* Default ID */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x881B),.driver_info = RTL8812},/* Default ID */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x881C),.driver_info = RTL8812},/* Default ID */
/*=== Customer ID ===*/
{USB_DEVICE(0x050D, 0x1106),.driver_info = RTL8812}, /* Belkin - sercomm */
{USB_DEVICE(0x2001, 0x330E),.driver_info = RTL8812}, /* D-Link - ALPHA */
{USB_DEVICE(0x7392, 0xA822),.driver_info = RTL8812}, /* Edimax - Edimax */
{USB_DEVICE(0x0DF6, 0x0074),.driver_info = RTL8812}, /* Sitecom - Edimax */
{USB_DEVICE(0x04BB, 0x0952),.driver_info = RTL8812}, /* I-O DATA - Edimax */
{USB_DEVICE(0x0789, 0x016E),.driver_info = RTL8812}, /* Logitec - Edimax */
{USB_DEVICE(0x0409, 0x0408),.driver_info = RTL8812}, /* NEC - */
{USB_DEVICE(0x0B05, 0x17D2),.driver_info = RTL8812}, /* ASUS - Edimax */
{USB_DEVICE(0x0E66, 0x0022),.driver_info = RTL8812}, /* HAWKING - Edimax */
{USB_DEVICE(0x0586, 0x3426),.driver_info = RTL8812}, /* ZyXEL - */
{USB_DEVICE(0x2001, 0x3313),.driver_info = RTL8812}, /* D-Link - ALPHA */
{USB_DEVICE(0x1058, 0x0632),.driver_info = RTL8812}, /* WD - Cybertan*/
{USB_DEVICE(0x1740, 0x0100),.driver_info = RTL8812}, /* EnGenius - EnGenius */
{USB_DEVICE(0x2019, 0xAB30),.driver_info = RTL8812}, /* Planex - Abocom */
{USB_DEVICE(0x07B8, 0x8812),.driver_info = RTL8812}, /* Abocom - Abocom */
{USB_DEVICE(0x2001, 0x3315),.driver_info = RTL8812}, /* D-Link - Cameo */
{USB_DEVICE(0x2001, 0x3316),.driver_info = RTL8812}, /* D-Link - Cameo */
#endif
#ifdef CONFIG_RTL8821A
/*=== Realtek demoboard ===*/
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x0811),.driver_info = RTL8821},/* Default ID */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x0821),.driver_info = RTL8821},/* Default ID */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x8822),.driver_info = RTL8821},/* Default ID */
{USB_DEVICE(USB_VENDER_ID_REALTEK, 0x0820),.driver_info = RTL8821},/* Default ID */
/*=== Customer ID ===*/
{USB_DEVICE(0x7392, 0xA811),.driver_info = RTL8821}, /* Edimax - Edimax */
{USB_DEVICE(0x04BB, 0x0953),.driver_info = RTL8821}, /* I-O DATA - Edimax */
{USB_DEVICE(0x2001, 0x3314),.driver_info = RTL8821}, /* D-Link - Cameo */
{USB_DEVICE(0x2001, 0x3318),.driver_info = RTL8821}, /* D-Link - Cameo */
{USB_DEVICE(0x0E66, 0x0023),.driver_info = RTL8821}, /* HAWKING - Edimax */
#endif
#ifdef CONFIG_RTL8192E
/*=== Realtek demoboard ===*/
{USB_DEVICE_AND_INTERFACE_INFO(USB_VENDER_ID_REALTEK, 0x818B,0xff,0xff,0xff),.driver_info = RTL8192E},/* Default ID */
{USB_DEVICE_AND_INTERFACE_INFO(USB_VENDER_ID_REALTEK, 0x818C,0xff,0xff,0xff),.driver_info = RTL8192E},/* Default ID */
#endif
#ifdef CONFIG_RTL8723B
//*=== Realtek demoboard ===*/
{USB_DEVICE_AND_INTERFACE_INFO(USB_VENDER_ID_REALTEK, 0xB720,0xff,0xff,0xff),.driver_info = RTL8723B}, /* 8723BU 1*1 */
//{USB_DEVICE(USB_VENDER_ID_REALTEK, 0xB720),.driver_info = RTL8723B}, /* 8723BU */
#endif
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, rtw_usb_id_tbl);
int const rtw_usb_id_len = sizeof(rtw_usb_id_tbl) / sizeof(struct usb_device_id);
static struct specific_device_id specific_device_id_tbl[] = {
{.idVendor=USB_VENDER_ID_REALTEK, .idProduct=0x8177, .flags=SPEC_DEV_ID_DISABLE_HT},//8188cu 1*1 dongole, (b/g mode only)
{.idVendor=USB_VENDER_ID_REALTEK, .idProduct=0x817E, .flags=SPEC_DEV_ID_DISABLE_HT},//8188CE-VAU USB minCard (b/g mode only)
{.idVendor=0x0b05, .idProduct=0x1791, .flags=SPEC_DEV_ID_DISABLE_HT},
{.idVendor=0x13D3, .idProduct=0x3311, .flags=SPEC_DEV_ID_DISABLE_HT},
{.idVendor=0x13D3, .idProduct=0x3359, .flags=SPEC_DEV_ID_DISABLE_HT},//Russian customer -Azwave (8188CE-VAU g mode)
#ifdef RTK_DMP_PLATFORM
{.idVendor=USB_VENDER_ID_REALTEK, .idProduct=0x8111, .flags=SPEC_DEV_ID_ASSIGN_IFNAME}, // Realtek 5G dongle for WiFi Display
{.idVendor=0x2019, .idProduct=0xAB2D, .flags=SPEC_DEV_ID_ASSIGN_IFNAME}, // PCI-Abocom 5G dongle for WiFi Display
#endif /* RTK_DMP_PLATFORM */
{}
};
struct rtw_usb_drv {
struct usb_driver usbdrv;
int drv_registered;
u8 hw_type;
};
struct rtw_usb_drv usb_drv = {
.usbdrv.name =(char*)DRV_NAME,
.usbdrv.probe = rtw_drv_init,
.usbdrv.disconnect = rtw_dev_remove,
.usbdrv.id_table = rtw_usb_id_tbl,
.usbdrv.suspend = rtw_suspend,
.usbdrv.resume = rtw_resume,
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 22))
.usbdrv.reset_resume = rtw_resume,
#endif
#ifdef CONFIG_AUTOSUSPEND
.usbdrv.supports_autosuspend = 1,
#endif
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 19))
.usbdrv.drvwrap.driver.shutdown = rtw_dev_shutdown,
#else
.usbdrv.driver.shutdown = rtw_dev_shutdown,
#endif
};
static inline int RT_usb_endpoint_dir_in(const struct usb_endpoint_descriptor *epd)
{
return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN);
}
static inline int RT_usb_endpoint_dir_out(const struct usb_endpoint_descriptor *epd)
{
return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT);
}
static inline int RT_usb_endpoint_xfer_int(const struct usb_endpoint_descriptor *epd)
{
return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT);
}
static inline int RT_usb_endpoint_xfer_bulk(const struct usb_endpoint_descriptor *epd)
{
return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK);
}
static inline int RT_usb_endpoint_is_bulk_in(const struct usb_endpoint_descriptor *epd)
{
return (RT_usb_endpoint_xfer_bulk(epd) && RT_usb_endpoint_dir_in(epd));
}
static inline int RT_usb_endpoint_is_bulk_out(const struct usb_endpoint_descriptor *epd)
{
return (RT_usb_endpoint_xfer_bulk(epd) && RT_usb_endpoint_dir_out(epd));
}
static inline int RT_usb_endpoint_is_int_in(const struct usb_endpoint_descriptor *epd)
{
return (RT_usb_endpoint_xfer_int(epd) && RT_usb_endpoint_dir_in(epd));
}
static inline int RT_usb_endpoint_num(const struct usb_endpoint_descriptor *epd)
{
return epd->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
}
static u8 rtw_init_intf_priv(struct dvobj_priv *dvobj)
{
u8 rst = _SUCCESS;
#ifdef CONFIG_USB_VENDOR_REQ_MUTEX
_rtw_mutex_init(&dvobj->usb_vendor_req_mutex);
#endif
#ifdef CONFIG_USB_VENDOR_REQ_BUFFER_PREALLOC
dvobj->usb_alloc_vendor_req_buf = rtw_zmalloc(MAX_USB_IO_CTL_SIZE);
if (dvobj->usb_alloc_vendor_req_buf == NULL) {
DBG_871X("alloc usb_vendor_req_buf failed... /n");
rst = _FAIL;
goto exit;
}
dvobj->usb_vendor_req_buf =
(u8 *)N_BYTE_ALIGMENT((SIZE_PTR)(dvobj->usb_alloc_vendor_req_buf ), ALIGNMENT_UNIT);
exit:
#endif
return rst;
}
static u8 rtw_deinit_intf_priv(struct dvobj_priv *dvobj)
{
u8 rst = _SUCCESS;
#ifdef CONFIG_USB_VENDOR_REQ_BUFFER_PREALLOC
if(dvobj->usb_vendor_req_buf)
rtw_mfree(dvobj->usb_alloc_vendor_req_buf, MAX_USB_IO_CTL_SIZE);
#endif
#ifdef CONFIG_USB_VENDOR_REQ_MUTEX
_rtw_mutex_free(&dvobj->usb_vendor_req_mutex);
#endif
return rst;
}
static struct dvobj_priv *usb_dvobj_init(struct usb_interface *usb_intf)
{
int i;
u8 val8;
int status = _FAIL;
struct dvobj_priv *pdvobjpriv;
struct usb_device_descriptor *pdev_desc;
struct usb_host_config *phost_conf;
struct usb_config_descriptor *pconf_desc;
struct usb_host_interface *phost_iface;
struct usb_interface_descriptor *piface_desc;
struct usb_host_endpoint *phost_endp;
struct usb_endpoint_descriptor *pendp_desc;
struct usb_device *pusbd;
_func_enter_;
if((pdvobjpriv = devobj_init()) == NULL) {
goto exit;
}
pdvobjpriv->pusbintf = usb_intf ;
pusbd = pdvobjpriv->pusbdev = interface_to_usbdev(usb_intf);
usb_set_intfdata(usb_intf, pdvobjpriv);
pdvobjpriv->RtNumInPipes = 0;
pdvobjpriv->RtNumOutPipes = 0;
//padapter->EepromAddressSize = 6;
//pdvobjpriv->nr_endpoint = 6;
pdev_desc = &pusbd->descriptor;
#if 0
DBG_871X("\n8712_usb_device_descriptor:\n");
DBG_871X("bLength=%x\n", pdev_desc->bLength);
DBG_871X("bDescriptorType=%x\n", pdev_desc->bDescriptorType);
DBG_871X("bcdUSB=%x\n", pdev_desc->bcdUSB);
DBG_871X("bDeviceClass=%x\n", pdev_desc->bDeviceClass);
DBG_871X("bDeviceSubClass=%x\n", pdev_desc->bDeviceSubClass);
DBG_871X("bDeviceProtocol=%x\n", pdev_desc->bDeviceProtocol);
DBG_871X("bMaxPacketSize0=%x\n", pdev_desc->bMaxPacketSize0);
DBG_871X("idVendor=%x\n", pdev_desc->idVendor);
DBG_871X("idProduct=%x\n", pdev_desc->idProduct);
DBG_871X("bcdDevice=%x\n", pdev_desc->bcdDevice);
DBG_871X("iManufacturer=%x\n", pdev_desc->iManufacturer);
DBG_871X("iProduct=%x\n", pdev_desc->iProduct);
DBG_871X("iSerialNumber=%x\n", pdev_desc->iSerialNumber);
DBG_871X("bNumConfigurations=%x\n", pdev_desc->bNumConfigurations);
#endif
phost_conf = pusbd->actconfig;
pconf_desc = &phost_conf->desc;
#if 0
DBG_871X("\n8712_usb_configuration_descriptor:\n");
DBG_871X("bLength=%x\n", pconf_desc->bLength);
DBG_871X("bDescriptorType=%x\n", pconf_desc->bDescriptorType);
DBG_871X("wTotalLength=%x\n", pconf_desc->wTotalLength);
DBG_871X("bNumInterfaces=%x\n", pconf_desc->bNumInterfaces);
DBG_871X("bConfigurationValue=%x\n", pconf_desc->bConfigurationValue);
DBG_871X("iConfiguration=%x\n", pconf_desc->iConfiguration);
DBG_871X("bmAttributes=%x\n", pconf_desc->bmAttributes);
DBG_871X("bMaxPower=%x\n", pconf_desc->bMaxPower);
#endif
//DBG_871X("\n/****** num of altsetting = (%d) ******/\n", pusb_interface->num_altsetting);
phost_iface = &usb_intf->altsetting[0];
piface_desc = &phost_iface->desc;
#if 0
DBG_871X("\n8712_usb_interface_descriptor:\n");
DBG_871X("bLength=%x\n", piface_desc->bLength);
DBG_871X("bDescriptorType=%x\n", piface_desc->bDescriptorType);
DBG_871X("bInterfaceNumber=%x\n", piface_desc->bInterfaceNumber);
DBG_871X("bAlternateSetting=%x\n", piface_desc->bAlternateSetting);
DBG_871X("bNumEndpoints=%x\n", piface_desc->bNumEndpoints);
DBG_871X("bInterfaceClass=%x\n", piface_desc->bInterfaceClass);
DBG_871X("bInterfaceSubClass=%x\n", piface_desc->bInterfaceSubClass);
DBG_871X("bInterfaceProtocol=%x\n", piface_desc->bInterfaceProtocol);
DBG_871X("iInterface=%x\n", piface_desc->iInterface);
#endif
pdvobjpriv->NumInterfaces = pconf_desc->bNumInterfaces;
pdvobjpriv->InterfaceNumber = piface_desc->bInterfaceNumber;
pdvobjpriv->nr_endpoint = piface_desc->bNumEndpoints;
//DBG_871X("\ndump usb_endpoint_descriptor:\n");
for (i = 0; i < pdvobjpriv->nr_endpoint; i++)
{
phost_endp = phost_iface->endpoint + i;
if (phost_endp)
{
pendp_desc = &phost_endp->desc;
DBG_871X("\nusb_endpoint_descriptor(%d):\n", i);
DBG_871X("bLength=%x\n",pendp_desc->bLength);
DBG_871X("bDescriptorType=%x\n",pendp_desc->bDescriptorType);
DBG_871X("bEndpointAddress=%x\n",pendp_desc->bEndpointAddress);
//DBG_871X("bmAttributes=%x\n",pendp_desc->bmAttributes);
DBG_871X("wMaxPacketSize=%d\n",le16_to_cpu(pendp_desc->wMaxPacketSize));
DBG_871X("bInterval=%x\n",pendp_desc->bInterval);
//DBG_871X("bRefresh=%x\n",pendp_desc->bRefresh);
//DBG_871X("bSynchAddress=%x\n",pendp_desc->bSynchAddress);
if (RT_usb_endpoint_is_bulk_in(pendp_desc))
{
DBG_871X("RT_usb_endpoint_is_bulk_in = %x\n", RT_usb_endpoint_num(pendp_desc));
pdvobjpriv->RtInPipe[pdvobjpriv->RtNumInPipes] = RT_usb_endpoint_num(pendp_desc);
pdvobjpriv->RtNumInPipes++;
}
else if (RT_usb_endpoint_is_int_in(pendp_desc))
{
DBG_871X("RT_usb_endpoint_is_int_in = %x, Interval = %x\n", RT_usb_endpoint_num(pendp_desc),pendp_desc->bInterval);
pdvobjpriv->RtInPipe[pdvobjpriv->RtNumInPipes] = RT_usb_endpoint_num(pendp_desc);
pdvobjpriv->RtNumInPipes++;
}
else if (RT_usb_endpoint_is_bulk_out(pendp_desc))
{
DBG_871X("RT_usb_endpoint_is_bulk_out = %x\n", RT_usb_endpoint_num(pendp_desc));
pdvobjpriv->RtOutPipe[pdvobjpriv->RtNumOutPipes] = RT_usb_endpoint_num(pendp_desc);
pdvobjpriv->RtNumOutPipes++;
}
pdvobjpriv->ep_num[i] = RT_usb_endpoint_num(pendp_desc);
}
}
DBG_871X("nr_endpoint=%d, in_num=%d, out_num=%d\n\n", pdvobjpriv->nr_endpoint, pdvobjpriv->RtNumInPipes, pdvobjpriv->RtNumOutPipes);
switch(pusbd->speed) {
case USB_SPEED_LOW:
DBG_871X("USB_SPEED_LOW\n");
pdvobjpriv->usb_speed = RTW_USB_SPEED_1_1;
break;
case USB_SPEED_FULL:
DBG_871X("USB_SPEED_FULL\n");
pdvobjpriv->usb_speed = RTW_USB_SPEED_1_1;
break;
case USB_SPEED_HIGH:
DBG_871X("USB_SPEED_HIGH\n");
pdvobjpriv->usb_speed = RTW_USB_SPEED_2;
break;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,31))
case USB_SPEED_SUPER:
DBG_871X("USB_SPEED_SUPER\n");
pdvobjpriv->usb_speed = RTW_USB_SPEED_3;
break;
#endif
default:
DBG_871X("USB_SPEED_UNKNOWN(%x)\n",pusbd->speed);
pdvobjpriv->usb_speed = RTW_USB_SPEED_UNKNOWN;
break;
}
if (pdvobjpriv->usb_speed == RTW_USB_SPEED_UNKNOWN) {
DBG_871X("UNKNOWN USB SPEED MODE, ERROR !!!\n");
goto free_dvobj;
}
if (rtw_init_intf_priv(pdvobjpriv) == _FAIL) {
RT_TRACE(_module_os_intfs_c_,_drv_err_,("\n Can't INIT rtw_init_intf_priv\n"));
goto free_dvobj;
}
//.3 misc
_rtw_init_sema(&(pdvobjpriv->usb_suspend_sema), 0);
rtw_reset_continual_io_error(pdvobjpriv);
usb_get_dev(pusbd);
status = _SUCCESS;
free_dvobj:
if (status != _SUCCESS && pdvobjpriv) {
usb_set_intfdata(usb_intf, NULL);
devobj_deinit(pdvobjpriv);
pdvobjpriv = NULL;
}
exit:
_func_exit_;
return pdvobjpriv;
}
static void usb_dvobj_deinit(struct usb_interface *usb_intf)
{
struct dvobj_priv *dvobj = usb_get_intfdata(usb_intf);
_func_enter_;
usb_set_intfdata(usb_intf, NULL);
if (dvobj) {
//Modify condition for 92DU DMDP 2010.11.18, by Thomas
if ((dvobj->NumInterfaces != 2 && dvobj->NumInterfaces != 3)
|| (dvobj->InterfaceNumber == 1)) {
if (interface_to_usbdev(usb_intf)->state != USB_STATE_NOTATTACHED) {
//If we didn't unplug usb dongle and remove/insert modlue, driver fails on sitesurvey for the first time when device is up .
//Reset usb port for sitesurvey fail issue. 2009.8.13, by Thomas
DBG_871X("usb attached..., try to reset usb device\n");
usb_reset_device(interface_to_usbdev(usb_intf));
}
}
rtw_deinit_intf_priv(dvobj);
devobj_deinit(dvobj);
}
//DBG_871X("%s %d\n", __func__, ATOMIC_READ(&usb_intf->dev.kobj.kref.refcount));
usb_put_dev(interface_to_usbdev(usb_intf));
_func_exit_;
}
static void rtw_decide_chip_type_by_usb_info(_adapter *padapter, const struct usb_device_id *pdid)
{
padapter->chip_type = pdid->driver_info;
#ifdef CONFIG_RTL8192C
if(padapter->chip_type == RTL8188C_8192C)
rtl8192cu_set_hw_type(padapter);
#endif
#ifdef CONFIG_RTL8192D
if(padapter->chip_type == RTL8192D)
rtl8192du_set_hw_type(padapter);
#endif
#ifdef CONFIG_RTL8723A
if(padapter->chip_type == RTL8723A)
rtl8723au_set_hw_type(padapter);
#endif
#ifdef CONFIG_RTL8188E
if(padapter->chip_type == RTL8188E)
rtl8188eu_set_hw_type(padapter);
#endif
#if defined(CONFIG_RTL8812A) || defined(CONFIG_RTL8821A)
if(padapter->chip_type == RTL8812 || padapter->chip_type == RTL8821)
rtl8812au_set_hw_type(padapter);
#endif
#ifdef CONFIG_RTL8192E
if(padapter->chip_type == RTL8192E)
rtl8192eu_set_hw_type(padapter);
#endif
#ifdef CONFIG_RTL8723B
if(padapter->chip_type == RTL8723B)
rtl8723bu_set_hw_type(padapter);
#endif
}
void rtw_set_hal_ops(_adapter *padapter)
{
#ifdef CONFIG_RTL8192C
if(padapter->chip_type == RTL8188C_8192C)
rtl8192cu_set_hal_ops(padapter);
#endif
#ifdef CONFIG_RTL8192D
if(padapter->chip_type == RTL8192D)
rtl8192du_set_hal_ops(padapter);
#endif
#ifdef CONFIG_RTL8723A
if(padapter->chip_type == RTL8723A)
rtl8723au_set_hal_ops(padapter);
#endif
#ifdef CONFIG_RTL8188E
if(padapter->chip_type == RTL8188E)
rtl8188eu_set_hal_ops(padapter);
#endif
#if defined(CONFIG_RTL8812A) || defined(CONFIG_RTL8821A)
if(padapter->chip_type == RTL8812 || padapter->chip_type == RTL8821)
rtl8812au_set_hal_ops(padapter);
#endif
#ifdef CONFIG_RTL8192E
if(padapter->chip_type == RTL8192E)
rtl8192eu_set_hal_ops(padapter);
#endif
#ifdef CONFIG_RTL8723B
if(padapter->chip_type == RTL8723B)
rtl8723bu_set_hal_ops(padapter);
#endif
}
void usb_set_intf_ops(_adapter *padapter,struct _io_ops *pops)
{
#ifdef CONFIG_RTL8192C
if(padapter->chip_type == RTL8188C_8192C)
rtl8192cu_set_intf_ops(pops);
#endif
#ifdef CONFIG_RTL8192D
if(padapter->chip_type == RTL8192D)
rtl8192du_set_intf_ops(pops);
#endif
#ifdef CONFIG_RTL8723A
if(padapter->chip_type == RTL8723A)
rtl8723au_set_intf_ops(pops);
#endif
#ifdef CONFIG_RTL8188E
if(padapter->chip_type == RTL8188E)
rtl8188eu_set_intf_ops(pops);
#endif
#if defined(CONFIG_RTL8812A) || defined(CONFIG_RTL8821A)
if(padapter->chip_type == RTL8812 || padapter->chip_type == RTL8821)
rtl8812au_set_intf_ops(pops);
#endif
#ifdef CONFIG_RTL8192E
if(padapter->chip_type == RTL8192E)
rtl8192eu_set_intf_ops(pops);
#endif
#ifdef CONFIG_RTL8723B
if(padapter->chip_type == RTL8723B)
rtl8723bu_set_intf_ops(pops);
#endif
}
static void usb_intf_start(_adapter *padapter)
{
RT_TRACE(_module_hci_intfs_c_,_drv_err_,("+usb_intf_start\n"));
rtw_hal_inirp_init(padapter);
RT_TRACE(_module_hci_intfs_c_,_drv_err_,("-usb_intf_start\n"));
}
static void usb_intf_stop(_adapter *padapter)
{
RT_TRACE(_module_hci_intfs_c_,_drv_err_,("+usb_intf_stop\n"));
//disabel_hw_interrupt
if(padapter->bSurpriseRemoved == _FALSE)
{
//device still exists, so driver can do i/o operation
//TODO:
RT_TRACE(_module_hci_intfs_c_,_drv_err_,("SurpriseRemoved==_FALSE\n"));
}
//cancel in irp
rtw_hal_inirp_deinit(padapter);
//cancel out irp
rtw_write_port_cancel(padapter);
//todo:cancel other irps
RT_TRACE(_module_hci_intfs_c_,_drv_err_,("-usb_intf_stop\n"));
}
static void process_spec_devid(const struct usb_device_id *pdid)
{
u16 vid, pid;
u32 flags;
int i;
int num = sizeof(specific_device_id_tbl)/sizeof(struct specific_device_id);
for(i=0; i<num; i++)
{
vid = specific_device_id_tbl[i].idVendor;
pid = specific_device_id_tbl[i].idProduct;
flags = specific_device_id_tbl[i].flags;
#ifdef CONFIG_80211N_HT
if((pdid->idVendor==vid) && (pdid->idProduct==pid) && (flags&SPEC_DEV_ID_DISABLE_HT))
{
rtw_ht_enable = 0;
rtw_bw_mode = 0;
rtw_ampdu_enable = 0;
}
#endif
#ifdef RTK_DMP_PLATFORM
// Change the ifname to wlan10 when PC side WFD dongle plugin on DMP platform.
// It is used to distinguish between normal and PC-side wifi dongle/module.
if((pdid->idVendor==vid) && (pdid->idProduct==pid) && (flags&SPEC_DEV_ID_ASSIGN_IFNAME))
{
extern char* ifname;
strncpy(ifname, "wlan10", 6);
//DBG_871X("%s()-%d: ifname=%s, vid=%04X, pid=%04X\n", __FUNCTION__, __LINE__, ifname, vid, pid);
}
#endif /* RTK_DMP_PLATFORM */
}
}
#ifdef SUPPORT_HW_RFOFF_DETECTED
int rtw_hw_suspend(_adapter *padapter )
{
struct pwrctrl_priv *pwrpriv;
struct usb_interface *pusb_intf;
struct net_device *pnetdev;
_func_enter_;
if(NULL==padapter)
goto error_exit;
if((_FALSE==padapter->bup) || (_TRUE == padapter->bDriverStopped)||(_TRUE==padapter->bSurpriseRemoved))
{
DBG_871X("padapter->bup=%d bDriverStopped=%d bSurpriseRemoved = %d\n",
padapter->bup, padapter->bDriverStopped,padapter->bSurpriseRemoved);
goto error_exit;
}
pwrpriv = adapter_to_pwrctl(padapter);
pusb_intf = adapter_to_dvobj(padapter)->pusbintf;
pnetdev = padapter->pnetdev;
LeaveAllPowerSaveMode(padapter);
DBG_871X("==> rtw_hw_suspend\n");
_enter_pwrlock(&pwrpriv->lock);
pwrpriv->bips_processing = _TRUE;
//padapter->net_closed = _TRUE;
//s1.
if(pnetdev)
{
netif_carrier_off(pnetdev);
rtw_netif_stop_queue(pnetdev);
}
//s2.
rtw_disassoc_cmd(padapter, 500, _FALSE);
//s2-2. indicate disconnect to os
//rtw_indicate_disconnect(padapter);
{
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
if(check_fwstate(pmlmepriv, _FW_LINKED))
{
_clr_fwstate_(pmlmepriv, _FW_LINKED);
rtw_led_control(padapter, LED_CTL_NO_LINK);
rtw_os_indicate_disconnect(padapter);
#ifdef CONFIG_LPS
//donnot enqueue cmd
rtw_lps_ctrl_wk_cmd(padapter, LPS_CTRL_DISCONNECT, 0);
#endif
}
}
//s2-3.
rtw_free_assoc_resources(padapter, 1);
//s2-4.
rtw_free_network_queue(padapter,_TRUE);
#ifdef CONFIG_IPS
rtw_ips_dev_unload(padapter);
#endif
pwrpriv->rf_pwrstate = rf_off;
pwrpriv->bips_processing = _FALSE;
_exit_pwrlock(&pwrpriv->lock);
_func_exit_;
return 0;
error_exit:
DBG_871X("%s, failed \n",__FUNCTION__);
return (-1);
}
int rtw_hw_resume(_adapter *padapter)
{
struct pwrctrl_priv *pwrpriv = adapter_to_pwrctl(padapter);
struct usb_interface *pusb_intf = adapter_to_dvobj(padapter)->pusbintf;
struct net_device *pnetdev = padapter->pnetdev;
_func_enter_;
DBG_871X("==> rtw_hw_resume\n");
_enter_pwrlock(&pwrpriv->lock);
pwrpriv->bips_processing = _TRUE;
rtw_reset_drv_sw(padapter);
if(pm_netdev_open(pnetdev,_FALSE) != 0)
{
_exit_pwrlock(&pwrpriv->lock);
goto error_exit;
}
netif_device_attach(pnetdev);
netif_carrier_on(pnetdev);
if(!rtw_netif_queue_stopped(pnetdev))
rtw_netif_start_queue(pnetdev);
else
rtw_netif_wake_queue(pnetdev);
pwrpriv->bkeepfwalive = _FALSE;
pwrpriv->brfoffbyhw = _FALSE;
pwrpriv->rf_pwrstate = rf_on;
pwrpriv->bips_processing = _FALSE;
_exit_pwrlock(&pwrpriv->lock);
_func_exit_;
return 0;
error_exit:
DBG_871X("%s, Open net dev failed \n",__FUNCTION__);
return (-1);
}
#endif
#ifdef CONFIG_SUSPEND_REFINE
static int rtw_suspend(struct usb_interface *pusb_intf, pm_message_t message)
{
int ret = 0;
struct dvobj_priv *dvobj = usb_get_intfdata(pusb_intf);
_adapter *padapter = dvobj->if1;
struct pwrctrl_priv *pwrpriv = adapter_to_pwrctl(padapter);
if((padapter->bup) || (padapter->bDriverStopped == _FALSE)||(padapter->bSurpriseRemoved == _FALSE))
{
#ifdef CONFIG_AUTOSUSPEND
if(pwrpriv->bInternalAutoSuspend ){
#ifdef SUPPORT_HW_RFOFF_DETECTED
// The FW command register update must after MAC and FW init ready.
if((padapter->bFWReady) && (pwrpriv->bHWPwrPindetect ) && (padapter->registrypriv.usbss_enable ))
{
u8 bOpen = _TRUE;
rtw_interface_ps_func(padapter,HAL_USB_SELECT_SUSPEND,&bOpen);
//rtl8192c_set_FwSelectSuspend_cmd(padapter,_TRUE ,500);//note fw to support hw power down ping detect
}
#endif//SUPPORT_HW_RFOFF_DETECTED
}
#endif//CONFIG_AUTOSUSPEND
}
ret = rtw_suspend_common(padapter);
return ret;
}
int rtw_resume_process(_adapter *padapter)
{
int ret,pm_cnt = 0;
struct pwrctrl_priv *pwrpriv = adapter_to_pwrctl(padapter);
#if defined(CONFIG_BT_COEXIST) && defined(CONFIG_AUTOSUSPEND) //add by amy for 8723as-vau
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,32))
DBG_871X("%s...pm_usage_cnt(%d) pwrpriv->bAutoResume=%x. ....\n",__func__,atomic_read(&(adapter_to_dvobj(padapter)->pusbintf->pm_usage_cnt)),pwrpriv->bAutoResume);
pm_cnt=atomic_read(&(adapter_to_dvobj(padapter)->pusbintf->pm_usage_cnt));
#else
DBG_871X("...pm_usage_cnt(%d).....\n", adapter_to_dvobj(padapter)->pusbintf->pm_usage_cnt);
pm_cnt = adapter_to_dvobj(padapter)->pusbintf->pm_usage_cnt;
#endif
DBG_871X("pwrpriv->bAutoResume (%x)\n",pwrpriv->bAutoResume );
if( _TRUE == pwrpriv->bAutoResume ){
pwrpriv->bInternalAutoSuspend = _FALSE;
pwrpriv->bAutoResume=_FALSE;
DBG_871X("pwrpriv->bAutoResume (%x) pwrpriv->bInternalAutoSuspend(%x)\n",pwrpriv->bAutoResume,pwrpriv->bInternalAutoSuspend );
}
#endif //#ifdef CONFIG_BT_COEXIST &CONFIG_AUTOSUSPEND&
#if defined (CONFIG_WOWLAN) || defined (CONFIG_AP_WOWLAN)
/*
* Due to usb wow suspend flow will cancel read/write port via intf_stop and
* bReadPortCancel and bWritePortCancel are set _TRUE in intf_stop.
* But they will not be clear in intf_start during wow resume flow.
* It should move to os_intf in the feature.
*/
RTW_ENABLE_FUNC(padapter, DF_RX_BIT);
RTW_ENABLE_FUNC(padapter, DF_TX_BIT);
#endif
ret = rtw_resume_common(padapter);
#ifdef CONFIG_AUTOSUSPEND
if(pwrpriv->bInternalAutoSuspend )
{
#ifdef SUPPORT_HW_RFOFF_DETECTED
// The FW command register update must after MAC and FW init ready.
if((padapter->bFWReady) && (pwrpriv->bHWPwrPindetect) && (padapter->registrypriv.usbss_enable ))
{
//rtl8192c_set_FwSelectSuspend_cmd(padapter,_FALSE ,500);//note fw to support hw power down ping detect
u8 bOpen = _FALSE;
rtw_interface_ps_func(padapter,HAL_USB_SELECT_SUSPEND,&bOpen);
}
#endif
#ifdef CONFIG_BT_COEXIST // for 8723as-vau
DBG_871X("pwrpriv->bAutoResume (%x)\n",pwrpriv->bAutoResume );
if( _TRUE == pwrpriv->bAutoResume ){
pwrpriv->bInternalAutoSuspend = _FALSE;
pwrpriv->bAutoResume=_FALSE;
DBG_871X("pwrpriv->bAutoResume (%x) pwrpriv->bInternalAutoSuspend(%x)\n",pwrpriv->bAutoResume,pwrpriv->bInternalAutoSuspend );
}
#else //#ifdef CONFIG_BT_COEXIST
pwrpriv->bInternalAutoSuspend = _FALSE;
#endif //#ifdef CONFIG_BT_COEXIST
pwrpriv->brfoffbyhw = _FALSE;
}
#endif//CONFIG_AUTOSUSPEND
return ret;
}
#else
static int rtw_suspend(struct usb_interface *pusb_intf, pm_message_t message)
{
struct dvobj_priv *dvobj = usb_get_intfdata(pusb_intf);
_adapter *padapter = dvobj->if1;
struct net_device *pnetdev = padapter->pnetdev;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct pwrctrl_priv *pwrpriv = dvobj_to_pwrctl(dvobj);
struct usb_device *usb_dev = interface_to_usbdev(pusb_intf);
#ifdef CONFIG_WOWLAN
struct wowlan_ioctl_param poidparam;
#endif // CONFIG_WOWLAN
int ret = 0;
u32 start_time = rtw_get_current_time();
_func_enter_;
DBG_871X("==> %s (%s:%d)\n",__FUNCTION__, current->comm, current->pid);
#ifdef CONFIG_WOWLAN
if (check_fwstate(pmlmepriv, _FW_LINKED))
pwrpriv->wowlan_mode = _TRUE;
else
pwrpriv->wowlan_mode = _FALSE;
#endif
#ifdef CONFIG_IOL_READ_EFUSE_MAP
if(!padapter->bup){
u8 bMacPwrCtrlOn = _FALSE;
rtw_hal_get_hwreg(padapter, HW_VAR_APFM_ON_MAC, &bMacPwrCtrlOn);
if(bMacPwrCtrlOn)
rtw_hal_power_off(padapter);
}
#endif
if((!padapter->bup) || (padapter->bDriverStopped)||(padapter->bSurpriseRemoved))
{
DBG_871X("padapter->bup=%d bDriverStopped=%d bSurpriseRemoved = %d\n",
padapter->bup, padapter->bDriverStopped,padapter->bSurpriseRemoved);
goto exit;
}
if(pwrpriv->bInternalAutoSuspend )
{
#ifdef CONFIG_AUTOSUSPEND
#ifdef SUPPORT_HW_RFOFF_DETECTED
// The FW command register update must after MAC and FW init ready.
if((padapter->bFWReady) && (pwrpriv->bHWPwrPindetect ) && (padapter->registrypriv.usbss_enable ))
{
u8 bOpen = _TRUE;
rtw_interface_ps_func(padapter,HAL_USB_SELECT_SUSPEND,&bOpen);
//rtl8192c_set_FwSelectSuspend_cmd(padapter,_TRUE ,500);//note fw to support hw power down ping detect
}
#endif
#endif
}
pwrpriv->bInSuspend = _TRUE;
rtw_cancel_all_timer(padapter);
LeaveAllPowerSaveMode(padapter);
rtw_stop_cmd_thread(padapter);
_enter_pwrlock(&pwrpriv->lock);
//padapter->net_closed = _TRUE;
//s1.
if(pnetdev)
{
netif_carrier_off(pnetdev);
rtw_netif_stop_queue(pnetdev);
}
#ifdef CONFIG_WOWLAN
if(pwrpriv->bSupportRemoteWakeup==_TRUE && pwrpriv->wowlan_mode==_TRUE){
if (rtw_port_switch_chk(padapter))
rtw_hal_set_hwreg(padapter, HW_VAR_PORT_SWITCH, NULL);
//set H2C command
poidparam.subcode=WOWLAN_ENABLE;
padapter->HalFunc.SetHwRegHandler(padapter,HW_VAR_WOWLAN,(u8 *)&poidparam);
}
else
#else
{
//s2.
rtw_disassoc_cmd(padapter, 0, _FALSE);
}
#endif //CONFIG_WOWLAN
if (rtw_chk_roam_flags(padapter, RTW_ROAM_ON_RESUME)) {
if(check_fwstate(pmlmepriv, WIFI_STATION_STATE)
&& check_fwstate(pmlmepriv, _FW_LINKED))
{
//DBG_871X("%s:%d assoc_ssid:%s\n", __FUNCTION__, __LINE__, pmlmepriv->assoc_ssid.Ssid);
DBG_871X("%s:%d %s(" MAC_FMT "), length:%d assoc_ssid.length:%d\n",__FUNCTION__, __LINE__,
pmlmepriv->cur_network.network.Ssid.Ssid,
MAC_ARG(pmlmepriv->cur_network.network.MacAddress),
pmlmepriv->cur_network.network.Ssid.SsidLength,
pmlmepriv->assoc_ssid.SsidLength);
rtw_set_to_roam(padapter, 1);
}
}
//s2-2. indicate disconnect to os
rtw_indicate_disconnect(padapter);
//s2-3.
rtw_free_assoc_resources(padapter, 1);
#ifdef CONFIG_AUTOSUSPEND
if(!pwrpriv->bInternalAutoSuspend )
#endif
//s2-4.
rtw_free_network_queue(padapter, _TRUE);
rtw_dev_unload(padapter);
#ifdef CONFIG_AUTOSUSPEND
pwrpriv->rf_pwrstate = rf_off;
pwrpriv->bips_processing = _FALSE;
#endif
_exit_pwrlock(&pwrpriv->lock);
if(check_fwstate(pmlmepriv, _FW_UNDER_SURVEY))
rtw_indicate_scan_done(padapter, 1);
if(check_fwstate(pmlmepriv, _FW_UNDER_LINKING))
rtw_indicate_disconnect(padapter);
exit:
DBG_871X("<=== %s return %d.............. in %dms\n", __FUNCTION__
, ret, rtw_get_passing_time_ms(start_time));
_func_exit_;
return ret;
}
int rtw_resume_process(_adapter *padapter)
{
struct net_device *pnetdev;
struct pwrctrl_priv *pwrpriv = NULL;
int ret = -1;
u32 start_time = rtw_get_current_time();
#ifdef CONFIG_BT_COEXIST
u8 pm_cnt;
#endif //#ifdef CONFIG_BT_COEXIST
_func_enter_;
DBG_871X("==> %s (%s:%d)\n",__FUNCTION__, current->comm, current->pid);
if(padapter) {
pnetdev= padapter->pnetdev;
pwrpriv = adapter_to_pwrctl(padapter);
} else {
goto exit;
}
_enter_pwrlock(&pwrpriv->lock);
#ifdef CONFIG_BT_COEXIST
#ifdef CONFIG_AUTOSUSPEND
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,32))
DBG_871X("%s...pm_usage_cnt(%d) pwrpriv->bAutoResume=%x. ....\n",__func__,atomic_read(&(adapter_to_dvobj(padapter)->pusbintf->pm_usage_cnt)),pwrpriv->bAutoResume);
pm_cnt=atomic_read(&(adapter_to_dvobj(padapter)->pusbintf->pm_usage_cnt));
#else
DBG_871X("...pm_usage_cnt(%d).....\n", adapter_to_dvobj(padapter)->pusbintf->pm_usage_cnt);
pm_cnt = adapter_to_dvobj(padapter)->pusbintf->pm_usage_cnt;
#endif
DBG_871X("pwrpriv->bAutoResume (%x)\n",pwrpriv->bAutoResume );
if( _TRUE == pwrpriv->bAutoResume ){
pwrpriv->bInternalAutoSuspend = _FALSE;
pwrpriv->bAutoResume=_FALSE;
DBG_871X("pwrpriv->bAutoResume (%x) pwrpriv->bInternalAutoSuspend(%x)\n",pwrpriv->bAutoResume,pwrpriv->bInternalAutoSuspend );
}
#endif //#ifdef CONFIG_AUTOSUSPEND
#endif //#ifdef CONFIG_BT_COEXIST
rtw_reset_drv_sw(padapter);
pwrpriv->bkeepfwalive = _FALSE;
DBG_871X("bkeepfwalive(%x)\n",pwrpriv->bkeepfwalive);
if(pm_netdev_open(pnetdev,_TRUE) != 0){
_exit_pwrlock(&pwrpriv->lock);
goto exit;
}
netif_device_attach(pnetdev);
netif_carrier_on(pnetdev);
#ifdef CONFIG_AUTOSUSPEND
if(pwrpriv->bInternalAutoSuspend )
{
#ifdef CONFIG_AUTOSUSPEND
#ifdef SUPPORT_HW_RFOFF_DETECTED
// The FW command register update must after MAC and FW init ready.
if((padapter->bFWReady) && (pwrpriv->bHWPwrPindetect) && (padapter->registrypriv.usbss_enable ))
{
//rtl8192c_set_FwSelectSuspend_cmd(padapter,_FALSE ,500);//note fw to support hw power down ping detect
u8 bOpen = _FALSE;
rtw_interface_ps_func(padapter,HAL_USB_SELECT_SUSPEND,&bOpen);
}
#endif
#endif
#ifdef CONFIG_BT_COEXIST
DBG_871X("pwrpriv->bAutoResume (%x)\n",pwrpriv->bAutoResume );
if( _TRUE == pwrpriv->bAutoResume ){
pwrpriv->bInternalAutoSuspend = _FALSE;
pwrpriv->bAutoResume=_FALSE;
DBG_871X("pwrpriv->bAutoResume (%x) pwrpriv->bInternalAutoSuspend(%x)\n",pwrpriv->bAutoResume,pwrpriv->bInternalAutoSuspend );
}
#else //#ifdef CONFIG_BT_COEXIST
pwrpriv->bInternalAutoSuspend = _FALSE;
#endif //#ifdef CONFIG_BT_COEXIST
pwrpriv->brfoffbyhw = _FALSE;
}
#endif
_exit_pwrlock(&pwrpriv->lock);
if( padapter->pid[1]!=0) {
DBG_871X("pid[1]:%d\n",padapter->pid[1]);
rtw_signal_process(padapter->pid[1], SIGUSR2);
}
if (rtw_chk_roam_flags(padapter, RTW_ROAM_ON_RESUME))
rtw_roaming(padapter, NULL);
ret = 0;
exit:
#ifdef CONFIG_RESUME_IN_WORKQUEUE
rtw_unlock_suspend();
#endif //CONFIG_RESUME_IN_WORKQUEUE
pwrpriv->bInSuspend = _FALSE;
DBG_871X("<=== %s return %d.............. in %dms\n", __FUNCTION__
, ret, rtw_get_passing_time_ms(start_time));
_func_exit_;
return ret;
}
#endif
static int rtw_resume(struct usb_interface *pusb_intf)
{
struct dvobj_priv *dvobj = usb_get_intfdata(pusb_intf);
_adapter *padapter = dvobj->if1;
struct net_device *pnetdev = padapter->pnetdev;
struct pwrctrl_priv *pwrpriv = dvobj_to_pwrctl(dvobj);
int ret = 0;
if(pwrpriv->bInternalAutoSuspend ){
ret = rtw_resume_process(padapter);
} else {
#ifdef CONFIG_RESUME_IN_WORKQUEUE
rtw_resume_in_workqueue(pwrpriv);
#else
if (rtw_is_earlysuspend_registered(pwrpriv)
#ifdef CONFIG_WOWLAN
&& !pwrpriv->wowlan_mode
#endif /* CONFIG_WOWLAN */
) {
/* jeff: bypass resume here, do in late_resume */
rtw_set_do_late_resume(pwrpriv, _TRUE);
} else {
ret = rtw_resume_process(padapter);
}
#endif /* CONFIG_RESUME_IN_WORKQUEUE */
}
return ret;
}
#ifdef CONFIG_AUTOSUSPEND
void autosuspend_enter(_adapter* padapter)
{
struct dvobj_priv *dvobj = adapter_to_dvobj(padapter);
struct pwrctrl_priv *pwrpriv = dvobj_to_pwrctl(dvobj);
DBG_871X("==>autosuspend_enter...........\n");
pwrpriv->bInternalAutoSuspend = _TRUE;
pwrpriv->bips_processing = _TRUE;
if(rf_off == pwrpriv->change_rfpwrstate )
{
#ifndef CONFIG_BT_COEXIST
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,35))
usb_enable_autosuspend(dvobj->pusbdev);
#else
dvobj->pusbdev->autosuspend_disabled = 0;//autosuspend disabled by the user
#endif
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,33))
usb_autopm_put_interface(dvobj->pusbintf);
#elif (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,20))
usb_autopm_enable(dvobj->pusbintf);
#else
usb_autosuspend_device(dvobj->pusbdev, 1);
#endif
#else //#ifndef CONFIG_BT_COEXIST
if(1==pwrpriv->autopm_cnt){
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,35))
usb_enable_autosuspend(dvobj->pusbdev);
#else
dvobj->pusbdev->autosuspend_disabled = 0;//autosuspend disabled by the user
#endif
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,33))
usb_autopm_put_interface(dvobj->pusbintf);
#elif (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,20))
usb_autopm_enable(dvobj->pusbintf);
#else
usb_autosuspend_device(dvobj->pusbdev, 1);
#endif
pwrpriv->autopm_cnt --;
}
else
DBG_871X("0!=pwrpriv->autopm_cnt[%d] didn't usb_autopm_put_interface\n", pwrpriv->autopm_cnt);
#endif //#ifndef CONFIG_BT_COEXIST
}
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,32))
DBG_871X("...pm_usage_cnt(%d).....\n", atomic_read(&(dvobj->pusbintf->pm_usage_cnt)));
#else
DBG_871X("...pm_usage_cnt(%d).....\n", dvobj->pusbintf->pm_usage_cnt);
#endif
}
int autoresume_enter(_adapter* padapter)
{
int result = _SUCCESS;
struct security_priv* psecuritypriv=&(padapter->securitypriv);
struct mlme_ext_priv *pmlmeext = &padapter->mlmeextpriv;
struct mlme_ext_info *pmlmeinfo = &(pmlmeext->mlmext_info);
struct dvobj_priv *dvobj = adapter_to_dvobj(padapter);
struct pwrctrl_priv *pwrpriv = dvobj_to_pwrctl(dvobj);
DBG_871X("====> autoresume_enter \n");
if(rf_off == pwrpriv->rf_pwrstate )
{
pwrpriv->ps_flag = _FALSE;
#ifndef CONFIG_BT_COEXIST
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,33))
if (usb_autopm_get_interface(dvobj->pusbintf) < 0)
{
DBG_871X( "can't get autopm: %d\n", result);
result = _FAIL;
goto error_exit;
}
#elif (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,20))
usb_autopm_disable(dvobj->pusbintf);
#else
usb_autoresume_device(dvobj->pusbdev, 1);
#endif
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,32))
DBG_871X("...pm_usage_cnt(%d).....\n", atomic_read(&(dvobj->pusbintf->pm_usage_cnt)));
#else
DBG_871X("...pm_usage_cnt(%d).....\n", dvobj->pusbintf->pm_usage_cnt);
#endif
#else //#ifndef CONFIG_BT_COEXIST
pwrpriv->bAutoResume=_TRUE;
if(0==pwrpriv->autopm_cnt){
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,33))
if (usb_autopm_get_interface(dvobj->pusbintf) < 0)
{
DBG_871X( "can't get autopm: %d\n", result);
result = _FAIL;
goto error_exit;
}
#elif (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,20))
usb_autopm_disable(dvobj->pusbintf);
#else
usb_autoresume_device(dvobj->pusbdev, 1);
#endif
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,32))
DBG_871X("...pm_usage_cnt(%d).....\n", atomic_read(&(dvobj->pusbintf->pm_usage_cnt)));
#else
DBG_871X("...pm_usage_cnt(%d).....\n", dvobj->pusbintf->pm_usage_cnt);
#endif
pwrpriv->autopm_cnt++;
}
else
DBG_871X("0!=pwrpriv->autopm_cnt[%d] didn't usb_autopm_get_interface\n",pwrpriv->autopm_cnt);
#endif //#ifndef CONFIG_BT_COEXIST
}
DBG_871X("<==== autoresume_enter \n");
error_exit:
return result;
}
#endif
#ifdef CONFIG_PLATFORM_RTD2880B
extern void rtd2885_wlan_netlink_sendMsg(char *action_string, char *name);
#endif
/*
* drv_init() - a device potentially for us
*
* notes: drv_init() is called when the bus driver has located a card for us to support.
* We accept the new device by returning 0.
*/
_adapter *rtw_sw_export = NULL;
_adapter *rtw_usb_if1_init(struct dvobj_priv *dvobj,
struct usb_interface *pusb_intf, const struct usb_device_id *pdid)
{
_adapter *padapter = NULL;
struct net_device *pnetdev = NULL;
int status = _FAIL;
if ((padapter = (_adapter *)rtw_zvmalloc(sizeof(*padapter))) == NULL) {
goto exit;
}
padapter->dvobj = dvobj;
dvobj->if1 = padapter;
padapter->bDriverStopped=_TRUE;
dvobj->padapters[dvobj->iface_nums++] = padapter;
padapter->iface_id = IFACE_ID0;
#if defined(CONFIG_CONCURRENT_MODE) || defined(CONFIG_DUALMAC_CONCURRENT)
//set adapter_type/iface type for primary padapter
padapter->isprimary = _TRUE;
padapter->adapter_type = PRIMARY_ADAPTER;
#ifndef CONFIG_HWPORT_SWAP
padapter->iface_type = IFACE_PORT0;
#else
padapter->iface_type = IFACE_PORT1;
#endif
#endif
//step 1-1., decide the chip_type via driver_info
padapter->interface_type = RTW_USB;
rtw_decide_chip_type_by_usb_info(padapter, pdid);
if (rtw_handle_dualmac(padapter, 1) != _SUCCESS)
goto free_adapter;
if((pnetdev = rtw_init_netdev(padapter)) == NULL) {
goto handle_dualmac;
}
SET_NETDEV_DEV(pnetdev, dvobj_to_dev(dvobj));
padapter = rtw_netdev_priv(pnetdev);
#ifdef CONFIG_IOCTL_CFG80211
if(rtw_wdev_alloc(padapter, dvobj_to_dev(dvobj)) != 0) {
goto handle_dualmac;
}
#endif
//step 2. hook HalFunc, allocate HalData
//hal_set_hal_ops(padapter);
rtw_set_hal_ops(padapter);
padapter->intf_start=&usb_intf_start;
padapter->intf_stop=&usb_intf_stop;
//step init_io_priv
rtw_init_io_priv(padapter,usb_set_intf_ops);
//step read_chip_version
rtw_hal_read_chip_version(padapter);
//step usb endpoint mapping
rtw_hal_chip_configure(padapter);
#ifdef CONFIG_BT_COEXIST
rtw_btcoex_Initialize(padapter);
#endif // CONFIG_BT_COEXIST
//step read efuse/eeprom data and get mac_addr
rtw_hal_read_chip_info(padapter);
//step 5.
if(rtw_init_drv_sw(padapter) ==_FAIL) {
RT_TRACE(_module_hci_intfs_c_,_drv_err_,("Initialize driver software resource Failed!\n"));
goto free_hal_data;
}
#ifdef CONFIG_PM
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,18))
if(dvobj_to_pwrctl(dvobj)->bSupportRemoteWakeup)
{
dvobj->pusbdev->do_remote_wakeup=1;
pusb_intf->needs_remote_wakeup = 1;
device_init_wakeup(&pusb_intf->dev, 1);
DBG_871X("pwrctrlpriv.bSupportRemoteWakeup~~~~~~\n");
DBG_871X("pwrctrlpriv.bSupportRemoteWakeup~~~[%d]~~~\n",device_may_wakeup(&pusb_intf->dev));
}
#endif
#endif
#ifdef CONFIG_AUTOSUSPEND
if( padapter->registrypriv.power_mgnt != PS_MODE_ACTIVE )
{
if(padapter->registrypriv.usbss_enable ){ /* autosuspend (2s delay) */
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,38))
dvobj->pusbdev->dev.power.autosuspend_delay = 0 * HZ;//15 * HZ; idle-delay time
#else
dvobj->pusbdev->autosuspend_delay = 0 * HZ;//15 * HZ; idle-delay time
#endif
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,35))
usb_enable_autosuspend(dvobj->pusbdev);
#elif (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,22) && LINUX_VERSION_CODE<=KERNEL_VERSION(2,6,34))
padapter->bDisableAutosuspend = dvobj->pusbdev->autosuspend_disabled ;
dvobj->pusbdev->autosuspend_disabled = 0;//autosuspend disabled by the user
#endif
//usb_autopm_get_interface(adapter_to_dvobj(padapter)->pusbintf );//init pm_usage_cnt ,let it start from 1
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,32))
DBG_871X("%s...pm_usage_cnt(%d).....\n",__FUNCTION__,atomic_read(&(dvobj->pusbintf ->pm_usage_cnt)));
#else
DBG_871X("%s...pm_usage_cnt(%d).....\n",__FUNCTION__,dvobj->pusbintf ->pm_usage_cnt);
#endif
}
}
#endif
//2012-07-11 Move here to prevent the 8723AS-VAU BT auto suspend influence
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,33))
if (usb_autopm_get_interface(pusb_intf) < 0)
{
DBG_871X( "can't get autopm: \n");
}
#endif
#ifdef CONFIG_BT_COEXIST
dvobj_to_pwrctl(dvobj)->autopm_cnt=1;
#endif
// set mac addr
rtw_macaddr_cfg(padapter->eeprompriv.mac_addr);
#ifdef CONFIG_P2P
rtw_init_wifidirect_addrs(padapter, padapter->eeprompriv.mac_addr, padapter->eeprompriv.mac_addr);
#endif // CONFIG_P2P
DBG_871X("bDriverStopped:%d, bSurpriseRemoved:%d, bup:%d, hw_init_completed:%d\n"
, padapter->bDriverStopped
, padapter->bSurpriseRemoved
, padapter->bup
, padapter->hw_init_completed
);
status = _SUCCESS;
free_hal_data:
if(status != _SUCCESS && padapter->HalData)
rtw_mfree(padapter->HalData, sizeof(*(padapter->HalData)));
free_wdev:
if(status != _SUCCESS) {
#ifdef CONFIG_IOCTL_CFG80211
rtw_wdev_unregister(padapter->rtw_wdev);
rtw_wdev_free(padapter->rtw_wdev);
#endif
}
handle_dualmac:
if (status != _SUCCESS)
rtw_handle_dualmac(padapter, 0);
free_adapter:
if (status != _SUCCESS) {
if (pnetdev)
rtw_free_netdev(pnetdev);
else
rtw_vmfree((u8*)padapter, sizeof(*padapter));
padapter = NULL;
}
exit:
return padapter;
}
static void rtw_usb_if1_deinit(_adapter *if1)
{
struct pwrctrl_priv *pwrctl = adapter_to_pwrctl(if1);
struct net_device *pnetdev = if1->pnetdev;
struct mlme_priv *pmlmepriv= &if1->mlmepriv;
if(check_fwstate(pmlmepriv, _FW_LINKED))
rtw_disassoc_cmd(if1, 0, _FALSE);
#ifdef CONFIG_AP_MODE
free_mlme_ap_info(if1);
#ifdef CONFIG_HOSTAPD_MLME
hostapd_mode_unload(if1);
#endif
#endif
rtw_cancel_all_timer(if1);
#ifdef CONFIG_WOWLAN
pwrctl->wowlan_mode=_FALSE;
#endif //CONFIG_WOWLAN
rtw_dev_unload(if1);
DBG_871X("+r871xu_dev_remove, hw_init_completed=%d\n", if1->hw_init_completed);
rtw_handle_dualmac(if1, 0);
#ifdef CONFIG_IOCTL_CFG80211
if(if1->rtw_wdev) {
rtw_wdev_free(if1->rtw_wdev);
}
#endif
#ifdef CONFIG_BT_COEXIST
if(1 == pwrctl->autopm_cnt){
#if (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,33))
usb_autopm_put_interface(adapter_to_dvobj(if1)->pusbintf);
#elif (LINUX_VERSION_CODE>=KERNEL_VERSION(2,6,20))
usb_autopm_enable(adapter_to_dvobj(if1)->pusbintf);
#else
usb_autosuspend_device(adapter_to_dvobj(if1)->pusbdev, 1);
#endif
pwrctl->autopm_cnt --;
}
#endif
rtw_free_drv_sw(if1);
if(pnetdev)
rtw_free_netdev(pnetdev);
#ifdef CONFIG_PLATFORM_RTD2880B
DBG_871X("wlan link down\n");
rtd2885_wlan_netlink_sendMsg("linkdown", "8712");
#endif
}
static int rtw_drv_init(struct usb_interface *pusb_intf, const struct usb_device_id *pdid)
{
_adapter *if1 = NULL, *if2 = NULL;
int status = _FAIL;
struct dvobj_priv *dvobj;
#ifdef CONFIG_MULTI_VIR_IFACES
int i;
#endif //CONFIG_MULTI_VIR_IFACES
RT_TRACE(_module_hci_intfs_c_, _drv_err_, ("+rtw_drv_init\n"));
//DBG_871X("+rtw_drv_init\n");
//step 0.
process_spec_devid(pdid);
/* Initialize dvobj_priv */
if ((dvobj = usb_dvobj_init(pusb_intf)) == NULL) {
RT_TRACE(_module_hci_intfs_c_, _drv_err_, ("initialize device object priv Failed!\n"));
goto exit;
}
if ((if1 = rtw_usb_if1_init(dvobj, pusb_intf, pdid)) == NULL) {
DBG_871X("rtw_usb_if1_init Failed!\n");
goto free_dvobj;
}
#ifdef CONFIG_CONCURRENT_MODE
if((if2 = rtw_drv_if2_init(if1, usb_set_intf_ops)) == NULL) {
goto free_if1;
}
#ifdef CONFIG_MULTI_VIR_IFACES
for(i=0; i<if1->registrypriv.ext_iface_num;i++)
{
if(rtw_drv_add_vir_if(if1, usb_set_intf_ops) == NULL)
{
DBG_871X("rtw_drv_add_iface failed! (%d)\n", i);
goto free_if2;
}
}
#endif //CONFIG_MULTI_VIR_IFACES
#endif
#ifdef CONFIG_INTEL_PROXIM
rtw_sw_export=if1;
#endif
#ifdef CONFIG_GLOBAL_UI_PID
if(ui_pid[1]!=0) {
DBG_871X("ui_pid[1]:%d\n",ui_pid[1]);
rtw_signal_process(ui_pid[1], SIGUSR2);
}
#endif
//dev_alloc_name && register_netdev
if((status = rtw_drv_register_netdev(if1)) != _SUCCESS) {
goto free_if2;
}
#ifdef CONFIG_HOSTAPD_MLME
hostapd_mode_init(if1);
#endif
#ifdef CONFIG_PLATFORM_RTD2880B
DBG_871X("wlan link up\n");
rtd2885_wlan_netlink_sendMsg("linkup", "8712");
#endif
RT_TRACE(_module_hci_intfs_c_,_drv_err_,("-871x_drv - drv_init, success!\n"));
status = _SUCCESS;
free_if2:
if(status != _SUCCESS && if2) {
#ifdef CONFIG_CONCURRENT_MODE
rtw_drv_if2_stop(if2);
rtw_drv_if2_free(if2);
#endif
}
free_if1:
if (status != _SUCCESS && if1) {
rtw_usb_if1_deinit(if1);
}
free_dvobj:
if (status != _SUCCESS)
usb_dvobj_deinit(pusb_intf);
exit:
return status == _SUCCESS?0:-ENODEV;
}
/*
* dev_remove() - our device is being removed
*/
//rmmod module & unplug(SurpriseRemoved) will call r871xu_dev_remove() => how to recognize both
static void rtw_dev_remove(struct usb_interface *pusb_intf)
{
struct dvobj_priv *dvobj = usb_get_intfdata(pusb_intf);
struct pwrctrl_priv *pwrctl = dvobj_to_pwrctl(dvobj);
_adapter *padapter = dvobj->if1;
struct net_device *pnetdev = padapter->pnetdev;
struct mlme_priv *pmlmepriv= &padapter->mlmepriv;
_func_enter_;
DBG_871X("+rtw_dev_remove\n");
RT_TRACE(_module_hci_intfs_c_,_drv_err_,("+dev_remove()\n"));
dvobj->processing_dev_remove = _TRUE;
rtw_unregister_netdevs(dvobj);
if(usb_drv.drv_registered == _TRUE)
{
//DBG_871X("r871xu_dev_remove():padapter->bSurpriseRemoved == _TRUE\n");
padapter->bSurpriseRemoved = _TRUE;
}
/*else
{
//DBG_871X("r871xu_dev_remove():module removed\n");
padapter->hw_init_completed = _FALSE;
}*/
#if defined(CONFIG_HAS_EARLYSUSPEND) || defined(CONFIG_ANDROID_POWER)
rtw_unregister_early_suspend(pwrctl);
#endif
rtw_pm_set_ips(padapter, IPS_NONE);
rtw_pm_set_lps(padapter, PS_MODE_ACTIVE);
LeaveAllPowerSaveMode(padapter);
#ifdef CONFIG_CONCURRENT_MODE
#ifdef CONFIG_MULTI_VIR_IFACES
rtw_drv_stop_vir_ifaces(dvobj);
#endif //CONFIG_MULTI_VIR_IFACES
rtw_drv_if2_stop(dvobj->if2);
#endif //CONFIG_CONCURRENT_MODE
#ifdef CONFIG_BT_COEXIST
rtw_btcoex_HaltNotify(padapter);
#endif
rtw_usb_if1_deinit(padapter);
#ifdef CONFIG_CONCURRENT_MODE
#ifdef CONFIG_MULTI_VIR_IFACES
rtw_drv_free_vir_ifaces(dvobj);
#endif //CONFIG_MULTI_VIR_IFACES
rtw_drv_if2_free(dvobj->if2);
#endif //CONFIG_CONCURRENT_MODE
usb_dvobj_deinit(pusb_intf);
RT_TRACE(_module_hci_intfs_c_,_drv_err_,("-dev_remove()\n"));
DBG_871X("-r871xu_dev_remove, done\n");
#ifdef CONFIG_INTEL_PROXIM
rtw_sw_export=NULL;
#endif
_func_exit_;
return;
}
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24))
extern int console_suspend_enabled;
#endif
static int rtw_drv_entry(void)
{
int ret = 0;
DBG_871X_LEVEL(_drv_always_, "module init start\n");
dump_drv_version(RTW_DBGDUMP);
#ifdef BTCOEXVERSION
DBG_871X_LEVEL(_drv_always_, DRV_NAME" BT-Coex version = %s\n", BTCOEXVERSION);
#endif // BTCOEXVERSION
ret = platform_wifi_power_on();
if(ret != 0)
{
DBG_871X("%s: power on failed!!(%d)\n", __FUNCTION__, ret);
ret = -1;
goto exit;
}
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24))
//console_suspend_enabled=0;
#endif
usb_drv.drv_registered = _TRUE;
rtw_suspend_lock_init();
rtw_drv_proc_init();
rtw_ndev_notifier_register();
ret = usb_register(&usb_drv.usbdrv);
if (ret != 0) {
usb_drv.drv_registered = _FALSE;
rtw_suspend_lock_uninit();
rtw_drv_proc_deinit();
rtw_ndev_notifier_unregister();
goto exit;
}
exit:
DBG_871X_LEVEL(_drv_always_, "module init ret=%d\n", ret);
return ret;
}
static void rtw_drv_halt(void)
{
DBG_871X_LEVEL(_drv_always_, "module exit start\n");
usb_drv.drv_registered = _FALSE;
usb_deregister(&usb_drv.usbdrv);
platform_wifi_power_off();
rtw_suspend_lock_uninit();
rtw_drv_proc_deinit();
rtw_ndev_notifier_unregister();
DBG_871X_LEVEL(_drv_always_, "module exit success\n");
rtw_mstat_dump(RTW_DBGDUMP);
}
#include "wifi_version.h"
#include <linux/rfkill-wlan.h>
int rockchip_wifi_init_module(void)
{
printk("\n");
printk("=======================================================\n");
printk("==== Launching Wi-Fi driver! (Powered by Rockchip) ====\n");
printk("=======================================================\n");
printk("Realtek 8188EU USB WiFi driver (Powered by Rockchip,Ver %s) init.\n", RTL8192_DRV_VERSION);
rockchip_wifi_power(1);
return rtw_drv_entry();
}
void rockchip_wifi_exit_module(void)
{
printk("\n");
printk("=======================================================\n");
printk("==== Dislaunching Wi-Fi driver! (Powered by Rockchip) ====\n");
printk("=======================================================\n");
printk("Realtek 8188EU USB WiFi driver (Powered by Rockchip,Ver %s) init.\n", RTL8192_DRV_VERSION);
rtw_drv_halt();
rockchip_wifi_power(0);
}
EXPORT_SYMBOL(rockchip_wifi_init_module);
EXPORT_SYMBOL(rockchip_wifi_exit_module);
#ifdef CONFIG_INTEL_PROXIM
_adapter *rtw_usb_get_sw_pointer(void)
{
return rtw_sw_export;
}
EXPORT_SYMBOL(rtw_usb_get_sw_pointer);
#endif //CONFIG_INTEL_PROXIM
|
crewrktablets/rk3x_kernel_3.10
|
drivers/net/wireless/rockchip_wlan/rtl8188eu/os_dep/linux/usb_intf.c
|
C
|
gpl-2.0
| 62,999
|
/*
* Copyright (c) 2015, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.api.vm;
import com.oracle.truffle.api.profiles.SeparateClassloaderTestRunner;
import java.util.concurrent.Executors;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(SeparateClassloaderTestRunner.class)
public class ContextStoreProfileTest {
@Test
public void switchFromConstantToMultipleThreads() throws Exception {
final ContextStoreProfile profile = new ContextStoreProfile(null);
ContextStore store1 = new ContextStore(null, 0);
final ContextStore store2 = new ContextStore(null, 0);
profile.enter(store1);
assertEquals("Store associated", store1, profile.get());
final ContextStore[] check = {null};
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
profile.enter(store2);
check[0] = profile.get();
}
}).get();
assertEquals("Store on other thread associated", store2, check[0]);
assertEquals("1st thread store is still there", store1, profile.get());
}
@Test
public void switchFromDynamicToMultipleThreads() throws Exception {
final ContextStoreProfile profile = new ContextStoreProfile(null);
ContextStore store1 = new ContextStore(null, 0);
ContextStore store2 = new ContextStore(null, 0);
final ContextStore store3 = new ContextStore(null, 0);
profile.enter(store1);
assertEquals("Store associated", store1, profile.get());
profile.enter(store2);
assertEquals("Store associated", store2, profile.get());
final ContextStore[] check = {null};
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
profile.enter(store3);
check[0] = profile.get();
}
}).get();
assertEquals("Store on other thread associated", store3, check[0]);
assertEquals("1st thread store is still there", store2, profile.get());
}
}
|
chumer/truffle
|
truffle/com.oracle.truffle.api.test/src/com/oracle/truffle/api/vm/ContextStoreProfileTest.java
|
Java
|
gpl-2.0
| 3,176
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_71) on Fri Feb 27 16:43:20 EST 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Deprecated List (Solr 4.10.4 API)</title>
<meta name="date" content="2015-02-27">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Deprecated List (Solr 4.10.4 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li>
<li><a href="deprecated-list.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Deprecated API" class="title">Deprecated API</h1>
<h2 title="Contents">Contents</h2>
<ul>
<li><a href="#interface">Deprecated Interfaces</a></li>
<li><a href="#class">Deprecated Classes</a></li>
<li><a href="#field">Deprecated Fields</a></li>
<li><a href="#method">Deprecated Methods</a></li>
<li><a href="#constructor">Deprecated Constructors</a></li>
</ul>
</div>
<div class="contentContainer"><a name="interface">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Deprecated Interfaces table, listing deprecated interfaces, and an explanation">
<caption><span>Deprecated Interfaces</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Interface and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/common/ResourceLoader.html" title="interface in org.apache.solr.common">org.apache.solr.common.ResourceLoader</a>
<div class="block"><i>This interface has been kept for backwards compatibility and will
be removed in (5.0). Use <a href="http://lucene.apache.org/core/4_10_4/analyzers-common/org/apache/lucene/analysis/util/ResourceLoader.html?is-external=true" title="class or interface in org.apache.lucene.analysis.util"><code>ResourceLoader</code></a></i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/util/plugin/ResourceLoaderAware.html" title="interface in org.apache.solr.util.plugin">org.apache.solr.util.plugin.ResourceLoaderAware</a>
<div class="block"><i>This interface has been kept for backwards compatibility and will
be removed in (5.0). Use <a href="http://lucene.apache.org/core/4_10_4/analyzers-common/org/apache/lucene/analysis/util/ResourceLoaderAware.html?is-external=true" title="class or interface in org.apache.lucene.analysis.util"><code>ResourceLoaderAware</code></a>.</i></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="class">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Deprecated Classes table, listing deprecated classes, and an explanation">
<caption><span>Deprecated Classes</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/schema/BCDIntField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.BCDIntField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieIntField.html" title="class in org.apache.solr.schema"><code>TrieIntField</code></a> instead</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/schema/BCDLongField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.BCDLongField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieLongField.html" title="class in org.apache.solr.schema"><code>TrieLongField</code></a> instead</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/schema/BCDStrField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.BCDStrField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieIntField.html" title="class in org.apache.solr.schema"><code>TrieIntField</code></a> instead</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/util/BCDUtils.html" title="class in org.apache.solr.util">org.apache.solr.util.BCDUtils</a>
<div class="block"><i>this class will be removed in 5.0</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/handler/BinaryUpdateRequestHandler.html" title="class in org.apache.solr.handler">org.apache.solr.handler.BinaryUpdateRequestHandler</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/schema/ByteField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.ByteField</a>
<div class="block"><i>Use <a href="org/apache/solr/schema/TrieIntField.html" title="class in org.apache.solr.schema"><code>TrieIntField</code></a> instead.</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/handler/CSVRequestHandler.html" title="class in org.apache.solr.handler">org.apache.solr.handler.CSVRequestHandler</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/schema/DateField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.DateField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieDateField.html" title="class in org.apache.solr.schema"><code>TrieDateField</code></a> instead</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/schema/DoubleField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.DoubleField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieDoubleField.html" title="class in org.apache.solr.schema"><code>TrieDoubleField</code></a> instead</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/schema/FloatField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.FloatField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieFloatField.html" title="class in org.apache.solr.schema"><code>TrieFloatField</code></a> instead</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/schema/IntField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.IntField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieIntField.html" title="class in org.apache.solr.schema"><code>TrieIntField</code></a> instead</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/handler/JsonUpdateRequestHandler.html" title="class in org.apache.solr.handler">org.apache.solr.handler.JsonUpdateRequestHandler</a></td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/analysis/LegacyHTMLStripCharFilter.html" title="class in org.apache.solr.analysis">org.apache.solr.analysis.LegacyHTMLStripCharFilter</a>
<div class="block"><i>use <a href="http://lucene.apache.org/core/4_10_4/analyzers-common/org/apache/lucene/analysis/charfilter/HTMLStripCharFilter.html?is-external=true" title="class or interface in org.apache.lucene.analysis.charfilter"><code>HTMLStripCharFilter</code></a></i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/analysis/LegacyHTMLStripCharFilterFactory.html" title="class in org.apache.solr.analysis">org.apache.solr.analysis.LegacyHTMLStripCharFilterFactory</a>
<div class="block"><i>use <a href="http://lucene.apache.org/core/4_10_4/analyzers-common/org/apache/lucene/analysis/charfilter/HTMLStripCharFilterFactory.html?is-external=true" title="class or interface in org.apache.lucene.analysis.charfilter"><code>HTMLStripCharFilterFactory</code></a></i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/schema/LongField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.LongField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieLongField.html" title="class in org.apache.solr.schema"><code>TrieLongField</code></a> instead</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/schema/ShortField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.ShortField</a>
<div class="block"><i>Use <a href="org/apache/solr/schema/TrieIntField.html" title="class in org.apache.solr.schema"><code>TrieIntField</code></a> instead.</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/schema/SortableDoubleField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.SortableDoubleField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieDoubleField.html" title="class in org.apache.solr.schema"><code>TrieDoubleField</code></a> instead</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/schema/SortableFloatField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.SortableFloatField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieFloatField.html" title="class in org.apache.solr.schema"><code>TrieFloatField</code></a> instead</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/schema/SortableIntField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.SortableIntField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieIntField.html" title="class in org.apache.solr.schema"><code>TrieIntField</code></a> instead</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/schema/SortableLongField.html" title="class in org.apache.solr.schema">org.apache.solr.schema.SortableLongField</a>
<div class="block"><i>this class will be removed in 5.0 - use <a href="org/apache/solr/schema/TrieLongField.html" title="class in org.apache.solr.schema"><code>TrieLongField</code></a> instead</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/handler/XmlUpdateRequestHandler.html" title="class in org.apache.solr.handler">org.apache.solr.handler.XmlUpdateRequestHandler</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/handler/XsltUpdateRequestHandler.html" title="class in org.apache.solr.handler">org.apache.solr.handler.XsltUpdateRequestHandler</a></td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="field">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Deprecated Fields table, listing deprecated fields, and an explanation">
<caption><span>Deprecated Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/core/ZkContainer.html#DEFAULT_HOST_CONTEXT">org.apache.solr.core.ZkContainer.DEFAULT_HOST_CONTEXT</a>
<div class="block"><i>will be remove in Solr 5.0 (SOLR-4622)</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/core/ZkContainer.html#DEFAULT_HOST_PORT">org.apache.solr.core.ZkContainer.DEFAULT_HOST_PORT</a>
<div class="block"><i>will be remove in Solr 5.0 (SOLR-4622)</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/core/SolrConfig.html#defaultIndexConfig">org.apache.solr.core.SolrConfig.defaultIndexConfig</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/core/SolrConfig.html#mainIndexConfig">org.apache.solr.core.SolrConfig.mainIndexConfig</a></td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/schema/DateField.html#MATH_LOCALE">org.apache.solr.schema.DateField.MATH_LOCALE</a>
<div class="block"><i>use DateMathParser.DEFAULT_MATH_LOCALE</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/schema/DateField.html#MATH_TZ">org.apache.solr.schema.DateField.MATH_TZ</a>
<div class="block"><i>use DateMathParser.DEFAULT_MATH_TZ</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/update/SolrIndexConfig.html#useCompoundFile">org.apache.solr.update.SolrIndexConfig.useCompoundFile</a>
<div class="block"><i>use <a href="org/apache/solr/update/SolrIndexConfig.html#getUseCompoundFile()"><code>SolrIndexConfig.getUseCompoundFile()</code></a></i></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="method">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Deprecated Methods table, listing deprecated methods, and an explanation">
<caption><span>Deprecated Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/analysis/SolrAnalyzer.html#charStream(java.io.Reader)">org.apache.solr.analysis.SolrAnalyzer.charStream(Reader)</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/schema/FieldType.html#getAnalyzer()">org.apache.solr.schema.FieldType.getAnalyzer()</a>
<div class="block"><i>(4.9) Use <a href="org/apache/solr/schema/FieldType.html#getIndexAnalyzer()"><code>FieldType.getIndexAnalyzer()</code></a> instead.</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/schema/IndexSchema.html#getAnalyzer()">org.apache.solr.schema.IndexSchema.getAnalyzer()</a>
<div class="block"><i>(4.9) Use <a href="org/apache/solr/schema/IndexSchema.html#getIndexAnalyzer()"><code>IndexSchema.getIndexAnalyzer()</code></a> instead.</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/update/processor/FieldMutatingUpdateProcessorFactory.html#getBooleanArg(org.apache.solr.common.util.NamedList,%20java.lang.String)">org.apache.solr.update.processor.FieldMutatingUpdateProcessorFactory.getBooleanArg(NamedList, String)</a>
<div class="block"><i>Use <a href="../solr-solrj/org/apache/solr/common/util/NamedList.html?is-external=true#removeBooleanArg(java.lang.String)" title="class or interface in org.apache.solr.common.util"><code>NamedList.removeBooleanArg(java.lang.String)</code></a> instead. Will be
removed in 5.0.</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/parser/CharStream.html#getColumn()">org.apache.solr.parser.CharStream.getColumn()</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/request/SimpleFacets.html#getFacetDateCounts()">org.apache.solr.request.SimpleFacets.getFacetDateCounts()</a>
<div class="block"><i>Use getFacetRangeCounts which is more generalized</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/request/SimpleFacets.html#getFacetDateCounts(java.lang.String,%20org.apache.solr.common.util.NamedList)">org.apache.solr.request.SimpleFacets.getFacetDateCounts(String, NamedList<Object>)</a>
<div class="block"><i>Use getFacetRangeCounts which is more generalized</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/handler/admin/LukeRequestHandler.html#getIndexInfo(org.apache.lucene.index.DirectoryReader,%20boolean)">org.apache.solr.handler.admin.LukeRequestHandler.getIndexInfo(DirectoryReader, boolean)</a>
<div class="block"><i>use <a href="org/apache/solr/handler/admin/LukeRequestHandler.html#getIndexInfo(org.apache.lucene.index.DirectoryReader)"><code>LukeRequestHandler.getIndexInfo(DirectoryReader)</code></a> since you now have to explicitly pass the "fl" prameter
and this was always called with "false" anyway from CoreAdminHandler</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/parser/CharStream.html#getLine()">org.apache.solr.parser.CharStream.getLine()</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/handler/MoreLikeThisHandler.MoreLikeThisHelper.html#getMoreLikeThese(org.apache.solr.search.DocList,%20int,%20int)">org.apache.solr.handler.MoreLikeThisHandler.MoreLikeThisHelper.getMoreLikeThese(DocList, int, int)</a></td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.html#getParsedResponse(org.apache.solr.request.SolrQueryRequest,%20org.apache.solr.response.SolrQueryResponse)">org.apache.solr.client.solrj.embedded.EmbeddedSolrServer.getParsedResponse(SolrQueryRequest, SolrQueryResponse)</a>
<div class="block"><i>use <a href="org/apache/solr/response/BinaryResponseWriter.html#getParsedResponse(org.apache.solr.request.SolrQueryRequest,%20org.apache.solr.response.SolrQueryResponse)"><code>BinaryResponseWriter.getParsedResponse(SolrQueryRequest, SolrQueryResponse)</code></a></i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/schema/DateField.html#getThreadLocalDateFormat()">org.apache.solr.schema.DateField.getThreadLocalDateFormat()</a>
<div class="block"><i>- use formatDate(Date) instead</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/handler/admin/CoreAdminHandler.html#handleAliasAction(org.apache.solr.request.SolrQueryRequest,%20org.apache.solr.response.SolrQueryResponse)">org.apache.solr.handler.admin.CoreAdminHandler.handleAliasAction(SolrQueryRequest, SolrQueryResponse)</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/highlight/DefaultSolrHighlighter.html#initalize(org.apache.solr.core.SolrConfig)">org.apache.solr.highlight.DefaultSolrHighlighter.initalize(SolrConfig)</a></td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/highlight/SolrHighlighter.html#initalize(org.apache.solr.core.SolrConfig)">org.apache.solr.highlight.SolrHighlighter.initalize(SolrConfig)</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/core/CoreContainer.html#isPersistent()">org.apache.solr.core.CoreContainer.isPersistent()</a></td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/schema/SchemaField.html#omitTf()">org.apache.solr.schema.SchemaField.omitTf()</a>
<div class="block"><i>Use <a href="org/apache/solr/schema/SchemaField.html#omitTermFreqAndPositions()"><code>SchemaField.omitTermFreqAndPositions()</code></a></i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/update/processor/FieldMutatingUpdateProcessorFactory.html#oneOrMany(org.apache.solr.common.util.NamedList,%20java.lang.String)">org.apache.solr.update.processor.FieldMutatingUpdateProcessorFactory.oneOrMany(NamedList, String)</a>
<div class="block"><i>Replaced by <a href="../solr-solrj/org/apache/solr/common/util/NamedList.html?is-external=true#removeConfigArgs(java.lang.String)" title="class or interface in org.apache.solr.common.util"><code>NamedList.removeConfigArgs(String)</code></a>. Will be
removed in version 5.0.</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/search/QueryParsing.html#parseSort(java.lang.String,%20org.apache.solr.request.SolrQueryRequest)">org.apache.solr.search.QueryParsing.parseSort(String, SolrQueryRequest)</a>
<div class="block"><i>use <a href="org/apache/solr/search/QueryParsing.html#parseSortSpec(java.lang.String,%20org.apache.solr.request.SolrQueryRequest)"><code>QueryParsing.parseSortSpec(java.lang.String, org.apache.solr.request.SolrQueryRequest)</code></a></i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/request/SimpleFacets.html#rangeCount(org.apache.solr.schema.SchemaField,%20java.util.Date,%20java.util.Date,%20boolean,%20boolean)">org.apache.solr.request.SimpleFacets.rangeCount(SchemaField, Date, Date, boolean, boolean)</a>
<div class="block"><i>Use rangeCount(SchemaField,String,String,boolean,boolean) which is more generalized</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/core/SolrCore.html#reload(org.apache.solr.core.ConfigSet,%20org.apache.solr.core.SolrCore)">org.apache.solr.core.SolrCore.reload(ConfigSet, SolrCore)</a>
<div class="block"><i>Use <a href="org/apache/solr/core/SolrCore.html#reload(org.apache.solr.core.ConfigSet)"><code>SolrCore.reload(ConfigSet)</code></a></i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/schema/FieldType.html#setAnalyzer(org.apache.lucene.analysis.Analyzer)">org.apache.solr.schema.FieldType.setAnalyzer(Analyzer)</a>
<div class="block"><i>(4.9) Use <a href="org/apache/solr/schema/FieldType.html#setIndexAnalyzer(org.apache.lucene.analysis.Analyzer)"><code>FieldType.setIndexAnalyzer(org.apache.lucene.analysis.Analyzer)</code></a> instead.</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/search/SortSpec.html#setSort(org.apache.lucene.search.Sort)">org.apache.solr.search.SortSpec.setSort(Sort)</a>
<div class="block"><i>use <a href="org/apache/solr/search/SortSpec.html#setSortAndFields(org.apache.lucene.search.Sort,%20java.util.List)"><code>SortSpec.setSortAndFields(org.apache.lucene.search.Sort, java.util.List<org.apache.solr.schema.SchemaField>)</code></a></i></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="constructor">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Deprecated Constructors table, listing deprecated constructors, and an explanation">
<caption><span>Deprecated Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/internal/csv/CSVParser.html#CSVParser(java.io.Reader,%20char)">org.apache.solr.internal.csv.CSVParser(Reader, char)</a>
<div class="block"><i>use <a href="org/apache/solr/internal/csv/CSVParser.html#CSVParser(java.io.Reader,%20org.apache.solr.internal.csv.CSVStrategy)"><code>CSVParser.CSVParser(Reader,CSVStrategy)</code></a>.</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/internal/csv/CSVParser.html#CSVParser(java.io.Reader,%20char,%20char,%20char)">org.apache.solr.internal.csv.CSVParser(Reader, char, char, char)</a>
<div class="block"><i>use <a href="org/apache/solr/internal/csv/CSVParser.html#CSVParser(java.io.Reader,%20org.apache.solr.internal.csv.CSVStrategy)"><code>CSVParser.CSVParser(Reader,CSVStrategy)</code></a>.</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/internal/csv/CSVStrategy.html#CSVStrategy(char,%20char,%20char,%20boolean,%20boolean,%20boolean)">org.apache.solr.internal.csv.CSVStrategy(char, char, char, boolean, boolean, boolean)</a>
<div class="block"><i>Use <a href="org/apache/solr/internal/csv/CSVStrategy.html#CSVStrategy(char,%20char,%20char,%20char,%20boolean,%20boolean,%20boolean,%20boolean)"><code>CSVStrategy.CSVStrategy(char, char, char, char, boolean, boolean, boolean, boolean)</code></a></i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.html#EmbeddedSolrServer(org.apache.solr.core.SolrCore)">org.apache.solr.client.solrj.embedded.EmbeddedSolrServer(SolrCore)</a>
<div class="block"><i>use <a href="org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.html#EmbeddedSolrServer(org.apache.solr.core.CoreContainer,%20java.lang.String)"><code>EmbeddedSolrServer.EmbeddedSolrServer(CoreContainer, String)</code></a> instead.</i></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/solr/search/SortSpec.html#SortSpec(org.apache.lucene.search.Sort,%20int)">org.apache.solr.search.SortSpec(Sort, int)</a>
<div class="block"><i>Specify both Sort and SchemaField[] when constructing</i></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/solr/search/SortSpec.html#SortSpec(org.apache.lucene.search.Sort,%20int,%20int)">org.apache.solr.search.SortSpec(Sort, int, int)</a>
<div class="block"><i>Specify both Sort and SchemaField[] when constructing</i></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li>
<li><a href="deprecated-list.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='/prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
|
ashrafmhd09/openpublish
|
solr-4.10.4/docs/solr-core/deprecated-list.html
|
HTML
|
gpl-2.0
| 27,622
|
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<linux/unistd.h>
/*
* Test the seek file operation on a file whose name is given as the first
* argument.
*/
int main(int argc, char **argv)
{
int fd;
int rc;
if( argc != 2 ) {
printf("usage: %s filename\n", argv[0]);
exit(2);
}
fd = open(argv[1], O_RDONLY, 0);
if(fd == -1) {
perror("test_seek:open");
exit(2);
}
rc = lseek(fd, 10, SEEK_SET);
if( rc == -1 ) {
perror("test_seek:lseek");
close(fd);
exit(1);
}
close(fd);
exit(0);
}
|
SELinuxProject/selinux-testsuite
|
tests/file/test_seek.c
|
C
|
gpl-2.0
| 594
|
#
# arch/arm/Makefile
#
# This file is included by the global makefile so that you can add your own
# architecture-specific flags and dependencies.
#
# This file is subject to the terms and conditions of the GNU General Public
# License. See the file "COPYING" in the main directory of this archive
# for more details.
#
# Copyright (C) 1995-2001 by Russell King
LDFLAGS_vmlinux :=-p --no-undefined -X
ifeq ($(CONFIG_CPU_ENDIAN_BE8),y)
LDFLAGS_vmlinux += --be8
endif
OBJCOPYFLAGS :=-O binary -R .note -R .note.gnu.build-id -R .comment -S
GZFLAGS :=-9
#KBUILD_CFLAGS +=-pipe
# Explicitly specifiy 32-bit ARM ISA since toolchain default can be -mthumb:
KBUILD_CFLAGS +=$(call cc-option,-marm,)
# Do not use arch/arm/defconfig - it's always outdated.
# Select a platform tht is kept up-to-date
KBUILD_DEFCONFIG := versatile_defconfig
# defines filename extension depending memory management type.
ifeq ($(CONFIG_MMU),)
MMUEXT := -nommu
endif
ifeq ($(CONFIG_FRAME_POINTER),y)
KBUILD_CFLAGS +=-fno-omit-frame-pointer -mapcs -mno-sched-prolog
endif
ifeq ($(CONFIG_CPU_BIG_ENDIAN),y)
KBUILD_CPPFLAGS += -mbig-endian
AS += -EB
LD += -EB
else
KBUILD_CPPFLAGS += -mlittle-endian
AS += -EL
LD += -EL
endif
comma = ,
# This selects which instruction set is used.
# Note that GCC does not numerically define an architecture version
# macro, but instead defines a whole series of macros which makes
# testing for a specific architecture or later rather impossible.
arch-$(CONFIG_CPU_32v7) :=-D__LINUX_ARM_ARCH__=7 $(call cc-option,-march=armv7-a,-march=armv5t -Wa$(comma)-march=armv7-a)
arch-$(CONFIG_CPU_32v6) :=-D__LINUX_ARM_ARCH__=6 $(call cc-option,-march=armv6,-march=armv5t -Wa$(comma)-march=armv6)
# Only override the compiler option if ARMv6. The ARMv6K extensions are
# always available in ARMv7
ifeq ($(CONFIG_CPU_32v6),y)
arch-$(CONFIG_CPU_32v6K) :=-D__LINUX_ARM_ARCH__=6 $(call cc-option,-march=armv6k,-march=armv5t -Wa$(comma)-march=armv6k)
endif
arch-$(CONFIG_CPU_32v5) :=-D__LINUX_ARM_ARCH__=5 $(call cc-option,-march=armv5te,-march=armv4t)
arch-$(CONFIG_CPU_32v4T) :=-D__LINUX_ARM_ARCH__=4 -march=armv4t
arch-$(CONFIG_CPU_32v4) :=-D__LINUX_ARM_ARCH__=4 -march=armv4
arch-$(CONFIG_CPU_32v3) :=-D__LINUX_ARM_ARCH__=3 -march=armv3
# This selects how we optimise for the processor.
tune-$(CONFIG_CPU_ARM610) :=-mtune=arm610
tune-$(CONFIG_CPU_ARM710) :=-mtune=arm710
tune-$(CONFIG_CPU_ARM7TDMI) :=-mtune=arm7tdmi
tune-$(CONFIG_CPU_ARM720T) :=-mtune=arm7tdmi
tune-$(CONFIG_CPU_ARM740T) :=-mtune=arm7tdmi
tune-$(CONFIG_CPU_ARM9TDMI) :=-mtune=arm9tdmi
tune-$(CONFIG_CPU_ARM940T) :=-mtune=arm9tdmi
tune-$(CONFIG_CPU_ARM946E) :=$(call cc-option,-mtune=arm9e,-mtune=arm9tdmi)
tune-$(CONFIG_CPU_ARM920T) :=-mtune=arm9tdmi
tune-$(CONFIG_CPU_ARM922T) :=-mtune=arm9tdmi
tune-$(CONFIG_CPU_ARM925T) :=-mtune=arm9tdmi
tune-$(CONFIG_CPU_ARM926T) :=-mtune=arm9tdmi
tune-$(CONFIG_CPU_FA526) :=-mtune=arm9tdmi
tune-$(CONFIG_CPU_SA110) :=-mtune=strongarm110
tune-$(CONFIG_CPU_SA1100) :=-mtune=strongarm1100
tune-$(CONFIG_CPU_XSCALE) :=$(call cc-option,-mtune=xscale,-mtune=strongarm110) -Wa,-mcpu=xscale
tune-$(CONFIG_CPU_XSC3) :=$(call cc-option,-mtune=xscale,-mtune=strongarm110) -Wa,-mcpu=xscale
tune-$(CONFIG_CPU_FEROCEON) :=$(call cc-option,-mtune=marvell-f,-mtune=xscale)
tune-$(CONFIG_CPU_V6) :=$(call cc-option,-mtune=arm1136j-s,-mtune=strongarm)
ifeq ($(CONFIG_AEABI),y)
CFLAGS_ABI :=-mabi=aapcs-linux -mno-thumb-interwork
else
CFLAGS_ABI :=$(call cc-option,-mapcs-32,-mabi=apcs-gnu) $(call cc-option,-mno-thumb-interwork,)
endif
ifeq ($(CONFIG_ARM_UNWIND),y)
CFLAGS_ABI +=-funwind-tables
endif
ifeq ($(CONFIG_THUMB2_KERNEL),y)
AFLAGS_AUTOIT :=$(call as-option,-Wa$(comma)-mimplicit-it=thumb,-Wa$(comma)-mauto-it)
AFLAGS_NOWARN :=$(call as-option,-Wa$(comma)-mno-warn-deprecated,-Wa$(comma)-W)
CFLAGS_THUMB2 :=-mthumb $(AFLAGS_AUTOIT) $(AFLAGS_NOWARN)
AFLAGS_THUMB2 :=$(CFLAGS_THUMB2) -Wa$(comma)-mthumb
endif
# Need -Uarm for gcc < 3.x
KBUILD_CFLAGS +=$(CFLAGS_ABI) $(CFLAGS_THUMB2) $(arch-y) $(tune-y) $(call cc-option,-mshort-load-bytes,$(call cc-option,-malignment-traps,)) -msoft-float -Uarm
KBUILD_AFLAGS +=$(CFLAGS_ABI) $(AFLAGS_THUMB2) $(arch-y) $(tune-y) -include asm/unified.h -msoft-float
CHECKFLAGS += -D__arm__
#Default value
head-y := arch/arm/kernel/head$(MMUEXT).o arch/arm/kernel/init_task.o
textofs-y := 0x00408000
textofs-$(CONFIG_ARCH_CLPS711X) := 0x00028000
# SA1111 DMA bug: we don't want the kernel to live in precious DMA-able memory
ifeq ($(CONFIG_ARCH_SA1100),y)
textofs-$(CONFIG_SA1111) := 0x00208000
endif
# Machine directory name. This list is sorted alphanumerically
# by CONFIG_* macro name.
machine-$(CONFIG_ARCH_AAEC2000) := aaec2000
machine-$(CONFIG_ARCH_AT91) := at91
machine-$(CONFIG_ARCH_BCMRING) := bcmring
machine-$(CONFIG_ARCH_CLPS711X) := clps711x
machine-$(CONFIG_ARCH_DAVINCI) := davinci
machine-$(CONFIG_ARCH_EBSA110) := ebsa110
machine-$(CONFIG_ARCH_EP93XX) := ep93xx
machine-$(CONFIG_ARCH_GEMINI) := gemini
machine-$(CONFIG_ARCH_H720X) := h720x
machine-$(CONFIG_ARCH_INTEGRATOR) := integrator
machine-$(CONFIG_ARCH_IOP13XX) := iop13xx
machine-$(CONFIG_ARCH_IOP32X) := iop32x
machine-$(CONFIG_ARCH_IOP33X) := iop33x
machine-$(CONFIG_ARCH_IXP2000) := ixp2000
machine-$(CONFIG_ARCH_IXP23XX) := ixp23xx
machine-$(CONFIG_ARCH_IXP4XX) := ixp4xx
machine-$(CONFIG_ARCH_KIRKWOOD) := kirkwood
machine-$(CONFIG_ARCH_KS8695) := ks8695
machine-$(CONFIG_ARCH_L7200) := l7200
machine-$(CONFIG_ARCH_LH7A40X) := lh7a40x
machine-$(CONFIG_ARCH_LOKI) := loki
machine-$(CONFIG_ARCH_MMP) := mmp
machine-$(CONFIG_ARCH_MSM) := msm
machine-$(CONFIG_ARCH_MV78XX0) := mv78xx0
machine-$(CONFIG_ARCH_MX1) := mx1
machine-$(CONFIG_ARCH_MX2) := mx2
machine-$(CONFIG_ARCH_MX25) := mx25
machine-$(CONFIG_ARCH_MX3) := mx3
machine-$(CONFIG_ARCH_NETX) := netx
machine-$(CONFIG_ARCH_NOMADIK) := nomadik
machine-$(CONFIG_ARCH_NS9XXX) := ns9xxx
machine-$(CONFIG_ARCH_OMAP1) := omap1
machine-$(CONFIG_ARCH_OMAP2) := omap2
machine-$(CONFIG_ARCH_OMAP3) := omap2
machine-$(CONFIG_ARCH_OMAP4) := omap2
machine-$(CONFIG_ARCH_ORION5X) := orion5x
machine-$(CONFIG_ARCH_PNX4008) := pnx4008
machine-$(CONFIG_ARCH_PXA) := pxa
machine-$(CONFIG_ARCH_REALVIEW) := realview
machine-$(CONFIG_ARCH_RPC) := rpc
machine-$(CONFIG_ARCH_S3C2410) := s3c2410 s3c2400 s3c2412 s3c2440 s3c2442 s3c2443
machine-$(CONFIG_ARCH_S3C24A0) := s3c24a0
machine-$(CONFIG_ARCH_S3C64XX) := s3c6400 s3c6410
machine-$(CONFIG_ARCH_S5PC1XX) := s5pc100
machine-$(CONFIG_ARCH_SA1100) := sa1100
machine-$(CONFIG_ARCH_SHARK) := shark
machine-$(CONFIG_ARCH_STMP378X) := stmp378x
machine-$(CONFIG_ARCH_STMP37XX) := stmp37xx
machine-$(CONFIG_ARCH_U300) := u300
machine-$(CONFIG_ARCH_VERSATILE) := versatile
machine-$(CONFIG_ARCH_W90X900) := w90x900
machine-$(CONFIG_FOOTBRIDGE) := footbridge
machine-$(CONFIG_ARCH_MXC91231) := mxc91231
machine-$(CONFIG_ARCH_RK2818) := rk2818
machine-$(CONFIG_ARCH_RK29) := rk29
# Platform directory name. This list is sorted alphanumerically
# by CONFIG_* macro name.
plat-$(CONFIG_ARCH_MXC) := mxc
plat-$(CONFIG_ARCH_OMAP) := omap
plat-$(CONFIG_PLAT_IOP) := iop
plat-$(CONFIG_PLAT_ORION) := orion
plat-$(CONFIG_PLAT_PXA) := pxa
plat-$(CONFIG_PLAT_S3C24XX) := s3c24xx s3c
plat-$(CONFIG_PLAT_S3C64XX) := s3c64xx s3c
plat-$(CONFIG_PLAT_S5PC1XX) := s5pc1xx s3c
plat-$(CONFIG_ARCH_STMP3XXX) := stmp3xxx
ifeq ($(CONFIG_ARCH_EBSA110),y)
# This is what happens if you forget the IOCS16 line.
# PCMCIA cards stop working.
CFLAGS_3c589_cs.o :=-DISA_SIXTEEN_BIT_PERIPHERAL
export CFLAGS_3c589_cs.o
endif
# The byte offset of the kernel image in RAM from the start of RAM.
TEXT_OFFSET := $(textofs-y)
# The first directory contains additional information for the boot setup code
ifneq ($(machine-y),)
MACHINE := arch/arm/mach-$(word 1,$(machine-y))/
else
MACHINE :=
endif
machdirs := $(patsubst %,arch/arm/mach-%/,$(machine-y))
platdirs := $(patsubst %,arch/arm/plat-%/,$(plat-y))
ifeq ($(KBUILD_SRC),)
KBUILD_CPPFLAGS += $(patsubst %,-I%include,$(machdirs) $(platdirs))
else
KBUILD_CPPFLAGS += $(patsubst %,-I$(srctree)/%include,$(machdirs) $(platdirs))
endif
export TEXT_OFFSET GZFLAGS MMUEXT
# Do we have FASTFPE?
FASTFPE :=arch/arm/fastfpe
ifeq ($(FASTFPE),$(wildcard $(FASTFPE)))
FASTFPE_OBJ :=$(FASTFPE)/
endif
# If we have a machine-specific directory, then include it in the build.
core-y += arch/arm/kernel/ arch/arm/mm/ arch/arm/common/
core-y += $(machdirs) $(platdirs)
core-$(CONFIG_FPE_NWFPE) += arch/arm/nwfpe/
core-$(CONFIG_FPE_FASTFPE) += $(FASTFPE_OBJ)
core-$(CONFIG_VFP) += arch/arm/vfp/
drivers-$(CONFIG_OPROFILE) += arch/arm/oprofile/
libs-y := arch/arm/lib/ $(libs-y)
# Default target when executing plain make
ifeq ($(CONFIG_XIP_KERNEL),y)
KBUILD_IMAGE := xipImage
else
KBUILD_IMAGE := zImage
endif
all: $(KBUILD_IMAGE)
boot := arch/arm/boot
# Update machine arch and proc symlinks if something which affects
# them changed. We use .arch to indicate when they were updated
# last, otherwise make uses the target directory mtime.
archprepare: maketools
PHONY += maketools FORCE
maketools: include/linux/version.h FORCE
$(Q)$(MAKE) $(build)=arch/arm/tools include/asm-arm/mach-types.h
# Convert bzImage to zImage
bzImage: zImage
zImage Image xipImage bootpImage uImage: vmlinux
$(Q)$(MAKE) $(build)=$(boot) MACHINE=$(MACHINE) $(boot)/$@
zinstall install: vmlinux
$(Q)$(MAKE) $(build)=$(boot) MACHINE=$(MACHINE) $@
CLEAN_FILES += include/asm-arm/mach-types.h \
include/asm-arm/arch include/asm-arm/.arch
# We use MRPROPER_FILES and CLEAN_FILES now
archclean:
$(Q)$(MAKE) $(clean)=$(boot)
# My testing targets (bypasses dependencies)
bp:; $(Q)$(MAKE) $(build)=$(boot) MACHINE=$(MACHINE) $(boot)/bootpImage
i zi:; $(Q)$(MAKE) $(build)=$(boot) MACHINE=$(MACHINE) $@
PHONY += kernel.img
kernel.img: Image FORCE
$(Q)$(srctree)/mkkrnlimg $(obj)/arch/arm/boot/Image $(obj)/kernel.img
@echo ' Image: $@ is ready'
define archhelp
echo ' kernel.img - Rockchip kernel image'
echo '* zImage - Compressed kernel image (arch/$(ARCH)/boot/zImage)'
echo ' Image - Uncompressed kernel image (arch/$(ARCH)/boot/Image)'
echo '* xipImage - XIP kernel image, if configured (arch/$(ARCH)/boot/xipImage)'
echo ' uImage - U-Boot wrapped zImage'
echo ' bootpImage - Combined zImage and initial RAM disk'
echo ' (supply initrd image via make variable INITRD=<path>)'
echo ' install - Install uncompressed kernel'
echo ' zinstall - Install compressed kernel'
echo ' Install using (your) ~/bin/$(INSTALLKERNEL) or'
echo ' (distribution) /sbin/$(INSTALLKERNEL) or'
echo ' install to $$(INSTALL_PATH) and run lilo'
endef
|
joaompinto/kernel-2.6.32.27-M722HC
|
arch/arm/Makefile
|
Makefile
|
gpl-2.0
| 10,787
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.